I started with mario.c from hacker1 problem set. I found a tricky and fast solution (when building up really high pyramids > 1000 rows) to build up the pyramids using printf's align functionallity combined with strcat function.
Code:
/**
* Program : mario.c
* Edition : hacker1
* Version : 2.0
* Author : Frank Geister
* Contact : [email protected]
* Description : prints out mario pyramids using printf align and strcat
*/
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#define MIN_HEIGTH 0
#define MAX_HEIGTH 23
int main (void)
{
int heigth = 0;
do
{
printf("Heigth: ");
heigth = GetInt();
}
while ((heigth < MIN_HEIGTH) || (heigth > MAX_HEIGTH));
//calculate max size of array to hold all hashes, 2 spaces and string terminator
char hashes[(MAX_HEIGTH * 2) + 3] = "#";
for (int i = 0; i < heigth; i++)
{
printf("%*s %-*s\n", heigth, hashes, heigth, hashes);
strcat(hashes, "#");
}
return 0;
}
However, I got two questions.
- Which output does check50 expect for heigth 2 and 23, program builds pyramids correctly?:
~/workspace/hacker1/ $ check50 2015.fall.hacker1.mario mario.c
...
:( handles a height of 2 correctly
\ expected output, but not " # # \n## ##\n"
:( handles a height of 23 correctly
\ expected output, but not " # # ..."
...
I'm an absolute beginner in C programming, normally I do a lot of Perl scripting and I don't have to care about memory segmentation faults, so my second question is, is the following statement correct and will the program add \0 automatically to the array?
//calculate max size of array to hold all hashes, 2 spaces and string terminator char hashes[(MAX_HEIGTH * 2) + 3] = "#";
Thanks a lot!
CS50 rocks :-)