Which loop would I use

Newbie here.
I'm looking for help dealing with a problem and I don't know exactly how to start it, so any advice would be greatly appreciated.
I have to write a program in which it reads a positive integer from the user and then prints it out in a triangle formation.

Ex: *User inputs 3*
Output:
1
12
123

It seems so simple but it's also giving me a headache as I am not quite sure which type of loop to use.

Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

int main ()
{
int x;
cout << "Please enter an integer: " << endl;


while (cin >> x)
{
for(int i =1; i < x-1; i++)
{
cout << i;
}
cout << "\n";
for(int i = 1; i < x; i++)
{
cout << i;
}
cout << "\n";
for(int i = 1; i < x+1; i++)
{
cout << i;
}
}
return 0;
}


I know this is clearly the wrong way to do it, cause this only works if the user entered a pretty low number, but I was hoping it would just give me that light bulb moment on how to fix it if I did it like this first.
Last edited on
closed account (48T7M4Gy)
1. enter value n
2. print number 1 on line 1
3. print numbers 1, 2 on line 2
...
4. print number 1, ... , k on line k
...
5. keep going until k == n

So there are two loops - lines 2 through 5 and line 4 alone is a loop inside the first.

BTW 2 for loops will do the job.
Last edited on
I would use three loops:
- a while loop to keep getting new input until the input is negative
- a for-loop to count the lines
- a for-loop to print the numbers 1-up-to-the-line-number
Topic archived. No new replies allowed.