Series: 1 + 1/3 + 1/5 +...upto N terms

Chi*_*uri 5 c loops series

I was recently asked this question in a programming test. I can't seem to understand why I am getting the answer '1'. I am a beginner in the C programming language.

Here is my code:

#include<stdio.h>
int main()
{
    float c = 0;
    int n, i = 1;
    printf("Enter the number here: ");
    n = getchar();
    while (i <= 2*n - 1)
    {
        c = c + (1/i);
        i = i + 2;
    }
    printf("%f", c);
}
Run Code Online (Sandbox Code Playgroud)

I have already tried using a for loop, but the answer remains the same. Any help would be appreciated!

Adr*_*ica 10

The problem in your code lies on this line:

c = c + (1/i);
Run Code Online (Sandbox Code Playgroud)

Here, the operation performed inside the parentheses is integer division! So, when i has any value greater than 1, the result will be zero. This zero is then converted to a float value.

To force the compiler to use floating point division, use this:

c = c + (1.0/i);
Run Code Online (Sandbox Code Playgroud)