0

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?

el_noobito
  • 67
  • 6
  • 1
    Welcome to SO. You are doing integer divisions. This means `1/i == 0` for any `i != 1` and `1 + 0 + 0 + 0 ... == 1` – Gerhardh Dec 02 '21 at 20:51
  • You have integer sum too, so that will also dump any fractional part. – Weather Vane Dec 02 '21 at 20:51
  • You are missing the concept of _integer division_. The idea that an _int_ divided by an _int_ will produce an _int_ as output, and therefore cannot represent a fraction like 1/3 -- and all that entails. And you haven't learned the typical workaround which is to cast one (or more) of the operands to be a floating point type, which will result in a floating point division and a floating point result. I acknowledge that your code seems logical, but unfortunately it just doesn't do what you intended given the behaviour of C with respect to the division operator. – Wyck Dec 02 '21 at 20:58

1 Answers1

1

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

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
D-FENS
  • 1,438
  • 8
  • 21