Home > OS >  Reverse right angle triangle pattern with numbers and asterisks using for-loops in C
Reverse right angle triangle pattern with numbers and asterisks using for-loops in C

Time:09-23

first time posting here, I'd like help with getting the output of the code upside down while still using the for commands, below is the best I can put in a clarification.

Desired Output:                 Actual Output:

123456                            1*****
12345*                            12****
1234**                            123***
123***                            1234**
12****                            12345*
1*****                            123456

Code:

#include <iostream>

using namespace std;

int main() {
    int num, row, integ;

    cout << "Please enter size: ";
    cin >> integ;

    for (row = 1; row <= integ; row  ) {
        for (num = 1; num <= row; num  ) {
            cout << num;
        }
        for (; num <= integ; num  ) {
            cout << "*";
        }
        cout << endl;
    }
}

CodePudding user response:

first time answering here :).

change num <= row to num <= integ - row 1

CodePudding user response:

Let's try to understand what we require.

We want to display number followed by stars. The numbers should decrease in each iteration and stars should increase.

Iteration-1: display 1 to integ - 0 and 0 asterisk 
Iteration-2: display 1 to integ - 1 and 1 asterisk
Iteration-3: display 1 to integ - 2 and 2 asterisk
Iteration-4: display 1 to integ - 3 and 3 asterisk
...
and so on.

As you can see, in each iteration we need to display value from 1 to (integ - x) and x asterisk, where x will starts from zero and keep on increasing.

To put this logic in code:

int main() {
    int integ;

    cout << "Please enter size: ";
    cin >> integ;

    for(int i = 0; i < integ;   i) {
        for(int j = 0; j < integ;   j) {
            if(j < (integ-i)) {
                cout << j 1;
            } else {
                cout << '*';
            }
        }
        std::cout << '\n';
    }
}

And here is the output:

123456
12345*
1234**
123***
12****
1*****

Hope it helps.

  • Related