Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

c++ Write a program that reads a positive odd whole number n and prints a pyrami

ID: 3800011 • Letter: C

Question

c++

Write a program  that reads a positive odd whole number n and prints a pyramid where the last row contains all numbers from n down to 1 (i.e., descending order), the second to last row displays all numbers from n – 1 down to 2, the third to last row displays all numbers from n – 2 down to 3, etc. The first row will contain only a single value, i.e. the middle value in the range, i.e. n down to 1. Each successive row contains two more values than the previous row. Note: the Pyramid of digits should not be in the middle of the page but on the left-most side.

For example, if n is 9, then the program will output: 654 7 65 43 87 654 32 9 8765 4321 If n is 13, then the program will output: 876 98765 0987 654 109 876543 210 987 65 432 32 109 8765 4321

Explanation / Answer

Code

#include <iostream>
using namespace std;
int main()
{
int i,space,rows,j,k=0;
cout<<"Enter the number of rows: ";
cin>>rows;
//to get the middle value from the given input
rows = (rows+1)/2;
cout<<" ";
for(i=1;i<=rows;++i){
//loop for printing spaces in each line
for(space=1;space<=rows-i;++space){
cout<<" ";
}
//loop for printing numbers in each line   
for(j=0,k=rows+i;j<(i*2)-1;++j){
cout<<--k << " ";
       }
       cout<<" ";
}
return 0;
}

output

Enter the number of rows: 5

3
4 3 2
5 4 3 2 1

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote