Repeating Action?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 3 of 3

Thread: Repeating Action?

  1. #1
    Join Date
    Feb 2009

    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.

    Enter the number of lines -> 5

    I have this:

     #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

  2. #2
    Join Date
    Feb 2009

    Re: Repeating Action?

    The problem is here

    while (cin >> n)

    Put the cin outside the while and make it similar to the inner loop.
    I love work. It gives me something to do between weekends.

    Microsoft MVP (Visual C++)

  3. #3
    Join Date
    Jan 2004
    Düsseldorf, Germany

    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

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

This is a survey!

HTML5 Development Center