Sum Series From User Input

Beginner

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.

Create a new C++ file

Create a new C++ file named main.cpp in the ~/project directory.

touch ~/project/main.cpp

Include Libraries

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>

Start the main function

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;
}

Declare required variables

We need to declare the required variables to perform the calculation.

    int i, n;
    float sum = 0, x, a = 1;

Get input from the user

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;

Calculate the sum of the series

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;
    }

Display the result

We will now display the result of the sum of the given series.

    std::cout << "Sum = " << sum;

Add a delay before closing the console window

This getch() function is used to hold the console window open to display the result for the user to view the output.

    getch();

Complete the program

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;
}

Summary

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:

  • Including required libraries
  • Starting the main function
  • Declaring required variables
  • Getting input from the user
  • Calculating the sum of the series using a loop
  • Displaying the result to the user
  • Adding a delay before closing the console window

Other Tutorials you may like