For loop in C++

For loop

 

Here, in this section we will discuss about for loop in C++.The syntactical structure is convenient in the for loop compared to other loop types where you can accommodate a number of statements and conditions within a single line

In computer science, a for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly as long as it satisfies the given condition

For-loops are typically used when the number of iterations is known before entering the loop.

for loop in C++

Program to print alphabets from A-Z using a for loop

for(char ch='A';ch<='Z';ch++)
{
cout<<ch"\t";
}

O/P:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Competitive Coding Techniques

Flow of Execution of for loop in C++:

  1. firstly the control goes to the initialization section and is executed one time
  2. Then the condition is checked for true/false?
  3. If it is true loop body gets executed else come out of the loop
  4. After execution of loop, body control goes to inc/dec sec
    again the condition is checked
  5. If true, repeat 3,4
  6. If false, come out of the loop

Example: Printing multiplication table of 4

for(int i=0;i<=10;i++)
{
cout<<4*i"\t";//body
}

O/P

0 4 8 12 16 24 28 32 36 40

                                              Designing an infinite loop in for

//ex1:
  for(;;)//all the three parts are optinal

//ex2:
for(int i=0;i<10;) //missing inc/dec part

//ex3:
for(int i=0;1;i++)//always true

//ex4:
for(int i=10;i>0;i++)//alwasys true ,because 0 is less than any number

Inappropriate use of the semicolon(;)

for(i=0;i<6;i++);//valid but wrong OP
cout<<i;//only 6 prints 1 time

O/P

6

It makes the loop not to enter down after the semicolon but rotates within the loop and goes down after its failure only