Program to print series 1,-2,6,-15,31...N

Problem statement:- Program to print series 1,-2,6,-15,31...N.

Example:    

                Input: n=5

                Output: 1 -2 6 -15 31   /* 1  (0+2)*-1  (2+2²)  (6+3²)*-1 (15+4²)*/


 Data requirement:-

   Input Data:- n

  Output Data:-pr

  Additional Data:- i.

Program in C
  
Here is the source code of the C Program to print series 1,-2,6,-15,31...n.

Code:

#include<stdio.h>
#include<math.h>
int main()
{
    int n,i,pr=1;
    printf("Enter the range of number(Limit):");
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {

       if(i%2==0)
        {
            printf("%d ",-1*pr);
        }
        else
        {
            printf("%d ",pr);
        }
        pr=pr+pow(i,2);
    }
}

Input/Output:
Enter the range of number(Limit):5
1 -2 6 -15 31

Program in C++

Here is the source code of the C++ Program to print series 1,-2,6,-15,31...n.

Code:

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    int n,i,pr=1;
    cout<<"Enter the range of number(Limit):";
    cin>>n;
    for(i=1;i<=n;i++)
    {

       if(i%2==0)
        {
            cout<<-1*pr<<" ";
        }
        else
        {
            cout<<pr<<" ";
        }
        pr=pr+pow(i,2);

    }
}

Input/Output:
Enter the range of number(Limit):7
1 -2 6 -15 31 -56 92

Program in Java

Here is the source code of the Java Program to print series 1,-2,6,-15,31...n.

Code:

import java.util.Scanner;
public class Print_Series5 {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n,i,pr=1;
   System.out.printf("Enter the range of number(Limit):");
    n=sc.nextInt();
    for(i=1;i<=n;i++)
    {
    if(i%2==0)
        {
    System.out.print(-1*pr+" ");
        }
        else
        {
        System.out.print(pr+" ");
        }
        pr=(int) (pr+Math.pow(i,2));

    }
    sc.close();
}
}

Input/Output:
Enter the range of number(Limit):6
1 -2 6 -15 31 -56 

Program in Python

Here is the source code of the Python Program to print series 1,-2,6,-15,31...n.

Code:

n=int(input("Enter the range of number(Limit):"))
i=1
pr=1
while i<=n:
    if(i%2==0):
        print(-1*pr,end=" ")
    else:
        print(pr, end=" ")
    pr+=pow(i,2)
    i+=1

Input/Output:
Enter the range of number(Limit):9
1 -2 6 -15 31 -56 92 -141 205 


Post a Comment

0 Comments