Program to Find sum of series 1+(1+3)+(1+3+5)+....+N

Problem statement:- Program to Find the sum of series 1+(1+3)+(1+3+5)+....+N.

Example:    

                Input: n=5

                Output: The sum of the series = 14 /* sum series =                                                                                1+(1+3)+(1+3+5)=1+4+9=14*/

              

                Input: n=8

                Output: The sum of the series = 30 /* sum series =                                                                                1+(1+3)+(1+3+5)+(1+3+5+7)=1+4+9+16=30*/


 Data requirement:-

   Input Data:- n

  Output Data:-sum

  Additional Data:- i, j

Program in C
  
Here is the source code of the C Program to find the sum of series 1+(1+3)+(1+3+5)+....+N.

Code:

#include<stdio.h>
int main()
{
    int n,i=1,sum=0,j;
    printf("Enter the range of number:");
    scanf("%d",&n);

  while(i<=n)
    {
    for(j=1;j<=i;j+=2){
        sum+=j;
        }
        i+=2;
    }

    printf("The sum of the series = %d",sum);
}

Input/Output:
Enter the range of number:5
The sum of the series = 14

Program in C++
  
Here is the source code of the C++ Program to find the sum of series 1+(1+3)+(1+3+5)+.... +N.

Code:

#include<iostream>
using namespace std;
int main()
{
    int n,i=1,sum=0,j;
    cout<<"Enter the range of number:";
    cin>>n;
      while(i<=n)
    {
    for(j=1;j<=i;j+=2){
        sum+=j;
        }
        i+=2;
    }
    cout<<"The sum of the series = "<<sum;
}

Input/Output:
Enter the range of number:8
The sum of the series = 30

Program in Java
  
Here is the source code of the Java Program to find the sum of series 1+(1+3)+(1+3+5)+.... +N.

Code:

import java.util.Scanner;
public class p25 {

public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
    int n,i=1,sum=0,j;
    
    System.out.println("Enter the range of number:");
    n=cs.nextInt();
    while(i<=n)
    {
    for(j=1;j<=i;j+=2){
        sum+=j;
        }
        i+=2;
    }
    System.out.println("The sum of the series = "+sum);
    cs.close();
}
}

Input/Output:
Enter the range of number:
12
The sum of the series = 91

Program in Python
  
Here is the source code of the Python Program to find the sum of series 1+(1+3)+(1+3+5)+ ....+N.

Code:

print("Enter the range of number(Limit):")
n = int(input())
i = 1
sum = 0
while (i <= n):
    for j in range(1, i + 1,2):
        sum+=j
    i += 2
print("The sum of the series = ", sum)

Input/Output:
Enter the range of number(Limit):
25
The sum of the series =  819


Post a Comment

0 Comments