Tell me why this program is equal to 9?

  • Thread starter the_d
  • Start date
  • Tags
    Program
  • #1
127
0
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
 
  • #2
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
 
  • #3
can u explain why you alternated the values in i and j and in what sequence you did it in please?
 
  • #4
can u explain why you alternated the values in i and j and in what sequence you did it in please?

They represent
Code:
  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

[tex]a=\sum_{i=0}^2\sum_{j=0}^1 2i+j-1[/tex]

First evaluate the inner sum (the sum over [itex]j[/itex]). Note that the term [itex]2i-1[/itex] is a constant in this inner sum. Using

[tex]\sum_{k=0}^n c = (n+1)*c[/tex]

[tex]\sum_{k=0}^n k = \frac{k*(k+1)}2[/tex]

The inner sum evaluates to

[tex]\sum_{j=0}^1 2i+j-1 = 2*(2i-1)+\frac{1*2}2 = 4i-1[/tex]

The outer sum thus becomes

[tex]a=\sum_{i=0}^2 4i-1 = 4\frac{2*3}{2}-3*1 = 12-3 = 9[/tex]
 
  • #5
or, in the rant straight from mighty wikipedia: click
 
  • #6
Perhaps it makes more sense with while loops:
Code:
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;
}
 

Suggested for: Tell me why this program is equal to 9?

Replies
2
Views
901
Replies
5
Views
583
Replies
9
Views
1K
Replies
9
Views
1K
Replies
13
Views
591
Replies
4
Views
591
Replies
89
Views
3K
Back
Top