Computer Science, asked by farzeenali2144, 8 months ago

Write a program to find the sum of the following series: 1-3+5-7+9..........n The value of n should be entered by the user in python

Answers

Answered by rajgargsai
0

Answer:

Given a series:

Sn = 1*3 + 3*5 + 5*7 + …

It is required to find the sum of first n terms of this series represented by Sn, where n is given taken input.

Examples:

Input : n = 2

Output : S<sub>n</sub> = 18

Explanation:

The sum of first 2 terms of Series is

1*3 + 3*5

= 3 + 15

= 28

Input : n = 4

Output : S<sub>n</sub> = 116

Explanation:

The sum of first 4 terms of Series is

1*3 + 3*5 + 5*7 + 7*9

= 3 + 15 + 35 + 63

= 116

Let, the n-th term be denoted by tn.

This problem can easily be solved by observing that the nth term can be founded by following method:

tn = (n-th term of (1, 3, 5, … ) )*(nth term of (3, 5, 7, ….))

Now, n-th term of series 1, 3, 5 is given by 2*n-1

and, the n-th term of series 3, 5, 7 is given by 2*n+1

Putting these two values in tn:

tn = (2*n-1)*(2*n+1) = 4*n*n-1

Now, the sum of first n terms will be given by :

Sn = ∑(4*n*n – 1)

=∑4*{n*n}-∑(1)

Now, it is known that the sum of first n terms of series n*n (1, 4, 9, …) is given by: n*(n+1)*(2*n+1)/6

And sum of n number of 1’s is n itself.

Now, putting values in Sn:

Sn = 4*n*(n+1)*(2*n+1)/6 – n

= n*(4*n*n + 6*n – 1)/3

Now, Sn value can be easily found by putting the desired value of n.

Below is the implementation of the above approach:

// C++ program to find sum of first n terms

#include <bits/stdc++.h>

using namespace std;

int calculateSum(int n)

{

// Sn = n*(4*n*n + 6*n - 1)/3

return (n * (4 * n * n + 6 * n - 1) / 3);

}

int main()

{

// number of terms to be included in the sum

int n = 4;

// find the Sn

cout << "Sum = " << calculateSum(n);

return 0;

}

Answered by Laxmipriyas007
1

Answer:

Python code for the problem:

def printSeries(n);

   sign = 1

   sm = 0

   for i in range(1, n+1, 2):

       sm = sm + (sign*i)

       sign = -(sign)

   return sm

C code for the problem:

int printSeries(int n) {

   sign = 1;

   sm = 0;

   for (int i=1; i<=n; i+2) {

       sm = sm + (sign*i);

       sign = -(sign);

   }

   return sm

}

Explanation:

Step for solving the problem:

  1. Start
  2. Take input from the user
  3. Assign sign = 1, to change sign after every element
  4. Assign sm = 0, which is the sum of the series.
  5. Run a for loop with increment of 2.
  6. Add i to the sm value with the sign.
  7. Return/print the sum of the given series.
  8. Stop

Two other problems in the same domain:

brainly.in/question/50278110

brainly.in/question/36399822

Similar questions