Loop in C++ with example and Theory

Posted on

 

In any programming language, loops are used to execute a set of statements repeatedly till a selected situation is glad.


The way it works

loop control - Loop in C++ with example and Theory

A sequence of assertion is executed till a specified situation is true. This sequence of assertion to be executed is saved contained in the curly braces { } generally known as loop physique. After each execution of loop physique, situation is checked, and whether it is discovered to be true the loop physique is executed once more. When situation test comes out to be false, the loop physique won’t be executed.


There are 3 kind of loops in C++ language

  1. whereas loop
  2. for loop
  3. do-while loop

whereas loop

whereas loop may be deal with as an entry management loop. It’s accomplished in 3 steps.

  • Variable initialization.( e.g int x=0; )
  • situation( e.g whereas( x<=10) )
  • Variable increment or decrement ( x++ or x– or x=x+2 )

Syntax :


for loop

for loop is used to execute a set of assertion repeatedly till a selected situation is glad. we are able to say it an open ended loop. Basic format is,

In for loop we have now precisely two semicolons, one after initialization and second after situation. On this loop we are able to have multiple initialization or increment/decrement, separated utilizing comma operator. for loop can have just one situation.


Nested for loop

We are able to even have nested for loop, i.e one for loop inside one other for loop. Fundamental syntax is,


do whereas loop

In some conditions it’s essential to execute physique of the loop earlier than testing the situation. Such conditions may be dealt with with the assistance of do-while loop. do assertion evaluates the physique of the loop first and on the finish, the situation is checked utilizing whereas assertion. Basic format of do-while loop is,


Leaping out of loop

Generally, whereas executing a loop, it turns into essential to skip part of the loop or to depart the loop as quickly as sure situation becocmes true, that’s bounce out of loop. C language permits leaping from one assertion to a different inside a loop in addition to leaping out of the loop.

1) break assertion

When break assertion is encountered inside a loop, the loop is straight away exited and this system continues with the assertion instantly following the loop.

2) proceed assertion

It causes the management to go on to the test-condition after which proceed the loop course of. On encountering proceed, cursor go away the present cycle of loop, and begins with the subsequent cycle.