C Program

  • Thread starter the_d
  • Start date
  • #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
 

Answers and Replies

  • #2
218
0
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
127
0
can u explain why you alternated the values in i and j and in what sequence you did it in please?
 
  • #4
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
685
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
218
0
or, in the rant straight from mighty wikipedia: click
 
  • #6
verty
Homework Helper
2,164
198
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;
}
 

Related Threads on C Program

Replies
9
Views
4K
  • Last Post
Replies
6
Views
3K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
2
Views
821
  • Last Post
Replies
4
Views
3K
  • Last Post
Replies
9
Views
3K
  • Last Post
Replies
4
Views
3K
  • Last Post
Replies
18
Views
4K
  • Last Post
Replies
5
Views
2K
  • Last Post
Replies
1
Views
639
Top