Summing Series


/* sum of the harmonic series */

#include <stdio.h>

int main() {

    int  i, n;
    float sum;

    n = 1000;
    sum = 0.0;

    for (i = 1; i <= n; i=i+1)
          sum = sum + 1.0/i;

    printf("Sum of %d terms is %f\n",n,sum);

}

A variable can be converted to another type by applying the operator called cast. For example if i is an integer, (float) i is the same number but considered as a float.
The same program as above but with doubles (double-precision floats) instead of floats:
#include <stdio.h>

int main() {

    int  i, n;
    double sum;

    n = 1000;
    sum = 0.0;

    for (i = 1; i <= n; i=i+1)
          sum = sum + 1/(double)i;

    printf("Sum of %d terms is %lf\n",n,sum);

}


While Loop



#include <stdio.h>

int main() {
   int i, n;
   double sum;
 
   n=1000;
   sum=0.0;
   i=1;

   while (i <= n) {
   sum = sum + 1/(double)i;
   i=i+1;
   }

    printf("Sum of %d terms is %lf\n",n,sum);
}


Do-While Loop


#include <stdio.h>

int main() {
   int i, n;
   double sum;

   n=1000;
   sum=0.0;
   i=1;

   do{
   sum = sum + 1/(double)i;
   i=i+1;   
   while(i <= n);

    printf("Sum of %d terms is %lf\n",n,sum);
}

If - Else Construction


#include <stdio.h>

int main() {

    int  i, n;
    double sum;

    n = 1000;
    sum = 0.0;

    for (i = 1; i <= n; i=i+1){
       if (i%2==1)
          sum = sum + 1/(double)i;
       else
          sum = sum - 1/(double)i;
}

    printf("Sum of %d terms is %lf\n",n,sum);

}