sigma in c programming

i got an equation composed of sigma : b = E (xi-x)*(yi-y) for i=1 and the last i is n

does anyone know how to write such program in C?
since it is a bit boring if i write :
b = (x1-x)*(y1-y) + (x2-x)*(y2-y) + ... + (xn-x)*(yn-y)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//you may be using another data type such as int
float b = 0;

//look into arrays to see how to instantiate them and fill in the values for your case
float xArray[] = {...};
float yArray[] = {...};

float x = 5; //or whatever value it has
float y = 10; //or whatever value it has

int i = 0; //loop counter
int n = /*whatever*/; //number of values

for(i = 0; i < n; i++) //arrays of size n are indexed 0..n-1
{
     b += (xArray[i] - x) * (yArray[i] - y);
}


http://www.cplusplus.com/doc/tutorial/control/
http://www.cplusplus.com/doc/tutorial/arrays/
Last edited on
@ko2dy: you just need a little understanding of looping (and arrays) :D
@shacktar: what do you mean by this:
1
2
int i = 0;
for (i = 0; /*...blablabla*/) {

:D
@chipp ko2dy specifically asked for C code. In C, all variable declarations need to be at the beginning of the block (I initialized i for good practice). Doing for(int i = 0; /*foo*/) is illegal in C.
@shacktar i tried your program recommendation, but there is an error said "pointer can only be subtracted by pointer"
i think it's incorrect to subtract x[i] with only x
closed account (D80DSL3A)
Yes x[i] - x would be a problem. You need a different name for the array. Notice that shacktar used xArray[i] - x
oh thank you for all the helps... i've solved my problem :)
@shacktar: i mean, it should be like this right?

1
2
int i;
for (i = 0; /*blablabla*) */


btw, do you mean that you intentionally initialized i twice?
closed account (1vRz3TCk)
shacktar wrote:
Doing for(int i = 0; /*foo*/) is illegal in C.

It is legal in C99 (declarations and statements are also allowed to appear in any order within a block in C99).

Chipp,
int i = 0; is initialization ( an initial value is assigned at the point of declaration)
i = 0 is just assignment.

Initialization is good practice.
It is legal in C99

Heh, what do you know. Of course, this isn't the first time C99 has surprised me (I didn't know it supported variable length arrays until recently).
closed account (1vRz3TCk)
I must admit that I tend not to program to C99 standard due to the patchiness of compliant compilers.
Topic archived. No new replies allowed.