View Full Version : C Program
can someone tell me why this program is equal to 9? I have been sitting for 2
hours trying to figure out how the program gets and when doing it by hand I
get something different. Here is the program:
#include <stdio.h>
int main()
{
int i, j;
int a=0;
for (i=0;i<3;i++)
for (j=0;j<2;j++)
a+=2*i+j-1;
printf("%d\n", a);
return 0;
}
a=9
what you mean why?
i=0, j=0: 2*i+j-1=-1, a=-1
i=0, j=1: 2*i+j-1=0, a=-1
i=1, j=0: 2*i+j-1=1, a=0
i=1, j=1: 2*i+j-1=2, a=2
i=2, j=0: 2*i+j-1=3, a=5
i=2, j=1: 2*i+j-1=4, a=9
can u explain why you alternated the values in i and j and in what sequence you did it in please?
can u explain why you alternated the values in i and j and in what sequence you did it in please?
They represent
for (i=0;i<3;i++)
for (j=0;j<2;j++)
In other words, whatta executed the program by hand.
Mathematically, your code is calculating
a=\sum_{i=0}^2\sum_{j=0}^1 2i+j-1
First evaluate the inner sum (the sum over j). Note that the term 2i-1 is a constant in this inner sum. Using
\sum_{k=0}^n c = (n+1)*c
\sum_{k=0}^n k = \frac{k*(k+1)}2
The inner sum evaluates to
\sum_{j=0}^1 2i+j-1 = 2*(2i-1)+\frac{1*2}2 = 4i-1
The outer sum thus becomes
a=\sum_{i=0}^2 4i-1 = 4\frac{2*3}{2}-3*1 = 12-3 = 9
or, in the rant straight from mighty wikipedia: click (http://en.wikipedia.org/wiki/For_loop)
Perhaps it makes more sense with while loops:
int main()
{
int i, j;
int a=0;
i = 0;
while (i < 3) {
j = 0;
while (j < 2) {
a += 2*i+j-1;
j++;
}
i++;
}
printf("%d\n", a);
return 0;
}
vBulletin® v3.8.7, Copyright ©2000-2012, vBulletin Solutions, Inc.