-
February 24th, 2009, 09:02 AM
#1
Repeating Action?
I'm supposed to print off stars. I prompt the user for a number (we'll call it n), and then print out n lines of stars. The first line will have one star and then it adds one each line.
eg.
Enter the number of lines -> 5
*
**
***
****
*****
I have this:
Code:
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the number of lines." << endl;
while (cin >> n) {
//--- Loop counting i up from 1 to n.
int i = 1; // Initialize counter.
while (i <= n) { // Test counter.
cout << "*";
i++; // Increment counter.
}
cout << endl;
}
return 0;
}
That gives me the entered number of stars but I don't know how to get the lines of stars up to that point.
eg. If I run it now:
Enter number of lines -> 5
*****
-
February 24th, 2009, 09:28 AM
#2
Re: Repeating Action?
The problem is here
while (cin >> n)
Put the cin outside the while and make it similar to the inner loop.
-
February 24th, 2009, 09:53 AM
#3
Re: Repeating Action?
Use nested loops: An outer loop to loop over the lines you want to write (user a loop variable row), an inner loop to write as many stars as suitable for this line (the current value of row). After the inner loop, write a line feed character (\n).
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
Please read Information on posting before posting, especially the info on using [code] tags.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|