Reputation: 327
May someone explain to me why the following blocks of code generate such different outputs?
public class hello
{
public static void main(String args[])
{
int a,b,c;
for (a = 0; a < 5; a++)
{
for (b = 4; b >= a; b--)
{
System.out.print(" ");
}
for (c = 0; c <= a - b; c++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Output:
public class hello
{
public static void main(String args[])
{
int a,b,c;
for (a = 0; a < 5; a++)
{
for (b = 4; b >= 0; b--)
{
System.out.print(" ");
}
for (c = 0; c <= a - b; c++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Output:
Shouldnt the outputs be the same since b >= a is equivalent to b >= 0 as b's value will be deducted by 1 for every loop?
Upvotes: 0
Views: 427
Reputation: 29
Please read the comments in the code and you will se the difference!
int a, b, c;
for (a = 0; a < 5; a++)
{
for (b = 4; b >= a; b--) // Print every time b-a + 1 underscores... since you start every time with b=4 you have for each a one space fewer
{
System.out.print(" ");
}
for (c = 0; c <= a - b; c++) // and then print (a-b)-c +1 stars (b is every time a-1)...
// (first a=0 -b=-1)+1=2 and any time it will prit 2 stars scince
{
System.out.print("*");
}
System.out.println();
}
for (a = 0; a < 5; a++)
{
for (b = 4; b >= 0; b--) // Print every time b-a + 1=4 underscores
{
System.out.print(" ");
}
for (c = 0; c <= a - b; c++) // and then print (a-b)-c +1 stars (b is every time -1)...
// first time ( a=0 -b=-1)+1 =2 , second time (a=1 - b=-1)+1=3
{
System.out.print("*");
}
System.out.println();
}
Upvotes: 1
Reputation: 1597
No, the outputs cannot be the same, since every time you are executing
for (a = 0; a < 5; a++)
this gets executed as well (5 times)
for (b = 4; b >= a; b--)
{
System.out.print(" ");
}
But the value of a
is changing with every iteration: a
will be initially 0, then 1, 2, 3 and finally 4.
Hence, the number of spaces that you are printing in the first scenario will decrease with every iteration of a
.
For a = 0 we have: b = 4, b = 3, b = 2, b = 1, b = 0 (
for loop
stops since b=-1 is not >= a=0)For a = 1 we have: b = 4, b = 3, b = 2, b = 1 (
for loop
stops since b=0 is not >= a=1)For a = 2 we have: b = 4, b = 3, b = 2 (
for loop
stops since b=1 is not >= a=2)For a = 3 we have: b = 4, b = 3 (
for loop
stops since b=2 is not >= a=3)For a = 4 we have: b = 4 (
for loop
stops since b=3 is not >= a=4)
Upvotes: 2
Reputation: 8386
variable a
will go from 0 to 4, so for each iteration you will have:
for (b = 4; b >= 0; b--)
{ [...]
for (b = 4; b >= 1; b--)
{ [...]
for (b = 4; b >= 2; b--)
{ [...]
Upvotes: 2