for statement in C++
The for
statement or for
loop is useful while executing a statement multiple number of times.
The for
loop is the most commonly used statement in C++. This loop consists of three expression:
- The first expression is used to initialize the index value
- The second expression is used to check whether or not the loop is to be continued again
- The third expression is used to change the index value for further iteration
The general form of for
statement is:
for(expression 1; expression 2; expression 3) statement;
In other words,
for(initial condition; test condition; incrementer or decrementer) { statement1; statement2; ..... ..... }
Where,
- expression 1 is the initialization of the expression or the condition called an index
- expression 2 is the condition checked. As long as the given expression is true the loop statement will be repeated
- expression 3 is the incrementer or decrementer to change the index value of the
for
loop variable
Typically, expression 1 is an assignment expression, expression 2 is a logical expression and expression 3 is a unary expression or an assignment expression.
When the for
statement is executed, expression 2 is evaluated and tested at the begening of each pass through the loop and expression 3 is evaluated at the end of each pass.
Program to compute a sum of consecutive integers, i.e., the program to compute the sum 1 + 2 + 3 + .. + n, for an integer input n.
#include { int n; cout << "Enter a positive integer: "; cin >> n; long sum = 0; for(int i=1; i<=n; i++) { sum = sum + i; } cout << "Sum of first " << n << " integers is " << sum; }
What will be the output of that above program?
Output:
Enter a positive integer: 3
Sum of first 3 integers is 6