I'm taking the CS50 course, and we're asked to create a program which takes an input (the total height of the pyramid) and outputs a pyramid of that height.
i.e Here’s how the program might work if the user inputs 8 when prompted:
$ ./mario
Height: 8
# #
## ##
### ###
#### ####
##### #####
###### ######
####### #######
######## ########
Here is my code:
#include <cs50.h>
#include <stdio.h>
void print_hashes(int width, int empty_space);
int main(void)
{
// Get height input between ranges 1 to 8 inclusive
int height;
do
{
height = get_int("Height: ");
}
while (height < 1 || height > 8);
// Loops through each row
for (int row = 1; row <= height; row++)
{
// Prints the left part of the pyramid, we need to print empty spaces before printing the hashes, so
// the width is equal to the height, amount of hashes printed is equal to the row, so amount of empty spaces is the width - row
print_hashes(height, height - row);
printf(" ");
// Prints the right part of the pyramid, we don't need to print empty spaces before printing hashes, so
// the width is equal to the amount of hashes, i.e the row and the amount of empty space is just 0
print_hashes(row, 0);
printf("\n");
}
}
void print_hashes(int width, int empty_space)
{
// Loops through the column in the row
for (int column = 0; column < width; column++)
{
// Checks if there needs to be an empty space within that column, if so print a space and if not print a hash
if (column < empty_space)
{
printf(" ");
}
else
{
printf("#");
}
}
}
I would like some feedback on my code and how I could improve it; things like readability, efficiency, etc.
Is my code easily understandable? Am I overdoing the comments? The reason I put a lot of comments is because in my experience, when looking at code days/weeks after writing it, I tend to forget what it does. So I wrote explanations so that I can easily understand the code in the future.
How do I improve the style, and are there any code conventions I'm not following? Can I optimize this to make it a faster process? Or maybe there's a better way to do the same thing? Basically, how do I improve my code?