Cpp - Statement for Loops

Introduction

A for loop combines the following three steps together into a single statement.

  • initialization of the counter
  • conditional test
  • change to the counter

The following code rewrites the preceding while loop to produce the same output:

for (int x = 0; x < 13; x++) 
{ 
    std::cout << "X"; 
} 
std::cout << "\n"; 

The first section of a for loop is the initialization.

Any C++ statement can be put here, but typically it is used to create and initialize a counter variable.

The second section is the test, which can be any legal C++ expression.

The third section changes the counter.

This typically is a statement that increments or decrements the counter's value, but any legal C++ statement can be used here.

Demo

#include <iostream> 

int main() //from  w  w  w  .  ja va  2  s  .  co m
{ 
    int number; 
    std::cout << "Enter a number: "; 
    std::cin >> number; 
     
    std::cout << "\nFirst 10 Multiples of " << number << "\n"; 
     
    for (int counter = 1; counter < 11; counter++) 
    { 
           std::cout << number * counter << " "; 
    } 
    std::cout << "\n"; 

    return 0; 
}

Result

Related Topics

Exercise