Good Afternoon,

How do you write a two nested do-while loops to display the pattern:
*
**
***
****
*****
******

So far I have this code, but it just displays ******

int i=0;
    do{

        cout<<'*';
        i++;
    }while(i<5);
    cout<<endl;

You need two loops: An outer loop to keep track of the rows, and an inner loop to keep track of the number of asterisks per row.

Right now, you have an outer loop that is keeping track of the rows. But you need to replace that cout line with an inner loop to not just print one asterisk, but to loop through printing a variable number of asterisks.

I will hant it in pseudocode, it's not too hard to figure it out by yourself:

i<-0;
while i != given_input_number do
    j<-0
    while j != i do
        print *
        increment(j)
    end_while
    print new line
    increment(i)
end_while

as cscgal said you have only the outer loop, so you need to put another loop, to count how many times you have to print the asterix. In this case, at each row, you'll have to print a number of asterixes which is greater than the one before, so a while till j != i suits this matter.

Edited 4 Years Ago by Lucaci Andrew

Lucaci Andrew,

I implemented this code, but it didn't work correctly.

int i = 0;
    int j = 0;

    while (i != 5)
    {
        do {

            while (j != i)
                do{
                cout<<'*';
                j++;
        }while(j<-0);
            cout<<endl;
            i++;
    }while(i<-0);
    }

Please tell me what I'm doing wrong. I would really appreciated your help.
Thank you

  1. follow exactly the pseudocode to get your porgram to work (you only need 2 loops)
  2. I suggest you use only while loops
  3. include the j=0 at the start of your first loop as the counter for the number of asterisks you need to print every time

poloblue I see you have 3 loops, from which 2 of them are do.... while loops. In my pseudocode I put only 2 while loops. As zeroliken said, follow the pseudocode and remember to initialize j=0 inside the first loop, so that after it prints 1 row of asterixes, to start again from 0 on the other row.

Lucaci Andrew, zeroliken, and Dani,

I made it to work with two nested while loops, I think that it can't de done using two nested while loops. Thanks everyone for your help.

Thank you

This question has already been answered. Start a new discussion instead.