nested while

I'm trying to do some nested whiles with y=x*z/(x-z)
so x goes from 1-5 and increment by 1
z goes from 2-6 and increment by 1

this is what i have so far...

x=1;
while (x<=5)
{
z=2;

while (z<=6)
{

y = (x*z) / (x-z);

z=z+1;
}
cout<<"\t"<<x
<<"\t "<<z
<<"\t "<<y<<endl;

x=x+1;
}
Yes, this is a nested loop. Here it is with code tags.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
    int x=1, z, y;
    while (x<=5)
    {
        z=2; 
        while (z<=6)
        { 
            y = (x*z) / (x-z);
            z=z+1;
        }
        cout<<"\t" <<x <<"\t "<<z <<"\t "<<y<<endl;
        x=x+1; 
    }
        1        7       -1
        2        7       -3
        3        7       -6
        4        7       -12
        5        7       -30
Press any key to continue . . .


Here are two suggestions,
1. For loops are designed for counters like this. This isn't your problem, but it will make things clearer.
2. Put the cout in the inner-most while loop as I am assuming that you want do display the result after every calculation (not just on the last calculation of z every time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
    int x, y, z;
    for (x = 1; x<=5; x++)
    {
        for (z = 2; z<=6; z++)
        { 
            if (x == z) continue; // No div/0!
            y = (x*z) / (x-z);
            cout<<"\t" <<x <<"\t "<<z <<"\t "<<y<<endl;
        }
    }
}
        1        2       -2
        1        3       -1
        1        4       -1
        1        5       -1
        1        6       -1
        2        3       -6
        2        4       -4
        2        5       -3
        2        6       -3
        3        2       6
        3        4       -12
        3        5       -7
        3        6       -6
        4        2       4
        4        3       12
        4        5       -20
        4        6       -12
        5        2       3
        5        3       7
        5        4       20
        5        6       -30
Press any key to continue . . .


Note my addition in line 8. In the case where x==z, you are dividing by zero. That's not allowed!!!! The continue keyword tells us to skip the rest of this loop and proceed with the next value of z.
Last edited on
Oh I needed to put the cout in the inner loop..... thanks =)
Topic archived. No new replies allowed.