For loop
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: For loop

Hybrid View

  1. #1
    Join Date
    Feb 2012
    Location
    INDIA
    Posts
    25

    For loop

    void main()
    {
    int i;
    for(i = 0; i <= 10; ++i);
    printf("%d ", i);
    }
    In the above program , we are pre-incrementing i, even though the output is 1-10 , which is the case for post increment.Why?? I mean why the output is same whether we pre-increment or post - increment the i's value.


    and ...

    void main()
    {
    int i;

    for(i = 1; i <= 5;printf("\n%d ", i))
    {

    i++;
    }

    }// why the output is 2 3 4 5 6..... it would have to first initialize the value i then compare , then print and then it would have to enter the loop , where the value of i would get incremented.
    TANUSHREE-AGRAWAL...

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,250

    Re: For loop

    Quote Originally Posted by Tanushreeagr
    In the above program , we are pre-incrementing i, even though the output is 1-10 , which is the case for post increment.
    You might want to compile and run the program as the output is not what you think it is. Note your semi-colons carefully.

    Quote Originally Posted by Tanushreeagr
    Why?? I mean why the output is same whether we pre-increment or post - increment the i's value.
    Yes, the choice between pre-increment and post-increment makes no real difference here. However, in situations where operator overloading is involved, the pre-increment version may be faster than the post-increment version, and at least no worse. Hence, we prefer pre-increment over post-increment unless we actually want the effect that is specific to post-increment.

    [quote=Tanushreeagr]it would have to first initialize the value i then compare , then print and then it would have to enter the loop
    No, the printf is in the part that happens after each iteration. Where did you get this semi-obfuscated code from, anyway?
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center