Search code examples
cloopsfor-loopsumfractions

Sum with a fraction with an index returns 1


I want to sum of all the fractions from 1 to 1/100, but when I compile the following code i get "1".

#include <stdio.h> 

main(){ 
    int i,sum; 
    sum=0;
    for (i=1;i<=100;i++){ 
        sum=sum+(1/i);
    }
printf("%d",sum);
}

Shouldn't the for loop return

  • i=1 --> sum=0+(1/1)
  • i=2 --> sum=1+(1/2)
  • i=3 --> sum= 3/2 + (1/3)

What am I missing here?


Solution

  • Because you are using integers, 1/i always rounds to 0, so your sum never changes. Replace int with float or double.