Replacing For Loop wiith a while loop

Hi guys appreciate your help,
I had a question to modify the for loop to while loop which i not sure how to go about it.

#include<iostream>
using namespace std;
int main()
{
int roll, col;
for (roll = 1; roll < 7; roll++)
{
for (col = 1; col <= roll; col++)
cout<<"*";
cout<<endl;

}


system("pause");

return 0;
}

sorry to post such a question as i am stil a noob trying to understand things about for and while loop....
Hi,

this case is a perfect use for a for-loop, so it wouldn't make sense to change it, but it would look like:

1
2
3
4
5
6
7
int roll = 1, col = 1;
while(roll++ < 7) {
     while(col++ <= roll) {
          cout << "*" << endl;
    }
    col = 1;
}
@kunichiwa
like murksmeier said you know when to use a while and when to prefer a for-loop or do-while .

For some situation the compiler will be able to optimize your loop .
thanks for all the help!!

this is my past year exam question and they want us to fully understand the application between for and while loo.
@murksmeier,
may i check with you when you attempt a question normally you will do first and change the code accordingly or you will think of the best way and write the code accordingly.
my problem is everything when i face a new question, my mind is in total blank, i do not know what method to use, using loop, for loop, while, array structure or function etc...

i really appreciate the experts to share with me their way of writing codes.


hi @murksmeiser,

i tried your coding and it comes out differently,
my desired output is:
*
**
***
****
*****
******

yours is:
*
*
*
*
*
*
*
*
*
*
*
*
....
.
.

appreciate you clarification
You can almost do this mechanically. This:
for (a, b, c) statement;
Is the same as this
1
2
3
4
5
6
7
{
    a;
    while (b) {
        statement;
        c;
    }
}

The only difference I can think of is that a continue statement will execute c in the for loop, but not in the while loop.

murksmeier's code doesn't work because (1) it increments roll and col at the beginning of the loop instead of the end and (2) it prints endl inside the inner loop instead of the outer loop.
Topic archived. No new replies allowed.