Thread: Need help with loop

  1. #1
    Registered User
    Join Date
    Apr 2016
    Posts
    21

    Need help with loop

    Hello, I need help to understand why its printing (14) thank you.
    Code:
    #include <stdio.h>
    #define N 100
    int main()
    {
        int i,j;
        for(i=0,j=0;i<N;++j,i+=j);
        printf("%d",j);
    
    }

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,128
    My version of your code:
    Code:
    #include <stdio.h>
    #define N 100
    
    int main(void)
    {
        int i, j;
    
        for(i = 0, j = 0; i < N; ++j, i += j);
    
        printf("i == %d, j == %d", i, j);
    }
    Displays the following:
    Code:
    i == 105, j == 14
    Your loop executes 14 times. Each time you increment j once, ("++j"), and add j to i each time through the loop. ("i += j")

    Is this what you meant to do?

    In the for loop, "++j, i += j", what is i being incremented by???

    Is j being incremented first, then i incremented by j, or the opposite?

    This is undefined behavior. Different compilers might interpret this differently.

  3. #3
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Quote Originally Posted by rstanley View Post
    This is undefined behavior. Different compilers might interpret this differently.
    It's not UB. The comma operator provides a sequence point after the evaluation of the left-hand operand.

    I wonder if the OP meant to have a semicolon after the for loop?
    Perhaps.
    Better to put it on a separate line so it's more obviously intended.
    Last edited by algorism; 08-27-2016 at 01:48 PM.

  4. #4
    Registered User
    Join Date
    Aug 2016
    Posts
    4
    Try this.

    for(i=0,j=0;i<N;++j,i+=j);
    so,
    i+=j means i=i+j
    i=0+1=>1 //i=0,j=1(as j is incremented)
    i=1+2=>3
    i=3+3=>6
    i=6+4=>10
    i=10+5=>15
    i=15+6=>21
    i=21+7=>28
    i=28+8=>36
    i=36+9=>41
    i=41+10=>51
    i=51+11=>62
    i=62+12=>74
    i=74+13=>87 //here j=13 ,when it checks next condtion j becomes 14

    next i value is 102,it does not satisfies the condition(i<N (i.e)102<100)
    so it comes out of the loop,with j=14 in hand
    in the next statement
    j is printed
    so,j=14

    i hope you understand.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. While loop in insertNode function is an infinite loop
    By blongnec in forum C Programming
    Replies: 8
    Last Post: 03-19-2016, 09:57 PM
  2. Replies: 4
    Last Post: 11-05-2015, 03:29 PM
  3. Replies: 1
    Last Post: 03-28-2015, 08:59 PM
  4. Help - Collect data from Switch loop inside While loop
    By James King in forum C Programming
    Replies: 15
    Last Post: 12-02-2012, 10:17 AM
  5. Replies: 23
    Last Post: 04-05-2011, 03:40 PM

Tags for this Thread