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); }
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); }
My version of your code:
Displays the following: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); }
Your loop executes 14 times. Each time you increment j once, ("++j"), and add j to i each time through the loop. ("i += j")Code:i == 105, j == 14
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.
Last edited by algorism; 08-27-2016 at 01:48 PM.
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.