Hello everyone,
I am currently taking CS50x thru Edx.org and was hoping someone would be kind enough to help explain something to me. Please keep in mind I have had zero experience in programming. My first weeks project was to write a code that would ask the user to input a number between 0 and 23 and then the code would build a half pyramid to the height the user stated starting with to hashes at the top.
Example: for 8 it would show
..............##
............###
..........####
........#####
......######
....#######
..########
#########
Except without the .'s. I couldn't get my spaces to stay put.
I did finally get it to work but getting the hashes to print was totally trial and error. Under //Print hash, I originally though h should equal 2 because I wanted to start with 2 hash marks but instead it was giving me 2 additional lines above my pyramid. So I started playing with that number just to see what would happen and got it to work with h = 0. I was hoping someone would be able to tell me why this is the case. I just need to understand why it works so I can learn from it. I hope I gave enough info. Thanks in advance.
------------------------------------------
Code:
#include <cs50.h>
#include <stdio.h>
int main(void)
{
// Declare variable for pyramid height
int height;
//Prompt user to enter pyramid height and make sure it is within the range
do
{
printf("Please enter a number between 0 and 23: ");
height = GetInt();
}
while (height < 0 || height > 23);
//Print pyramid
for (int i = 1; i <= height; i++)
{
//Print space
for (int s = height - i; s > 0; s--)
{
printf(" ");
}
//Print hash
for (int h = 0; h <= i; h++)
{
printf("#");
}
//Print new line
printf("\n");
}
}