sigma in c programming

Sep 4, 2011 at 6:09am
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)
Sep 4, 2011 at 6:42am
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 Sep 4, 2011 at 6:45am
Sep 4, 2011 at 8:01am
@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
Sep 4, 2011 at 5:19pm
@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.
Sep 6, 2011 at 3:22am
@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
Sep 6, 2011 at 3:46am
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
Sep 6, 2011 at 3:50am
oh thank you for all the helps... i've solved my problem :)
Sep 6, 2011 at 7:12am
@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?
Sep 6, 2011 at 9:25am
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.
Sep 6, 2011 at 1:50pm
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).
Sep 6, 2011 at 2:22pm
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.