Sum Series Using C++

Beginner

Introduction

In this lab, you will learn how to write a C++ program to find the sum of a series. We will go through two different methods to find the sum of the series 1 + 2 + 3 + 4 + ... + n. You will be able to understand and write C++ codes more efficiently.

Declare Header Files and Namespaces

The path of the code file is ~/project/main.cpp.

In this step, we will declare the necessary header files and namespaces to start coding in C++.

#include<iostream>
using namespace std;

Define Function to Find Sum of Series (First Method)

We will now define a function to find the sum of a given series using the first method. It takes an integer number as input and returns the sum of the series.

int findSumMethodOne(int num){
    int sum = 0;
    for(int i = 0; i < num; i++){
        sum = sum + i;
    }
    return sum;
}

Define Function to Find Sum of Series (Second Method)

We will now define a function to find the sum of a given series using the second method. It takes an integer number as input and returns the sum of the series.

int findSumMethodTwo(int num){
    int sum = 0;
    sum = num * (num + 1) / 2;
    return sum;
}

Main Function

In this step, we will define the main function and ask the user to input the value of 'n' for which the sum of the series is to be calculated.

int main(){
    int n;
    cout<<"Enter the value of n, till which sum is required: ";
    cin>>n;
    cout<<"Method One: "<<findSumMethodOne(n)<<endl;
    cout<<"Method Two: "<<findSumMethodTwo(n)<<endl;
    return 0;
}

To run the C++ code use the following commands:

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

Summary

In this lab, we have learned how to write a C++ program to find the sum of a series using two different methods. We implemented a for loop to loop through the values of n and adding them to the sum. Also, we used the sum formula directly to find the answer. This lab has helped you in understanding the two different methods to find the sum of an arithmetic series.

Other Tutorials you may like