top of page
Search

C Coding - Building a Mario Pyramid

  • shivam07das
  • Aug 27, 2023
  • 2 min read

Today we are going to see how to code and display a right-aligned pyramid as depicted in the World 1-1 in Nintendo’s Super Mario Brothers video game. We are going to code using the C language and recreate the pyramid in text format using hashes ("#")

ree

Shown below is the C code that will accept a number from the user and print the pyramid of the same height

1. int main(void)
2. {
3.   int n  = get_int("Input: ");
4.     while (n < 1 || n > 8) {
5.       n  = get_int("height : ");
6.     }
7.   for(int i=1;i<=n; i++) {
8.     for(int r=1;r<=n; r++) {
9.         if (r <= n-i) {
10.           printf(" ");
11.        }
12.        else {
13.           printf("#");
14.        }
15.    }
16.   printf("\n");
17. }

The main idea behind the algorithm is as follows:

By looping through each row and column we can create a grid-like shape and pinpoint the exact areas where we need to place a hashtag and where we need to leave a blank space.

Let's now analyze the key sections of the code


Line 3 - 6: Gets the input for the height and makes sure that it is more than 1 and less than 8


Line 7: This outer for loop represents the number of rows in the grid i.e. the height of the pyramid


Line 8: This inner for loop represents the number of columns in the grid i.e. the width of the pyramid


Line 9 - 15: For the current row, as we move from left to right, If the current space in the column does not match up with the where the hashtag is supposed to be print a blank space (" ") and increment the column by 1. If it matches, then print a hashtag ("#").


The table below provides a clearer picture of the state of the program at each iteration though both the loops i.e. as it moves to to bottom and left to right in the given grid space

i

r

n-i

r <= n-i

print

1

1

6

true

" "

1

2

6

true

" "

...

1

7

6

false

"#"

2

1

5

true

" "

2

2

5

true

" "

...

2

6

5

false

" #"

2

7

5

false

"##"

...

Line 16: When your reach the end of the outer loop i.e. current row, print a newline ("\n") to move to the new row. This allows the program to move top to bottom


Now if you run the program with an input of 7, it will print the following output

            #
           ##
          ###
         ####
        #####
       ######
      #######

And that's it ! We have successfully written a program in C to print a Mario Pyramid !

 
 
 

Comments


@Aurea Ratio. Powered and secured by Wix

bottom of page