How to Calculate Series Summation Using the for Loop in C++
In this tutorial, we will learn how to calculate the sum of a series using a for
loop in C++. But, let’s first discuss the concept of the for
loop.
the for
Loop in C++
The for
loop is a control flow statement in C++ that allows us to iterate over a series of values. The syntax of the for
loop is as follows:
for (initializer; condition; incrementer) {
statement(s);
}
There are three parts in the for
loop syntax: initializer
, condition
, and incrementer
. Semicolons separate all three parts.
The initializer
is executed before the loop starts, and it usually sets up variables that will be used later on in the body of the loop. The condition
is evaluated before each iteration and decides whether to continue or break out of the loop.
The incrementer
can update a variable after each iteration.
Steps to Calculate Series Summation Using the for
Loop in C++
The following steps are needed to calculate the sum of a series using a for
loop in C++:
-
Declare an integer variable called sum and initialize it as 0.
-
Initialize the variable
i
to zero. -
Set the condition for the loop to be
i<n
, wheren
is the number of values you want to iterate. -
Every time through the loop, add 1 to
i
and then use it in your calculation. -
After every iteration, check if your condition (in this case,
i<n
) is still true, and if so, continue with another iteration. -
Lastly, print out the final sum.
Let’s discuss an example of calculating the sum of the series using a for
loop by applying the abovementioned steps.
#include <iostream>
using namespace std;
int main() {
int sum = 0;
for (int i = 1; i < 10; i += 2) {
cout << i << '+';
sum += i;
}
cout << "\n sum of series using for loop: " << sum << endl;
return 0;
}
Click here to check the working of the code as mentioned above.
Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.
Facebook