

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find sum of given sequence in C++
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
#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
#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
- Related Questions & Answers
- C# Program to find the sum of a sequence
- C++ Program to Find the Longest Increasing Subsequence of a Given Sequence
- C++ Program to Find the Longest Prefix Matching of a Given Sequence
- C++ Program to find out the distinct elements in a given sequence
- Program to find sum of elements in a given array in C++
- Program to find last digit of the given sequence for given n in Python
- C/C++ Program to find the sum of elements in a given array
- C++ Program to Generate Randomized Sequence of Given Range of Numbers
- Program to find nth sequence after following the given string sequence rules in Python
- Find element position in given monotonic Sequence in C++
- C++ program to find sequence of indices of the team members
- C# Program to find the average of a sequence of numeric values
- Program to find sum of harmonic series in C++
- Program to find the sum of all digits of given number in Python
- 8086 program to find sum of Even numbers in a given series
Advertisements