C++ Loop Control Statements

PREV     NEXT

What are Loops?

The loops are needed to execute a block of code many of the times. In this, basically the statements are executed sequentially which means the first statement in a function is executed first than the second statement and so on. The loops are used to execute a single statement or the group of statements multiple times.

Some of the loops in C++ are

  • For loop
  • While loop
  • Do-while loop

Let us understand these loops in briefly

 For loop

The for loop is used as a repetition control statement that allows you to write a loop that will execute a specific number of times. The for loop is used to execute the block of statements again and again till the condition returns false. In for loop, the statement is executed till the Boolean condition is not true, as the condition is true it will terminate the loop. The for loop consists of three parts first is the initialization, second is the condition and third is increment or decrement statement.

The for loop syntax is like this:

COMPILE & RUN

Let us have a look on the example:

COMPILE & RUN

While loop

The while loop is basically most basic loop statement, it repeats the statement till the condition is true. In this, there can be a single statement or block of statements and the condition can be any expression and any non zero value is true. It basically targets the statement as long as the given condition is true.

Let us have a look at the syntax:

COMPILE & RUN

Let us have a look on the example:

COMPILE & RUN

Do-while loop

As you have study about the for loop and while loop in which they test the loop condition at the top of the loop whereas do-while loop check the condition at the bottom of the loop. In do-while loop, the program will execute the body of the loop first and at the end of the loop, the test condition in the while statement is executed; if condition is true then program continues to execute loop body otherwise it will come out of the loop.

Let us have a look at the syntax:

COMPILE & RUN

Let us have a look on the example:

COMPILE & RUN

PREV     NEXT


Share this website !!!
Facebook Twitter Linkedin