Sum of the series 1^1 + 2^2 + 3^3 + ... + n^n using recursion 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

66 Lectures 5.5 hours

In this problem, we are given a number n which defines the nth terms of the series 1^1 + 2^2 + 3^3 + … + n^n. Our task is to create a program that will find the sum of the series.

Let’s take an example to understand the problem,

Input

n = 4

Output

30

Explanation −sum = (1^1) + (2^2) + (3^3) + (4^4) = 1 + 4 + 9 + 16 = 30.

To solve this problem, we will loop from 1 to n. Find the square of each number. And add each to the sum variable.

Algorithm

Initialize sum = 0
Step 1: Iterate from i = 1 to n. And follow :
Step 1.1: Update sum, sum += i*i
Step 2: Print sum.

Example

Program to illustrate the working of our solution,

Live Demo

#include <iostream>
using namespace std;
long long calcSeriesSum(int n) {
long long sum = 0;
for( int i = 1; i <= n; i++ )
sum += (i*i);
return sum;
}
int main() {
int n = 7;
cout<<"Sum of the series 1^1 + 2^2 + 3^3 + ... + "<<n<<"^"<<n<<" is "<<calcSeriesSum(n);
return 0;
}

Output

Sum of the series 1^1 + 2^2 + 3^3 + ... + 7^7 is 140
Updated on 14-Aug-2020 14:09:35