When I am doing my assignments I done a small mistake by placing ; in the for loop like the following code.
for(i=0;i<n;i++);{
n=n*i;
}
When I compiled the program its compiled with no error but I did not get the output for a while. Then later figured out that I misplaced the semicolon in for loop. What was the bug when I place semicolon after for loop.
class A
{
public static void main(String args[])
{
int i, n=1;
for(i=1; i<=5; i++);
n=n*i;
System.out.println(n);
}
}
I am getting output for the following code as 6 instead of 120.
The reason why you're getting 6 is simple. At the last iteration the value of i turns from 5 to 6, the loop won't do another iteration because i=6 and it doesn't satisfy the condition for the
for loop
any more. Since n=1 and i=6 then the output of n*i is 6.You didn't get an output because the semi-colon ended the statement, [ for(I = 0; I < n; I++ ]
The code should be:
If you place semicolon after a for loop then it is technically correct syntax. Because it is considered as an empty statement - that means nothing to execute.
In your case -
An empty statement executed up to
n
times. Or in other words thefor-loop
simply runsn
times.The curly braces
{}
after the for loop executed only once. Now the code block inside the curly braces{}
considered as a floating block.When you do this:
for(i=0;i<n;i++);
you are essentially doing this:for(i=0;i<n;i++) {}
. This translates to a loop with no body.This also happens for
while
loops:while(..);{<Foo>}
. The extra;
will make execute only once.The same goes for
if
statements. Doingif(a==b);{<Foo>}
will still execute<Foo>
for the same reason. Ifa == b
, then, the empty statement will be taken into consideration. Afterwards,<Foo>
will be executed. This can give the wrong impression that Java will treat afalse
as atrue
since ifa != b
, then,<Foo>
would still be executed.for
loop can execute only one code block or one statement, even empty ones. So semicolon here represents empty statement (statement which does nothing).In other words you can think of
for(int i; i<n; i++);
asfor(int i; i<n; i++){}
.So code like
is same as
and
is simply
About
As explained earlier your code
is same as
which means that it your loop will not execute
n=n*i
but will try to execute{}
which does nothing. Also at end of each iterationi
will be incremented because ofi++
so wheni
will become5
your andi<5
will be false flow of control will leave loop and will executen=n*5
which means that n will becomen=1*5
which is5
.If you want to get as result
120
by executingn=n*i
in each loop simply remove semicolon after loop.BTW prefer to place code which should be executed by loop or
if
statement in code blocks,This makes your code easier to read and maintain. Also if you will make again your mistake and you will use some auto formatting tool which will indent your code for you you will see that it will be formatted as
which makes spotting such errors very easy.