Explanation

Can someone provide an explanation to the steps in this program please. From the first half I understand that int a will be equal to 1, and x=1 will be in the cout area. But the second half I'm a bit lost. Is x now equal to 0 or is it still equal to 1? Will b=1+3 or b=0+3? What does the line "for(i=a;i<b; ) x += i++;" mean?

#include <math.h>
#include <iostream>
using namespace std;

int f1(int a);
int main()
{
int x;
x = f1(1);
cout << "x=" << x << "\n";
return(0);
}
int f1(int a)
{
int i, x=0;
int b = a+3;
for(i=a;i<b; ) x += i++;
cout << "i=" << i << "\n";
return(x);
}
The for sentence is the only important one in your code. if you understand what it means, it is very easy to know what the whole program does. now let me try to explain it.

First, the loop body is x+=i++, it means that x will add the value of i, and i will be incremented. We can rewrite it:
1
2
x+=i;
i++;


OK,rewrite the for sentence:
1
2
3
4
5
for (i=a; i<b ; )
{
    x+=i;
    i++;
}


Now let's see what the function f1 do:
1
2
3
4
5
6
7
8
9
10
11
12
13
int f1(int a)
{
    int i;
    int x=0;
    int b=a+3;
    for (i=a; i<b; )
    {
        x+=i;
        i++;
    }
    cout << "i=" << i , "\n"
    return (x)
}


Variable i will be changed in the loop, then let's see how it changed:
In the first loop, i=a(initialization), a+1(caused by i++)
In the second loop, i=a+1, a+2
in the third loop, i=a+2, a+3

Now i=a+3, it is not less than b(a+3), so the loop is end.

So x will be added by a,a+1,a+2.
The function f1 will add a,a+1 and a+2 together and return the result.
Topic archived. No new replies allowed.