how to change for to while loop..?!?

i need to try this program in a while loop.
i wrote it in for.! but i couldnt figure it out to change it to while.!

1=1
1+2=3
1+2+3=6
1+2+3+4=10
1+2+3+4+5=15

1
2
3
4
5
6
int i,j
for (i=1,i<=5;i++)
{
for (j=0;j<=1;j+2)
cout<<i<<"+"<<j<<"="<<i+j<<endl;
}
Both for loop and while loops have three components:
- initialization
- condition
- increment
1
2
3
4
5
j = 0;  // initialization
while (j<=1)    // condition
{  cout<<i<<"+"<<j<<"="<<i+j<<endl;
    j += 2;   // increment
}

Note that in line 4 of your code, your increment won't work. You're not changing j.


closed account (28poGNh0)
@elmoro15

I am wondering How your program working using for loop

1
2
3
4
5
6
int i,j// Here you miss ;
for (i=1,i<=5;i++)//Also this must changes to for (i=1;i<=5;i++)
{
    for (j=0;j<=1;j+2)//The 3 expression in for has no effect
    cout<<i<<"+"<<j<<"="<<i+j<<endl;
}


// The program not gonna execute

However I think you looking for this one using for loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
    int sum = 0;

    for(int i=1;i<6;i++)
    {
        for(int j=1;j<=i;j++)
        {
            cout << j << " + ";
            sum += j;
        }cout << "\b\b = " << sum << endl;
        sum = 0;
    }
}


@AbstractionAnon gives a good explaination of how while works you should learn from It

this one is combination between for and while loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
    int sum = 0;
    int i=0;

    while(i<6)
    {
        for(int j=1;j<=i;j++)
        {
            cout << j << " + ";
            sum += j;
        }cout << "\b\b = " << sum << endl;
        sum = 0;
        i++;
    }
}


but if you like kick off the for loop from source code I hope this exp will be the one

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
    int sum = 0;
    int i=1,j=0;

    while(i<6)
    {
        j = 1;
        while(j<=i)
        {
            cout << j << " + ";
            sum += j;
            j++;
        }

        cout << "\b\b = " << sum << endl;
        sum = 0;
        i++;
    }
}
Topic archived. No new replies allowed.