Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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);
}

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

like image 282
Chinmay Vemuri Avatar asked Oct 16 '19 08:10

Chinmay Vemuri


People also ask

What is the sum to n terms of the Series 1 * 3 * 5?

We have found the sum of n terms of the series 1, 3, 5, 7, …… is n2. ∴ The sum of series 1, 3, 5, 7, 9,…… up to n terms is n2.

What is the sum of a series of numbers upto n terms?

The sum of n terms of AP is the sum(addition) of first n terms of the arithmetic sequence. It is equal to n divided by 2 times the sum of twice the first term – 'a' and the product of the difference between second and first term-'d' also known as common difference, and (n-1), where n is numbers of terms to be added.

What is the formula for summation of 1 2 3 n?

Hence the sum of 1 , 2 , 3 , ⋯ , n is n n + 1 2 .


2 Answers

The problem in your code lies on this line:

c = c + (1/i);

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);
like image 69
Adrian Mole Avatar answered Nov 07 '22 05:11

Adrian Mole


I agree with Adrian's answer.

Another issue is because of the way floating point numbers are represented in a system when they are added in arbitrary order, precision can be lost.

To have maximum precision, floating point numbers should be added from smallest first to largest last.

like image 43
Robert Andrzejuk Avatar answered Nov 07 '22 05:11

Robert Andrzejuk