Introduction
In this lab, we will learn how to write a C++ program that calculates the sum of a series. The series we will be working with is the sum of the squares of reciprocal of natural numbers. In simple terms, the program calculates the sum of 1 + 1/2^2 + 1/3^3 + 1/4^4 + ... + 1/N^N.
Create a new file in the project directory
Create a new file named main.cpp in your project directory.
touch ~/project/main.cpp
Add necessary header files
Add the necessary header files to the program. In this program, we need iostream and cmath header files.
#include<iostream>
#include<cmath>
using namespace std;
Write the findsum() function
In this step, we will define the findsum() function that will be used to calculate the sum of the series. This function takes the value of N as input and returns the sum of the series.
double findsum(int N) {
double sum = 0;
for(int i=1; i<=N; i++) {
sum += pow((double)1/i,i);
}
return sum;
}
In the above code, we have used the pow() function from <cmath> header file to calculate the power of each term. We are also using the double data type to get accurate values.
Write the main() function
In this step, we will write the main() function that will take input from the user in the form of an integer N. Then we will call the findsum() function to calculate the sum of the series. Finally, we will print the result.
int main() {
int N;
cout << "Enter the value of N: ";
cin >> N;
double sum = findsum(N);
cout << "Sum of the series is: " << sum << endl;
return 0;
}
Compile and run the program
Save the changes made to main.cpp file and run the following command in your terminal:
g++ main.cpp -o main && ./main
After successful compilation and run, it will ask the user to enter the value of N. After entering the value of N, the program will return the sum of the series.
Full code of main.cpp file
#include <iostream>
#include <cmath>
using namespace std;
double findsum(int N) {
double sum = 0;
for(int i=1; i<=N; i++) {
sum += pow((double)1/i,i);
}
return sum;
}
int main() {
int N;
cout << "Enter the value of N: ";
cin >> N;
double sum = findsum(N);
cout << "Sum of the series is: " << sum << endl;
return 0;
}
Summary
In this lab, we learned how to write a C++ program that calculates the sum of a series. We used a loop to iterate through all the terms and added them up to get the sum of the series. We also used the pow() function to calculate the power of each term.



