0
What happens when we add a semi colon after for loop in c language?
with a example and with a definition
1 ответ
+ 6
Nice question Arjun.
e.g. for(a=1;a<=5;a++);
printf("%d",a)
here, in above example, you can see that there is a semicolon after for(a=1;a<=5;a++). so in this case the loop executes as:
for(a=1;a<=5;a++)
;
printf("%d",a)
it means that the loop keeps rotating between for(a=1;a<=5;a++) and ;(semicolon) when the condition becomes false i.e. a=6
then if comes out of the semicolon and prints 6 as an output, but the expected output is 12345. so it becomes wrong but not error.
e.g.a=1;
while(a<=5);
{
printf("%d",a);
a++;
}
here in the above example, the loop is infinite because it keeps rotating between while(a<=5) and the ;(semicolon) here is no change in value in 'a' the loop is infinite.
e.g. a=1;
do;{
printf("%d"a);
a++;
}while(a<=5);
here in the above example ;(semicolon) after the while is required, its a rule.
but after the do it is not. the do will get executed after that 1 is printed, a++ will also occur because in c you can add curly brackets (braces) to every single statement it won't cause error but the while can't rotate the loop and makes our program wrong.