Reputation: 89
When I try to change the nested for loop the program doesn't work as supposed
This is the original code:
public class AandB
{
public static void main (String [] args) {
int a = 0, b = 2;
int j = 1;
for (int i = 2; i>= 1; i--) {
for(int j = 1; j <=3; j++) {
if(j%2 == 0) {
b = b* 2;
} else {
a= a + b;
}
System.out.println("a=" + a + " b=" + b);
}
}
}
}
It has this output:
a=2 b=2 a=2 b=4 a=6 b=4 a=10 b=4 a=10 b=8 a=18 b=8
I changed this code above so that it could work with a while loop inside the for loop:
public class AandB
{
public static void main (String [] args) {
int a = 0, b = 2;
int j = 1;
for (int i = 2; i>= 1; i--) {
while(j <4) {
if(j%2 == 0) {
b = b* 2;
} else {
a= a + b;
}
System.out.println("a=" + a + " b=" + b);
j++;
}
}
}
}
It has this output:
a=2 b=2 a=2 b=4 a=6 b=4 a=6 b=8
It should output the same results, but I can't get it right. The problem is that after the while loop ends, the for iterates but ignores the while because the condition no longer applies. I suppose I need to clear the variable j? Or create something like a counter variable?
Upvotes: 1
Views: 68
Reputation: 40036
As in C/C++/Java 101, for
is (almost) equivalent to while
by the following conversion:
for (A; B; C) {
D;
}
Can be written as while
in form of:
A;
while(B) {
D;
C;
}
So your
for (int i = 2; i>= 1; i--) {
for(int j = 1; j <=3; j++) {
// do something
}
}
Should be written as (if just changing the inner loop)
for (int i = 2; i>= 1; i--) {
int j = 1;
while(j <=3) {
// do something
j++;
}
}
Upvotes: 1
Reputation: 201439
Move int j = 1;
inside the for
loop. That's the difference between your existing for loop and while loop implementations. Something like,
for (int i = 2; i >= 1; i--) {
int j = 1;
while (j < 4) {
When your for loop had for(int j = 1; j <=3; j++) {
that shadowed the outer j
and re-initialized to 1
on every iteration of the outer loop.
Upvotes: 1
Reputation: 57
I believe that it's your initialization on the 2nd one. You're saying while(j <=4)
, meaning that it loops 5 times, rather than on the first one, which loops 2 times.
Upvotes: 0
Reputation: 3
In the original loop, your conditional is "j <=3" in the while loop it changes to "j <=4".
Upvotes: 0