So I have to write a program that when executed produces something like this:
the number after the 9th digit should be a 0 then start all over again from 1.
1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
12345678901
to make a triangle of sorts. But when I run my code it goes infinitely long.
#include <iostream>
usingnamespace std;
int main()
{
int n(0); // input number of rows
int x; // number of values in a row
cout << "Enter number of rows: ";
cin >> n;
n=1;
while( n<=10)
{
cout << n <<endl;
n++;
}
while(n>=10)
{
cout << n+(n%10) << endl;
}
return 0;
}
The previous while loop ends when n++ makes n equal to 11. That makes the condition in the next while loop always true.
1 2 3 4
while(n>=10)
{
cout << n+(n%10) << endl;
}
Edit: Not sure what's happening with n - do you mean to initialize it to 0 in the declaration statement? Then the user inputs a value for n, then it gets reset to 1?
The user is to input a value which is the number of rows they want to output then the loops should run to output that many times. I have n=1 because with while loops you need a variable to start with correct? I can get this to work with for loops but it needs to be done with while.
Yes, but if you overwrite what the user entered with 1, you won't know when to stop printing rows of numbers.
I would have a separate variable for the user's input, then two variables to control the row and column. The outer while loop would keep track of the row, the inner while loop would keep track of the column.
I think you still have an infinite loop there. If the user enters 5 - the first while condition will always be true - it just keeps incrementing n and printing out a single value of n on each row.
In the triangle shape, the number of digits printed in each row is equal to the number of the row, e.g. - row 1 only prints one digits, row 5 prints 5 digits. And the number of rows is tied to the number the user input. So this will work into the conditions of the loops.
Something like this
1 2 3 4 5 6 7 8 9 10 11
while the row <= user's choice //outer while
start at first column
while the column <= row // inner while
print digit (column%10)
increment column
// end inner while
output a newline
increment row
//end outer while