# Program to find sum of given sequence in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

In this problem, we are given two numbers n and k for a series. Our task is to create a program to find sum of given sequence in C++.

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).

Problem description − Here, we will find the sum of the given series till nth term based on the given value of k.

Let’s take an example to understand the problem

## Input

n = 4, k = 3

## Output

30

## Explanation

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 second for finding the value of the term. Then adding the value of each term to get the result.

Program to illustrate the working of our solution

## Example

Live Demo

#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, k = 3;
cout<<"The sum of series is "<<findSeriesSum(n, k);
return 0;
}

## Output

The sum of series is 30

This solution is not efficient as it needs a nested loop that makes the time complexity of the order O(n2).

Program to illustrate the working of our solution

## Example

Live Demo

#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, k = 3;
cout<<"The sum of series is "<<findSeriesSum(n, k);
return 0;
}

## Output

The sum of series is 30
Updated on 16-May-2022 07:28:36