Program to find sum of given sequence in C++


In this article, we are given two numbers n and k representing a series. Our task is to create a program in C++ that finds the sum of the sequence given below:

The input cycle is the process of adding up all the numbers in the given sequence to get a single output. The process of recursion is frequently used in mathematics and may be implemented with sequences namely the arithmetic ones ( each term is acquired by adding a constant difference between the previous one) and the geometric sequence ( where each term is multiplied by a constant ratio with the former term ).

The sequence is −

(1*2*3*...*k) + (2*3*...k*(k+1)) + (3*4*...*k*k+1*k+2) + ((n-k+1)*(nk+
2)*... *(n-k+k).

Following is the Input and Output Scenario to find the sum of the given series till the nth term based on the given value of k.

Input

n = 4, k = 3

Output

30

Explanation

(1*2*3*....*k) + (2*3*....k*(k+1))
Series: (1*2*3) + (2*3*4) = 30

Solution Approach

A simple solution is to find the sum using iteration. We will use two loops, one for each term and the second for finding the value of the term. Then add the value of each term to get the result.

There are two approaches for this Problem −

  • Using Nested Loop
  • Using Single Loop

Using Nested Loop

Example

Following is the program to find the sum of the given sequence by using nested loops in C++ −

#include <iostream>
using namespace std;
int findSeriesSum(int n, int k){
   int sumVal = 0, term = 1;
   for(int i = 1; i <= (n-k + 1); i++){
      term = 1;
      for(int j = i; j< (k+i); j++){
         term *= j;
      }
      sumVal += term;
   }
   return sumVal;
}
int main(){
   int n = 4;
   int k = 3;
   cout<<"Sum of the series is: "<<findSeriesSum(n, k);
   return 0;
}

Output

Sum of the series is: 30

Using Single Loop

Let’s see another solution for the given problem. We will try for a more efficient approach that avoids nested loops and improves the time complexity.

Example

Below is a program in C++ that finds the sum of a given sequence using a single (without nested) loop −

#include <iostream>
using namespace std;
int findSeriesSum(int n, int k){
   int sumVal = 1;
   for(int i = n+1; i > n-k; i--)
   sumVal *= i;
   sumVal /= (k + 1);
   return sumVal;
}
int main(){
   int n = 4;
   int k = 3;
   cout<<"Sum of the series is: "<<findSeriesSum(n, k);
   return 0;
}

Output

Sum of the series is: 30

Updated on: 22-May-2024

571 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements