Loop Assignment 25 — Sum of Series 1 + 1/2² + 1/3² + … + 1/N² Using For Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Sum of the Series 1 + 1/2² + 1/3² + … + 1/N² Using a For Loop

📑 On this page:
  • Why 1.0 and Not 1?
  • The Algorithm in Three Lines
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • Why 1 / (i * i) silently returns 0 for every term, and how to fix it
  • Why the accumulator must be double, not int or float
  • How a simple for loop builds the sum term by term from 1 to N
  • Why this series converges to π²/6 ≈ 1.644934 as N grows — and why that matters
  • Why the loop is O(N) and how it compares to the O(log N) digit-count loop

Why 1.0 and Not 1?

Here's the single biggest trap in this program: writing sum = sum + 1 / (i * i) with an int or even a double accumulator will produce zero for every term after the first. The reason is C's integer division rule: when both operands are integers, the result is an integer with the fractional part discarded. 1 / 4 is 0, not 0.25. 1 / 9 is 0. The whole series collapses to just 1 plus a string of zeros.

The fix is one character: write 1.0 / (i * i) instead of 1 / (i * i). Because 1.0 is a double, C promotes i * i to double before dividing, and the division becomes floating-point. Now 1.0 / 4 is 0.25, 1.0 / 9 is 0.111…, and the series actually sums.

This is the same lesson that shows up in every "sum of a fraction series" assignment. The loop logic is almost trivial — add a term, increment i, repeat — but the type of the constant 1 determines whether the program works or silently gives the wrong answer. It's a one-character bug that produces no compiler error and no warning. You have to know it's there.

💡 In one line: 1 / (i * i) is integer division and returns 0 for every i > 1. Write 1.0 / (i * i) to force floating-point division.

Diagram showing the series 1 + 1/2² + 1/3² + ... + 1/N² with terms 1, 0.25, 0.111, 0.0625 and the sum approaching 1.644934

The Algorithm in Three Lines

In pseudocode, the series is just a running total:

sum = 0.0
for i = 1 to N:
    sum = sum + 1.0 / (i * i)
print sum
                                

Three lines, and the rest of the program is input, validation, and output. The for loop is the natural choice here because the number of iterations is known before the loop starts: exactly N terms.

N Sum Why this is worth checking
11.000000Only the first term — the loop runs once
21.250000Adds 1/4 — first fractional term
31.361111Adds 1/9 ≈ 0.111
101.549768Approaching the limit but still visibly below
1001.634984Within 0.01 of the infinite sum
10001.643935Very close — the tail is tiny
∞1.644934π²/6 — the Basel problem limit

The sum increases quickly at first and then flattens out. After 100 terms you're already within 0.01 of the limit; after 1000 terms, within 0.001. The remaining terms add up to less and less because 1/i² shrinks quadratically.

Complete C Program

Program: sum of reciprocal squares using a for loop

#include <stdio.h>

int main(void) {
    int n;

    printf("Enter the number of terms (N): ");
    if (scanf("%d", &n) != 1 || n < 1) {
        printf("Invalid input. Enter a positive integer.\n");
        return 1;
    }

    double sum = 0.0;
    for (int i = 1; i <= n; i++) {
        sum += 1.0 / (i * i);   /* 1.0, not 1 — forces double division */
    }

    printf("Sum of the series 1 + 1/2^2 + ... + 1/%d^2 = %.6f\n", n, sum);
    return 0;
}
                                    

And here's a variant that prints each term as it goes, which is useful for tracing and for seeing the series build up:

Variant with term-by-term output

#include <stdio.h>

int main(void) {
    int n;
    printf("Enter N: ");
    scanf("%d", &n);

    double sum = 0.0;
    for (int i = 1; i <= n; i++) {
        double term = 1.0 / (i * i);
        sum += term;
        if (i <= 5 || i == n)
            printf("i = %-3d  term = %.8f  running sum = %.8f\n", i, term, sum);
        else if (i == 6)
            printf("...\n");
    }

    printf("Final sum = %.6f\n", sum);
    return 0;
}
                                    

The first variant is the one to submit for the assignment. The second is for understanding — watching the running sum approach the limit one term at a time is a good way to internalise why the series converges.

Program Output

Enter the number of terms (N): 10
Sum of the series 1 + 1/2^2 + ... + 1/10^2 = 1.549768
                                

Try a few more. Input 1 and you should get exactly 1.000000. Input 100 and you should get approximately 1.634984. Input 1000 and you should get approximately 1.643935. The larger N gets, the closer the sum creeps to 1.644934 — the value of π²/6, the famous Basel problem result that Euler solved in 1734 [citation:8].

Step-by-Step Explanation

Let's walk through N = 5 and then look at the type rules that make or break the program.

1. Reading and validating input

scanf("%d", &n) reads an integer. The combined check != 1 || n < 1 catches both a failed read (user typed letters) and a semantically invalid input (zero or negative N). The series starts at i = 1, so N must be at least 1. Without this check, N = 0 would skip the loop entirely and print a sum of 0.0 — which is not wrong, exactly, but is not the series the user asked for.

2. The accumulator type

double sum = 0.0; — the accumulator must be double (or float, but double gives better precision for little cost). If you declare int sum = 0, every fractional term truncates to 0 and the sum stays at 1. If you declare float sum, you lose precision around the 7th decimal digit, which is fine for this assignment but bad practice for a series that converges slowly. double gives about 15 significant digits, which is more than enough.

3. The loop and the critical 1.0

For N = 5, the loop runs like this:

  1. i = 1: term = 1.0 / 1 = 1.000000, sum = 1.000000
  2. i = 2: term = 1.0 / 4 = 0.250000, sum = 1.250000
  3. i = 3: term = 1.0 / 9 ≈ 0.111111, sum ≈ 1.361111
  4. i = 4: term = 1.0 / 16 = 0.062500, sum ≈ 1.423611
  5. i = 5: term = 1.0 / 25 = 0.040000, sum ≈ 1.463611
  6. i = 6: condition i <= 5 is false — loop exits

Final sum ≈ 1.463611. Notice how the terms shrink: 1, 0.25, 0.111, 0.0625, 0.04. The first two terms account for most of the sum; the rest add smaller and smaller corrections. That's why the series converges — the tail is dominated by tiny terms.

4. Why 1 / (i * i) fails

In C, 1 is an int and i * i is an int. Integer division truncates toward zero: 1 / 4 = 0, 1 / 9 = 0, and so on. The only iteration where the term is non-zero is i = 1, where 1 / 1 = 1. So the "sum" comes out as exactly 1.0 no matter what N is. This is one of the most common bugs in series-summing programs, and it produces no compiler warning because the code is syntactically correct — it's semantically wrong.

5. Why the loop is O(N)

The loop runs exactly N times, and each iteration does a constant amount of work (one multiplication, one division, one addition). So the time complexity is O(N). This is different from the digit-counting loop, which is O(log N) because dividing by 10 shrinks the input exponentially fast. Here, adding one more term requires one more iteration — linear, not logarithmic. For N up to a few million, this is still fast on modern hardware; for truly huge N, the series converges so slowly that the sum barely changes, so there's no practical reason to go beyond N = 10⁶ or so.

6. The Basel problem connection

The infinite series ∑ 1/n² has a closed-form sum: π²/6 ≈ 1.644934. This was a famous open problem in the 17th century — Bernoulli and others tried and failed to find the exact value. Euler solved it in 1734, and the result made him famous [citation:8]. The finite sum your program computes approaches this limit as N grows: N = 10 gives 1.549768, N = 100 gives 1.634984, N = 1000 gives 1.643935. The convergence is slow — you need about 10⁶ terms to get 6 decimal places of accuracy — but it does converge, and that's the mathematical fact behind the program.

🎯 Remember this: write 1.0, not 1. Use double, not int. The for loop is natural because N is known. And the series converges to π²/6 — a result worth knowing if you ever get asked about it in an interview.

Frequently Asked Questions

1. Why does my program always output 1.000000 no matter what N is?

You're using 1 / (i * i) instead of 1.0 / (i * i). Integer division truncates every term except the first to 0. Change the constant to 1.0 (or cast one operand to double) and the fractional terms will appear.

2. Can I use float instead of double?

Yes, but double is better. float has about 7 significant decimal digits; double has about 15. For this series, which converges slowly, the extra precision helps you see the difference between N = 1000 and N = 10000. The memory cost of double (8 bytes vs 4) is irrelevant here.

3. Why does the series converge to π²/6?

That's the Basel problem, solved by Euler in 1734. The proof is non-trivial and involves either Fourier series, complex analysis, or a clever integral identity. For this assignment, you don't need the proof — just know that the limit exists and equals approximately 1.644934. Your program approximates it from below as N increases.

4. How many terms do I need to get 6 decimal places of accuracy?

About one million. The tail of the series after N terms is roughly 1/N, so to get an error below 10⁻⁶ you need N ≈ 10⁶. That's why the series is said to converge slowly — you get about one extra decimal digit for every tenfold increase in N. For a classroom assignment, N = 100 or 1000 is fine; the point is the loop, not the numerical analysis.

5. Why use a for loop instead of while?

Because the number of iterations is known in advance: exactly N terms. A for loop puts the initialization, condition, and increment on one line, which makes that structure explicit. A while loop would work too, but it's better suited to cases where the iteration count is unknown (like the digit-extraction loop, which runs until N becomes 0).

6. What if N is very large, like 10⁹?

The loop will run for a long time — O(N) means a billion iterations, which takes seconds to minutes depending on hardware. And the sum won't change much: after about 10⁶ terms, adding more terms changes the result by less than 10⁻⁶. In practice, if you only need a few decimal places, stop at N = 10⁶ or so. If you need more precision, you'd need a different approach (like Euler-Maclaurin summation) rather than brute-force looping.

💡 Tip: After this program, try the same series with a while loop and a do-while loop. The output should be identical. Then try the alternating version 1 − 1/2² + 1/3² − 1/4² + … — it converges to π²/12 ≈ 0.822467, and the sign alternation adds an interesting twist to the loop body.

📖 Related Tutorials

  • 26. Sum of the Series 1! + 2! + 3! + … + N! Using a For Loop
  • 27. Generate the First N Terms of the Tribonacci Sequence Using a While Loop
  • 28. Find the Largest Prime Factor Using a While Loop
  • 29. Iterative Binary Search Using a While Loop
  • 30. Check Amicable Numbers Using a For Loop
  • C FOR Loop
  • While Loop
  • All 30 Loop Assignments

Previous Topic: -->> 24. Full Symmetric Number Pyramid Using Nested While Loops   ||   Next Topic: -->> 26. Sum of the Series 1! + 2! + 3! + … + N! Using a For Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.