For Loop(C++ For Loop Syntax and How For Loop Works? )



Loops are used in programming to repeat a specific block until some end condition is met. There are three types of loops in C++ programming:
  1. for loop

C++ for Loop Syntax

for(initializationStatement; testExpression; updateStatement) {
    // codes 
}
where, only testExpression is mandatory.

How for loop works?

  1. The initialization statement is executed only once at the beginning.
  2. Then, the test expression is evaluated.
  3. If the test expression is false, for loop is terminated. But if the test expression is true, codes inside body of for loop is executed and update expression is updated.
  4. Again, the test expression is evaluated and this process repeats until the test expression is false.

Flowchart of for Loop in C++

Flowchart of for loop in C++ Programming

Example 1: C++ for Loop

  1. // C++ Program to find factorial of a number
  2. // Factorial on n = 1*2*3*...*n
  3. #include <iostream>
  4. using namespace std;
  5. int main()
  6. {
  7. int i, n, factorial = 1;
  8. cout << "Enter a positive integer: ";
  9. cin >> n;
  10. for (i = 1; i <= n; ++i) {
  11. factorial *= i; // factorial = factorial * i;
  12. }
  13. cout<< "Factorial of "<<n<<" = "<<factorial;
  14. return 0;
  15. }
  16. Output
    Enter a positive integer: 5
    Factorial of 5 = 120

Comments

Popular posts from this blog

C++ Templates ?

C++ Program to Print Number Entered by User

Educational Website