C++ for Loop

A C++ for loop allows for a block of code to be executed until a conditional becomes false. For loops are usually used when a block of code needs to executed a fixed number of times. 


Flow of for Loop in C++ by Flow Diagram
C++ for Loop Flowchart diagram
C++ for Loop Flowchart Diagram

Syntax:

    for( initialization ; conditional ; iteration ) {
        // loop body
    }

Each loop consists of 3 parts, an initialization step, the conditional, and an iteration step. The initialization is run before entering the loop, the condition is checked at the beginning of each run through the loop, and the iteration step executes at the end of each pass through the loop. The Step of Iteration do increment or decrements the count of value like ++ for increment and -- for decrements.

Example:


#include <iostream>
using namespace std;
int main () {
   // for loop example
for( int i = 0; i < 5; i++ ) // with initialization, condition, and increment
{
  cout << "Apple: " << i << endl; 
 }
   return 0;

}

Output:



<< C++ Switch          --         C++ while Loop>> 

No comments:

Post a Comment