'For' Loop Vs. 'While' Loop

gsk_ssit

gsk_ssit

@gsk-ssit-KY7Fvw Oct 25, 2024

Actually i tried writing the following programs the 'for' loop is giving the correct answer but 'while' loop is not compiling correctly .Can some body explain the following programs.I think both programs are one and the same.


For WHILE loop:

int i;
i=1;
while(i<=10)
printf("%d\n",i);
i++;
system("pause");
return 0; 

For FOR loop:

int i;
for(i=1;i<=10;i++ )
printf("%d\n",i);
 
system("pause");
return 0; 

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • [Prototype]

    [Prototype]

    @prototype-G9Gn5k Feb 12, 2013

    Braces!

    If you don't write the while's body(or any other loop or conditional statement) within braces, only the immediate next line is considered to the part of the loop while other statement following it will be considered OUTSIDE the loop.

    It works with for loop because, the counter variable "i" is a part of 'for' construct which is not the case in while. What's happening here is, for C compiler, the i++, which was supposed to be the counter for while loop is actually outside the while due to the missing braces. Insert the braces and things will work.

    On the side note, its a good practice to always insert braces. This helps in tracking the flow of program and makes it easily readable.