CrazyEngineers
  • 'For' Loop Vs. 'While' Loop

    gsk_ssit

    Member

    Updated: Oct 25, 2024
    Views: 2.0K
    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; 
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • [Prototype]

    MemberFeb 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.
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register