Create an inverse triangle in the form of numbers (decreasing order)

By | November 23, 2024

We have to create an inverse triangle in the form of numbers (decreasing order).

Example:

If the user provide 5. The print 5, 5 times ; 4, 4 times and so on. As-
5  5  5  5  5  
4  4  4  4  
3  3  3  
2  2  
1

Implementation:
First we declare a variable – number and assign it with a value provided by user. Now we will use a loop (while or for) to repeat the numbers from number to 1 to create the inverse triangle design. This loop will continue till the number variable is having value greater than 0. Within the first loop, we have another loop , this loop will count and print the variable i from 1 till the value of number. As the inner loop ends, the cursor goes to the next line (i.e. new line) and the value of number is decremented by 1.

Code:

#include <iostream>
using namespace std;

int main()
{
    int number;
    cout<<"Enter your desired number : ";
    cin>>number;
    cout<<endl;

    while(number > 0)
    {
        for(int i=0 ; i<number ; i++)
        {
            cout<<" "<<number<<" ";
        }
        cout<<endl;  // to go to the next line
        number--;    // decrementing number when the inner loop is completed50
    }
    return 0;
}

Output:

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.