C++ Loops

Share:

Looping is executing same code many times it will execute forever if we don’t control it with conditions.



We have three kind of loops in C++:

§  While:
Structure for while loop in C++:

                while ( condition ) { codes; ConditionChanger; }

while:
if we want to use while loop we need to use while key word before we start.

Condition:
A condition is made of operators will be used in here inside prentices ( ( ) ) their result may be one of these two values true or false. Conditions are two type simple conditions ( conditions that don’t have any logical operator in them ) and compound conditions ( conditions that  have logical operator in them , these logical operators connect two simple conditions ) which both can be used in if condition. We can use true or false directly like a condition.

ConditionChanger:
We need to change condition in loop body otherwise the loop condition will always remain true and it will be executed until condition is true so we need to make the condition false in order to stop the loop.
We can change it by operators:

                int num = 1;       
    while ( num == 1 ) { codes; num++; }

§  do while:
syntax for the do while loop in C++:

                do{ codes; ConditionChanger; } while ( condition );

do while key word:
the main deference between while and do while loops is this which in while loop we always check condition before executing codes but in do while loop the condition will always be checked after code execution.

ConditionChanger:
Again, if the condition is true we need to make it false to stop the loop we can use increment and decrement operators to do that.

§  for:
for loop is the third form of the loop which is used commonly among programmers and the reason is this which all counter declaration and initialization, condition and condition changer are all in the same place and make them more readable.
structure of for loop in C++:

for ( DataType CounterName=Value ; condition ; ConditionChanger ) { codes; }
                  
                        for:
                        we have to use this key word before using for loop.
                         
                        Counter:
The first part in prentices is counter declaration and initialization we make a variable just to use it in condition and it is a local variable in for loop.

Condition:
Condition in for loop is the same condition which is needed in conditional statements, while and do while loops.

Condition Changer:
Condition changer in for loop is the same which we use for while and do while loops

No comments