Microcontroller Embedded C Programming Lecture 125| ‘for’ loop number pyramid exercise

  • Post author:
  • Post category:Blog

 

‘for’ loop number pyramid exercise

 

 

Exercise:

Write a program to print a number pyramid. You should print something like this, as shown in Figure 1.

number pyramid exercise
Figure 1. Output

 

Figure 1 shows the pattern you had to print at the output.

You have to ask the user to enter the height of the pyramid, and after that, you have to print in the above pattern. So, you have to do this exercise by using ‘for’ loops.

 

First, let me tell you the logic of how you should implement this.

number pyramid exercise
Figure 2. Implementation

 

You have to use a nested for loop here.

The first ‘for’ statement is the outer for loop and the second ‘for’ statement is inner for loop.

So, use the outer for loop to track the height and use the inner for loop to print the rows. Actually, this output is displayed row-by-row. 

The row-by-row printing is taken care of by the inner for loop and how long you should proceed is decided by the outer for loop.

 

Hints for this exercise

'for' loop number pyramid exercise
Figure 3. Hints

 

Consider two variables ‘i’ and ‘j’.  

Use the variable ‘i’ to track the pyramid’s height and use the variable ‘j’ to decide how many numbers you should print in a given row.

For example, if you consider the 6th line here. Currently, ‘i’ is 6; you should print j. Starting from ‘i’ up to 0, but not 0. So, like that, you have to decide. 

This exercise provides valuable hints to guide you through the process, ensuring a successful implementation. Dive into the article to see this program in action and gain a deeper understanding of ‘for’ loop usage in C programming.

I will implement this in the following article.

 

FastBit Embedded Brain Academy Courses

Click here: https://fastbitlab.com/course1

 

FastBitLab

The FastBit Embedded Brain Academy uses the power of internet to bring the online courses related to the field of embedded system programming, Real time operating system, Embedded Linux systems, etc at your finger tip with very low cost. Backed with strong experience of industry, we have produced lots of courses with the customer enrolment over 3000+ across 100+ countries.