'For' Loop Vs. 'While' Loop

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

  • [Prototype]
    [Prototype]
    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.

You are reading an archived discussion.

Related Posts

Any more laws you think should be added? Fire away and I'll feature them in Part Two!
5 Days ago in FOSDEM 2013, HURD a GNU Micro-Kernel Project was presented. Richard Stallman founded GNU Micro Kernel Project in the year 1983 known as HURD. It is predicted...
HI All, Is anyone of us aware of any Framework that could be used for automation testing for devices i.e. smartphones & Tablets ? ( For example: For web testing...
By user oriented I mean a product that is people can and should use daily. Along with all the service oriented work we do, don't we have enough talent to...
Isearch after information about who the car can communicate with others cars and protocols for this?​I know that these subjects are new so they are several start ups and labs...