Calculation of Summation in C++


In Mathematics we have studied “SUMMATION“. the below example provides you the C++ code to find summation of several numbers in C++. We can take the inputs from the user to create a type of series and then find the summation, we just have to change the statement inside the for loop for the desired formula, but here we considered it for summation of even numbers from 1 to 100. Lets look at the code :

    //Calculating Summation with "for loop".
    #include <iostream>
    using namespace std;
    int main()
        int sum = 0; // initialize sum
        // sum even integers from 2 through 100
        for ( int number = 2; number <= 100; number += 2 )
           //Put your formula here
           sum += number; // add number to sum
        cout << "Sum is " << sum << endl; // output sum
        return 0;

In the above example we initialized the variable “sum” from 0, now in the for loop we started the variable “number” from 2, because the summation will start from 2, now in the condition we made it limited up to 100, and in the increment we increased it by 2. So in this case we are going to find summation of series of even numbers from 2 to 100. Inside the body of the loop we added the “number” increased by 2 after every cycle in “sum”. At the end when we got the completion of summation, we printed the summation on the screen.