Learner
Learner

Reputation: 241

Translating a simple for loop into a while loop?

How can I write this same code with the while loop instead of the for loop?

int n;
cin >> n;

for (int i = 1; i <= n; i++) {
        for (int j = n; j >= i; j--) {
            cout << j;
        }
        cout << endl;
    }

This is my attempt, but it does not achieve the same affect. I'm not sure why.

int n;
cin >> n;
int i = 1;
int j = n;

    while (i <= n) {
        while (j >= i) {
            cout << j;
            j--;
        }
        i++;
        cout << endl;
    }

Upvotes: 1

Views: 57

Answers (1)

Claudi
Claudi

Reputation: 5416

You have to reset j before the while(j >= i) loop.

while (i <= n) {
    j = n;   //<<<<<<<< Reset j to the starting value
    while (j >= i) {
        cout << j;
        j--;
    }
    i++;
    cout << endl;
}

Upvotes: 1

Related Questions