C++ Program to Find Series Sum

Beginner

Introduction

In this lab, we will write a C++ program to find the sum of a series generated from an input value x and the number of terms n. The series follows the pattern x + x^2/2 + x^3/3 + ... + x^n/n.

Create a new C++ file

Create a new C++ file in the ~/project directory and name it main.cpp.

touch ~/project/main.cpp

Include the necessary Libraries

We will be using the iostream and math.h libraries in this program as we need mathematical operations in our program. So, include these libraries at the top of the code file as given below:

#include<iostream>
#include<math.h>
using namespace std;

Write the main() function

In our main() function, we will declare the input variables, x, n and sum.

int main()
{
    int i,n;
    float x,sum=0;
}

Take user input for x and n

In this step, we will take the user input values for x and n. Prompt the user to enter the two values and take the input using cin.

cout<<"\nx + x^2/2 + x^3/3 + ... + x^n/n\n";
cout<<"\nEnter value of x and n :\n";
cin>>x>>n;

Calculate the sum of the series

In this step, we will use a for loop for the the number of terms n and calculate the sum using the given formula. We will add each pow(x, i)/i expression to the previous sum value at each iteration.

for(i=1;i<=n;++i)
{
    sum+=pow(x,i)/i;
}

Display the Result

Finally, we will output the sum of the series generated by the input values given by the user.

cout<<"\nSum is = "<<sum<<endl;

Compile and Run the code

To compile the code, open the terminal and navigate to the ~/project directory. Type the following command in the terminal:

g++ main.cpp -o main && ./main

Full code for the main.cpp file

#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    int i,n;
    float x,sum=0;

    cout<<"\nx + x^2/2 + x^3/3 + ... + x^n/n\n";
    cout<<"\nEnter value of x and n :\n";
    cin>>x>>n;

    for(i=1;i<=n;++i)
    {
        sum+=pow(x,i)/i;
    }
    cout<<"\nSum is = "<<sum<<endl;
    return 0;
}

Summary

In this lab, we learned how to write a C++ program to find the sum of a series generated by an input value x and the number of terms n. We used the math.h library to compute mathematical operations and utilized a for loop structure to iterate through the number of input terms.

Other Tutorials you may like