Thread: simple for loop

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    8

    simple for loop

    #include <stdio.h>

    void main()
    {
    int x;
    for(x=10;x;x--)
    printf("%d\n",x);
    }

    In the above program, the output is printing from 10 to 1. But I didn't give any lower limit. How is it printing like that?

    Regards
    Kokila

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    You did give a lower limit. The loop stops when x is false, which reached as x is 0.

  3. #3
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    Let's compare it with a typical condition and let's see why they both work:

    for(x=10;x;x--)
    versus
    for(x=10; x > 0; x--)


    Code:
    x     x > 0  
    10    1
    9     1
    8     1
    7     1
    6     1
    5     1
    4     1
    3     1
    2     1
    1     1
    0     0
    Notice the for loop will run when it is TRUE or a non-zero value.
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>void main()
    main() returns an int, so make it
    >int main(void)

    and return 0; at the end.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  5. #5
    Registered User
    Join Date
    Nov 2001
    Posts
    8

    Thumbs up

    Thanks for all the responses.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. creating very simple text editor using c
    By if13121 in forum C Programming
    Replies: 9
    Last Post: 10-19-2010, 05:26 PM
  2. Simple message encryption
    By Vicious in forum C++ Programming
    Replies: 10
    Last Post: 11-07-2004, 11:48 PM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. Simple simple program
    By Ryback in forum C++ Programming
    Replies: 10
    Last Post: 09-09-2004, 05:48 AM
  5. Need help with simple DAQ program
    By canada-paul in forum C++ Programming
    Replies: 12
    Last Post: 03-15-2002, 08:52 AM