w3resource

C++ Exercises: Print a pyramid of digits as shown below for n number of lines

C++ For Loop: Exercise-49 with Solution

Write a C++ program to print a pyramid of digits as shown below for n number of lines.

    1                                                                                                         
   232                                                                                                        
  34543                                                                                                       
 4567654                                                                                                      
567898765

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

int main()
{
    int i, j, spc, n;
    cout << "\n\n Display the pattern like pyramid using digits:\n";
    cout << "---------------------------------------------------\n";
    cout << " Input the number of rows: ";
    cin >> n;
    for (i = 1; i <= n; i++) 
    {
        spc = n - i;
        while (spc-- > 0)
            cout << " ";
        for (j = i; j < 2 * i - 1; j++)
            cout << j;
        for (j = 2 * i - 1; j > i - 1; j--)
            cout << j;
        cout << endl;
    }
}

Sample Output:

 Display the pattern like pyramid using digits:                        
---------------------------------------------------                    
 Input the number of rows: 5                                           
    1                                                                  
   232                                                                 
  34543                                                                
 4567654                                                               
567898765 

Flowchart:

Flowchart: Print a pyramid of digits as shown below for n number of lines

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to display the pattern like pyramid using the alphabet.
Next: Write a program in C++ to print a pattern like highest numbers of columns appear in first row.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.

C++ Programming: Tips of the Day

What is the "-->" operator in C/C++?

--> is not an operator. It is in fact two separate operators, -- and >.

The conditional's code decrements x, while returning x's original (not decremented) value, and then compares the original value with 0 using the > operator.

To better understand, the statement could be written as follows:

while( (x--) > 0 )

Ref : https://bit.ly/3kOTBby





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook