Write a program in C that recreates a half-pyramid using hashes (#) for blocks. Prompt the user for the half-pyramid’s height and align the bottom-left corner of the half-pyramid with the left-hand edge of the terminal window.
/** * mario.c * * Koren Leslie Cohen * * Creates a Mario Pyramid. */ #include <stdio.h> #include <cs50.h> int main(void) { // declaring my variables int height; int all_rows; int space; int hash; // prompts user for integer until integer is 0 to 23 do { printf("Welcome to Mario! Please choose a number from 0 to 23:"); height = GetInt(); } while ((height < 0) || (height > 23)); // this is the loop that will create the number of rows in the pyramid entered by the user for (all_rows = 1; all_rows <= height; all_rows++) { for (space = (height - all_rows); space > 0; space--) { printf(" "); } for (hash = 1; hash <= (all_rows + 1); hash++) { printf("#"); } printf("\n"); } return 0; }
Result:
Latest posts by Koren Leslie Cohen (see all)
- PM Career Story - April 28, 2022
- How to Transition into Product Management - December 26, 2017
- What I’ve Learned in My First Few Months as a Product Manager - October 14, 2015
Tushar Mittal says
Thanks, worked like charm.
kohl says
(hash = 1; hash <= (all_rows + 1); hash++)
if you set int hash equal to 0 instead of one, you don't have to set the limit to all_rows +1
mac says
please am new to programming. can some one explain to me the above program and how the for loops work
That Guy says
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Mando says
For the initialization and conditions of the nested for loops, why subtract height by row? Also what will the original “all_rows” loop do?
sarah says
Thanks for posting this. But please also explain in steps because we are new to these kind of projects,
That Guy says
Maybe you should take Intro to computer Science? You take it free here: https://prod-edx-mktg-edit.edx.org/course/introduction-computer-science-harvardx-cs50x
Akash says
can you please explain
for (hash = 1; hash <= (all_rows + 1); hash++)
Lawrence Hardy says
I am taking this class Harvard CS50 online, I wanted some commentary on my loops. However after reading your code. I would appreciate some information on your Mario For loop.
B says
would you consider consulting this violating academic honesty?
B says
this class is really hard I feel like i can’t do it without consulting outside sources
silvia says
I regret saying that I gave up developping this code on my own (it’s my first week programming) and copied-pasted yours. Why does it always tell me (in mine) that I have one single error: “mario2.c:7:1: error: expected identifier or ‘(‘ “?? How can I check it?
Gautam Bharath says
Hello Koren Leslie Cohen,
Thank you for this. It is very helpful.