Program to print the sum of the series 1+(1+2)+...+(1+2+...n)

Code

# Writing a program to print the sum of the series 1+(1+2)+(1+2+3)....(1+2+3+n).
import math
n=int(input("Enter value of n you want to find the sum of the series:- "))
b=0
for i in range(1,n+1):
    for j in range(1,i+1):
       
        b=b+j
print(b)


Explanation

This Python program calculates the sum of the series:
1 + (1+2) + (1+2+3) + … + (1+2+3+…+n).

First, the math module is imported, though it is not actually used in the program. Then, the user is prompted to enter a value for n, which represents how many terms of the series will be summed.

A variable b is initialized to 0. This variable will store the final result of the series.

The program uses nested loops:

  • The outer loop (for i in range(1, n+1)) runs from 1 to n. Each iteration represents one term of the series.
  • The inner loop (for j in range(1, i+1)) calculates the sum of numbers from 1 to i.

Inside the inner loop, the value of j is added to b. This means:

  • When i = 1, it adds (1)
  • When i = 2, it adds (1+2)
  • When i = 3, it adds (1+2+3), and so on.

Thus, b accumulates the total of all partial sums.

Finally, print(b) displays the computed sum.

Comments

Popular posts from this blog

Resonance Effect

Linux Fundamentals