Skip to content
doubtly

Write a program to compute sum of series. s = 1+ (1 / 2) + ( 1 / 3 )+ ( 1 / 4 )+ ( 1 / 5 )+………+ ( 1 / n )

Write a program to compute sum of series.

s = 1+ (1 / 2) +   ( 1 / 3 )+  ( 1 / 4 )+  ( 1 / 5 )+………+  ( 1 / n )

Do modification in above program to display following pattern

s = 1+  ( 1 / 2 ! ) +   ( 1 / 3 ! )+  ( 1 / 4 ! )+  ( 1 / 5 !)+………+  ( 1 / n !)

Doubtly Asked Updated Student doubt Save WhatsApp Report

2 answers

Best answer

Answer: Add 1.0/i for i = 1 to n; for the modified series keep a running factorial (fact = fact × i) and add 1.0/fact.

Logic:

  • Series 1: \( s = \sum_{i=1}^{n} \frac{1}{i} \). Use 1.0 so that the division is not integer division.
  • Modified series: \( s = \sum_{i=1}^{n} \frac{1}{i!} \). Instead of recomputing i! each time, multiply the previous factorial by i.

Program:

#include <stdio.h>

int main()
{
    int n, i;
    float sum1 = 0, sum2 = 0;
    double fact = 1;

    printf("Enter n: ");
    scanf("%d", &n);

    /* Series 1: 1 + 1/2 + 1/3 + ... + 1/n */
    for (i = 1; i <= n; i++)
        sum1 = sum1 + 1.0 / i;
    printf("1 + 1/2 + ... + 1/%d = %f\n", n, sum1);

    /* Modified series: 1 + 1/2! + 1/3! + ... + 1/n! */
    for (i = 1; i <= n; i++)
    {
        fact = fact * i;          /* fact now holds i! */
        sum2 = sum2 + 1.0 / fact;
    }
    printf("1 + 1/2! + ... + 1/%d! = %f\n", n, sum2);

    return 0;
}

Sample output (actual run):

Enter n: 5
1 + 1/2 + ... + 1/5 = 2.283334
1 + 1/2! + ... + 1/5! = 1.716667

Check for n = 5: \( 1 + 0.5 + 0.3333 + 0.25 + 0.2 = 2.2833 \) and \( 1 + 0.5 + 0.1667 + 0.0417 + 0.0083 = 1.7167 \).

Doubtly · 23 Apr 2022 Report
Was this answer helpful?

Use a loop that adds \(1/i\) for \(i = 1\) to \(n\); for the second series keep a running factorial and add \(1/i!\).

(a) \(s = 1 + \frac12 + \frac13 + \dots + \frac1n\)

#include <stdio.h>
int main() {
    int n, i;
    float s = 0;
    printf("Enter n: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++)
        s = s + 1.0 / i;
    printf("Sum = %f\n", s);
    return 0;
}

Writing 1.0 / i (not 1 / i) makes the division real; with integers, 1/2 would give 0.

(b) Modified: \(s = 1 + \frac1{2!} + \frac1{3!} + \dots + \frac1{n!}\)

#include <stdio.h>
int main() {
    int n, i;
    float s = 0, fact = 1;
    printf("Enter n: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        fact = fact * i;      /* now fact = i! */
        s = s + 1 / fact;
    }
    printf("Sum = %f\n", s);
    return 0;
}

In each pass fact is multiplied by i, so it holds \(i!\) without a separate inner loop. The first term is \(1/1! = 1\). For \(n = 3\): \(1 + 0.5 + 0.1667 = 1.6667\).

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.