Finally , I make mario !!
Tue 02 July 2013The Source Code Explained
After slogging for nearly a week , just right now I finally solved mario , from pset1. The problem consisted of printing out half-pyramids of a specific height, provided by the user. The output of the problem had to look something like this:-
Height: 8Now take a look at source code , here:-
## ### #### ##### ###### ####### ######## #########
Warning:- This is a spoiler for other people still trying on mario.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
//Getting User Input-
int height;
do
{
printf("Height: ");
height = GetInt();
}
while( (height <= 1) || (height > 23) );
for(int i = 1; i <= height; i++)
{
//print spaces
for(int s = height-i ;s > 0; s--)
{
printf(" ");
}
//print hashes
for(int j = 0;j <= i; j++)
{
printf("#");
}
//print new_line
printf("\n");
}
printf("For loop has finished printing !! \n");
return 0;
}
First Block , Getting User Input :-
int height;
do
{
printf(“Height: “);
height = GetInt();
}
while( (height \<= 1) || (height > 23)
);
The first block of code consists of the DO-WHILE loop , which prompts for user input. The loop will not exit until the user enters a number between 2 and 23.
The main block , generating half-pyramid :-
for(int i = 1; i \<= height; i++)
{
//print spaces
for(int s = height-i ;s > 0; s—)
{
printf(” “);
}
//print hashes
for(int j = 0;j \<= i; j++)
{
printf(“#”);
}
//print new_line
printf(“\n”);
}
The algorithm I used to generate the half pyramid was as follows :-
- A for loop for automating the generation of each line.
- A for loop for generating spaces in each line.
- A for loop for generating hashes in each line.
- Printing new line after the spaces and sharps have been printed.
Now the first for loops repeats itself for the height specified , which means it will generate the pattern for each line. I have also used the iterator “i” as a reference to line number, that’s why ‘i’ has been initialized as 1.
The second for loop is used to print spaces. The logic used here is -
Number
of spaces in each line = height specified - number of line
//Decrementing by one in each line
Now basically, the loop will repeat itself on the same line again and again , thereby printing spaces as it completes.
The third for loop is used to print sharps.The logic used here is -
Number
of hashes in each line = two at first line , increment by one with each line
After printing out hashes we need to have a new line , before our main for loop repeats again and to do that we use “\n ”
And folks that’s mario for you. Make sure your main returns.
PS :-* If you are following the hacker edition pset then after the for loop printing first set of sharps you will need to add a tab space by printing out \t character. And then repeat the for loop for printing the hashes exactly as it was.
Comments