C++ for Statement

Introduction

The for-statement executes code in a loop.

The execution depends on the condition.

General syntax of the for-statement is:

for (init_statement; condition; iteration_ expression) { 
     // execute some code 
}.

A simple example:

#include <iostream> 

int main() /*from   ww  w .j a  v  a2s  . c o  m*/
{ 
    for (int i = 0; i < 10; i++) 
    { 
        std::cout << "The counter is: " << i << '\n'; 
    } 
} 

This example executes the code inside the for loop ten times.

The init_statement is int i = 0; We initialize the counter to 0.

The condition is: i < 10; and the iteration_expression is i++;.

If we wanted something to execute 20 times, we would set a different condition:

#include <iostream> 

int main() //from  ww  w. j  av a2s .  c om
{ 
    for (int i = 0; i < 20; i++) 
    { 
        std::cout << "The counter is: " << i << '\n'; 
    } 
} 



PreviousNext

Related