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.
#include <iostream>
usingnamespace 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.
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