Sunday, July 26, 2009

Simple C one dimensional array help?

Write a program using a single-subscripted variable to evaluate the following expressions:





Total = summation of x^2 with 10 being on the top of the sigma or whatever and i=1 to start.


The values of x1, x2, … are read from the terminal. You need to use a one-dimensional array x to read the values and compute the sum of their squares

Simple C one dimensional array help?
According to the problem statement, the values of x are input from stdin. I'll give some tips on how to fix your code. I didn't compile and test it, you'll have to do that.





#define N 10





int main(int argc, char *argv[]) {


int a[N];


int i, sum = 0;





/* you might want to use double for a[ ] */


/* and sum, to help if large values are input */





for (i = 0; i %26lt; N; i++) {


/* read input */


if (scanf("%d",%26amp;a[i]) == 1) {


/* you only want the squares, so */


/* you can do it in place */


a[i] = a[i] * a[i];


} else {


/* bad entry - you may want to print an */


/* error message and prompt for retry */


}


}





/* compute the sum of the squares */


for (i = 0; i %26lt; N; i++) {


sum += a[i];


}


return 0;


}
Reply:The array holds the data. One dimensional; a(1)=1, a(2)=2 etc.


Then you need to set up a loop which contains the formula (number squared) Another instruction reads the data from the array, incrementing by one each time round the loop. You also need a print instruction either in the loop or as a total outside the loop.


This is how I would (attempt) to do it in BASIC anyway
Reply:That sounds like your homework, and I'm not doing it for you!


No comments:

Post a Comment