Re: Steve Summit C notes , exercise



arnuld wrote:
this is the programme i created, for exercise 2, assignment 3 at

http://www.eskimo.com/~scs/cclass/asgn.beg/PS2.html

it runs fine. i wanted to know if it needs any improvement:

----------------- PROGRAMME ----------------------------
/* Steve Summit's C programming

Section 3 :: exercise 2

STATEMENT:
Write a program to compute the average of the ten numbers 1, 4,
9, ..., 81, 100,
that is, the average of the squares of the numbers from 1 to 10. (This
will be a
simple modification of Exercise 3 from last week: instead of printing
each square
as it is computed, add it in to a variable sum which keeps track of
the sum of all
the squares, and then at the end, divide the sum variable by the
number of numbers summed.)

*/

#include <stdio.h>

#define DIVISOR 10

int main()
{
int i;
double sum;

You can probably make this an int. The square of an int is still an int (providing no overflows). It's generally faster using ints than doubles.


sum = 0;
for(i = 0; i <= 10; ++i)

To make your code portable, some might say to use
for (i=1; i<=DIVISOR; i++)

the ordering of ++i or i++ doesn't matter here.

sum += i*i;

printf("the average is: %.1f\n", sum / DIVISOR);

if you take my advice above about using an int above, just be careful to promote sum to a float here, e.g. (float)sum / DIVISOR


return 0;

}

----------------------- OUTPUT ----------------------
[arch@voodo steve-summit]$ gcc -std=c99 -pedantic -Wall -Wextra
assign-3_ex-2.c
[arch@voodo steve-summit]$ ./a.out
the average is: 38.5
[arch@voodo steve-summit]$

.



Relevant Pages

  • Segmentation Fault....
    ... // - Sum of numbers squared ... double vsum(double x, int n){ ... float Result = 0; ... //Calculation for - Mean of the squares ...
    (comp.lang.c)
  • Steve Summit C notes , exercise
    ... this is the programme i created, for exercise 2, assignment 3 at ... the average of the squares of the numbers from 1 to 10. ... the sum of all ...
    (comp.lang.c)
  • Re: Segmentation Fault....
    ... // - Sum of numbers squared ... double vsum(double x, int n){ ... float Result = 0; ... //Calculation for - Mean of the squares ...
    (comp.lang.c)
  • Re: Steve Summit C notes , exercise
    ... /* Steve Summit's C programming ... the average of the squares of the numbers from 1 to 10. ... simple modification of Exercise 3 from last week: ... the sum of all ...
    (comp.lang.c)
  • Re: Steve Summit C notes , exercise
    ... the average of the squares of the numbers from 1 to 10. ... simple modification of Exercise 3 from last week: ... the sum of all ... int main ...
    (comp.lang.c)