Introduction
In this lab, we will learn how to write a C++ program to find the sum of a given series. The series is 1/2 + 4/5 + 7/8 ... n. We will take the value of n as input from the user and calculate the sum of the series.
In this lab, we will learn how to write a C++ program to find the sum of a given series. The series is 1/2 + 4/5 + 7/8 ... n. We will take the value of n as input from the user and calculate the sum of the series.
Create a new C++ file named main.cpp
in the ~/project
directory.
touch ~/project/main.cpp
In this program, we need to include the iostream and conio libraries. The iostream library is used for input and output operations and conio library is used to clear the console screen.
#include <iostream>
#include <conio.h>
In C++, the main() function is the starting point of the program execution. The first line of the main function is declared as int main()
and followed by opening and closing curly braces.
int main()
{
// Code goes here
return 0;
}
We need to declare the required variables to perform the calculation.
int i, n;
float sum = 0, x, a = 1;
We will prompt the user to enter the value of 'n' which represents the number of terms in the series.
std::cout << "Enter the number of terms: ";
std::cin >> n;
We will use a for loop to calculate the sum of the given series. The calculation is done as shown below:
for (i = 0; i < n; ++i) {
x = a / (a + 1);
sum += x;
a += 3;
}
We will now display the result of the sum of the given series.
std::cout << "Sum = " << sum;
This getch()
function is used to hold the console window open to display the result for the user to view the output.
getch();
The complete program is provided below.
#include <iostream>
#include <conio.h>
int main()
{
int i, n;
float sum = 0, x, a = 1;
// Prompt user to enter the number of terms
std::cout << "Enter the number of terms: ";
std::cin >> n;
// Loop to calculate the sum of the series
for (i = 0; i < n; ++i) {
x = a / (a + 1);
sum += x;
a += 3;
}
// Display the result
std::cout << "Sum = " << sum;
// Hold the console window open
getch();
return 0;
}
In this lab, we learned how to write a C++ program to find the sum of a given series. We accomplished this by performing the following steps: