user12909901
user12909901

Reputation:

Nested While loop not working (C++ problem)

I am trying to output a triangle sort of figure based on the user entered number. For example, if the user enters 3, the output should be:

1

12

123

but all I am getting is

1

2

3

what do I need to fix?

//File: digits.cpp
//Created by: Noah Bungart
//Created on: 02/16/2020

#include <iostream>
#include <cmath>
using namespace std;

int main(){

    int Rows;
    cout << "Enter number of rows: ";
    cin >> Rows;

    int i = 1;
    int j = 1;

    while (i <= Rows){
        while (j <= i){     //Should be iterating through j loop but isn't
            if (i < 10){
                cout << j;
            }
            if (i >= 10){
              cout << (j % 10); 
            }
            j++; 
        }
        cout << endl;
        i++; 
    }
    return(0);
}

Upvotes: 0

Views: 433

Answers (1)

Elton Viana
Elton Viana

Reputation: 301

You just forgot to "reset" the j variable.

Just add a j = 1; just after the i++ (or before the second while loop).

Upvotes: 1

Related Questions