Tarsemsingh
Tarsemsingh

Reputation: 23

Why does this program output "10"?

I am a newbie and tested the following code in c and in php. Please tell me why this code outputs "10".

for($i=0;$i<10;$i++);
{
    print $i;
}

Upvotes: 2

Views: 507

Answers (8)

Kathir
Kathir

Reputation: 1240

The semicolon(;) next to for loop indicates that the loop contents are empty and hence the empty contents executed 10 times as in loop (for($i=0;$i<10;$i++);) and for each looping the value of $i gets incremented and the final value 10 gets printed as output.

Upvotes: 0

Yellos
Yellos

Reputation: 1657

Remove the semicolon in this line and it will output 1,2,3..9:

for($i=0;$i<10;$i++);

If you don't do that it will first run through the loop without writing anything, and after that print $i, which has become 10 in the for-loop.

Upvotes: 2

iiro
iiro

Reputation: 3118

Yes, but he is asking WHY it is printing "10". Here is the reason:

Your code is :

<?php
for($i=0;$i<10;$i++);
{
print $i;
}
?>

This line for($i=0;$i<10;$i++); is a loop, and it loops 10 times from 0 to 9. After every number the variable $i is incremented ($i++) so after first loop, $i has value of 1. After tenth iteration, it has value of 10.

After that you do print $i; so it will correctly print number 10.

But now, if you remove the semicolon after for-loop, so that the for loop has a following body

{
print $i;
}

and it will print 0123456789.

Upvotes: 6

Yash Shah
Yash Shah

Reputation: 182

Remove the ;(semicolon) after the for($i=0;$i<10;$i++); statement.

Upvotes: 2

dInGd0nG
dInGd0nG

Reputation: 4114

See Ther is a semicolon after that for loop. So PHP thinks that the loop has no body. So The print $i is executed only once

Upvotes: 4

James
James

Reputation: 66844

Because of the semi-colon in your for statement. This ends the statement earlier than you expect and the print statement is no longer part of the loop.

Upvotes: 2

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

remove ;

for($i=0;$i<10;$i++);
                    ^

working example http://codepad.viper-7.com/SeVcbl

Upvotes: 4

Dukeatcoding
Dukeatcoding

Reputation: 1393

Wrong code ;

<?php
 for($i=0;$i<10;$i++)
 {
  print $i;
 }

?>

Should output all numbers

Upvotes: 3

Related Questions