I know similar question has been asked, but I read it before posting my question, and it did not seem to help me.
The following program should return the sum (i+1)*2 + (i+2)*3 that runs from 0 to a certain number:
#include <stdio.h>
#define MULa 2
#define MULb 3
#define NUM 3
int entry( int a, int b )
{
return (a* MULa + b* MULb);
}
int sum(int num)
{
int my_sum = 0;
int i = 0, j = 0;
while (j <= num)
{
printf("in iteration %d before incrementing: i is %d\n", j, i);
my_sum += entry(i++, i++);
printf("sum is %d in iteration %d\n", my_sum, j);
j++;
printf("after incrementing: i is %d\n", i);
}
return (my_sum);
}
int main()
{
int my_sum = sum( NUM );
printf("sum is %d\n", my_sum);
return 0;
}
Now, the program does not do what it is supposed to.
From what I understand, through each iteration i is incremented twice, and this is done after the function call. I printed out the values of sum and expected the following result:
in iteration 0 before incrementing: i is 0
sum is 8 in iteration 0 /*(0+1)*2 + (0+2)*3 = 8*/
after incrementing: value of i is 2
in iteration 1 before incrementing: i is 2
sum is 26 in iteration 1 / *8 + (2+1)*2 + (2+2)*3 = 26*
after incrementing: i is 4
in iteration 2 before incrementing: i 4
sum is 54 in iteration 2 /*26+(4+1)*2 + (4+2)*3 = 54*/
after incrementing: i is 6
in iteration 3 before incrementing: i 6
sum is 92 in iteration 3 /*54 + (6+1)*2 + (6+2)*3 = 92*/
after incrementing: i is 8
sum is 68
But instead, I got this:
in iteration 0 before incrementing: i 0
sum is 2 in iteration 0
after incremeting: i is 2
in iteration 1 before incrementing: i 2
sum is 14 in iteration 1
after incremeting: i is 4
in iteration 2 before incrementing: i 4
sum is 36 in iteration 2
after incremeting: i is 6
in iteration 3 before incrementing: i 6
sum is 68 in iteration 3
after incremeting: i is 8
sum is 68
I don't really understand why that's the output. How come sum is 2 for example, in iteration 0? I'd be glad if you could explain how this function works, what actually occurs in each step.
Thanks in advance!