Search code examples
c++loopsnumbersnested-loops

C++ Number Pattern Solution Using only Loops


Hello I tried searching the website to see if there are any similar questions, but I haven't found any. I do apologize if there is something similar. I'm supposed to code a sort of number pattern given an input as shown below without using lists, vectors, arrays, etc and only with loops (for, while, do-while)

Input: 5

Output:

 
1 2 3 4 5

2 2 3 4 5

3 3 3 4 5

4 4 4 4 5

5 5 5 5 5 

(without all the extra lines, but it wouldn't show up properly) I tried using the following code:

int count = 1;
int counter = 1;

while (count <= a) {
        cout << count << " ";
        count++;
    }
    cout << endl;
    for (int i = 1 + counter; i <= a; i++) {
        cout << i << " ";
        for (int k = i; k <= a; k++) 
            cout << k << " ";
        cout << endl;
        counter++;
    }

I get the output:

1 2 3
2 2 3
3 3

I do understand that my way of going about the question (using only two for loops) is incorrect, but I have no idea how to approach this problem. Any advice is greatly appreciated. Thank you!


Solution

  • You will have to print i i-1 times instead of once.

    int count = 1;
    int counter = 1;
    
    while (count <= a) {
        cout << count << " ";
        count++;
    }
    cout << endl;
    for (int i = 1 + counter; i <= a; i++) {
        for (int k = 1; k < i; k++) // print i (i-1) times
            cout << i << " ";
        for (int k = i; k <= a; k++) 
            cout << k << " ";
        cout << endl;
        counter++;
    }