Wednesday, April 6, 2016

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:
In other words,
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 thefor 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.

0 comments:

Post a Comment