Types of Loops in C and C++?

uriotnews

Loops in a programming language is a piece of code that get executed repeatedly until the specified condition becomes false. A loop consists of two parts, a block of statements and a condition that control the loop.

Loops mainly consisted of three statements – initialization condition, test condition, update condition.

For example, if we want to print “Hello Codies” 5 times, we can do this in two ways. Writing the statement 5 times (#1) or use loops which save time and effort (#2).

Output:

In this tutorial, you will learn-

  1. Types of Loops
  2. While Loop
  3. Do-While loop
  4. For loop
  5. Nested loop
  6. Break Statement
  7. Continue Statement

Types of Loops in C/C++

Loops are classified into two types depending upon the position control statements:

  • Entry controlled loop
  • Exit controlled loop

Entry controlled loop: A conditional statement is evaluated before executing the body of a loop. It is also called as a pre-checking or Counter controlled loops where the programmer already know how many times the loop get executed. Counter controlled loops are often called definite iteration because the number of repetitions is known before the loop begins execution.

Exit controlled loop: In this type of loops conditional statement are evaluated after executing the loop body once irrespective of whether the test condition is true or false. It is also called as a post-checking or Sentinel controlled Loop because the programmer don’t know exactly know how many times loop will be executed. Sentinel-controlled loop also known as indefinite repetition.

The control conditions must be specified properly otherwise the loop will execute infinite number of times (infinite loop). An infinite loop occurs when no termination condition is specified or specified conditions never meet.

C programming language provides us with 3 types of loop and C++ has 4th extra loop:

  • while loop
  • do-while loop
  • for loop
  • Nested Loop (only in C++)

The syntax of these loops mainly differs in the placement of these three statements initialization condition, test condition, update condition.

While Loop in C/C++

The while loop specify that a program should repeat set of instruction inside the block till the condition remains true. While loop used in place where we don’t know number of iteration before and it depends on the update inside the block. While loop is Entry Controlled loop and widely used in C/C++.

Syntax of WHILE Loop:

Flow Chart of While loop.

In While loop, condition evaluated first if condition is TRUE than block of statements get executed and update condition then control again goes back at the beginning, and the condition is checked again if it is true, the same process is executed until the given condition becomes false. Once the test condition results FALSE control goes back to main program. While Loop is Entry-Controlled Loop.

Note: If Loop contains only one statement, then the curly braces are not compulsory. Though It is a good practice to include braces.

Following program illustrates a while loop:

Output:

The above program prints series of numbers from 1 to 5 using a while loop.

Let’s see what happening in above program step by step.

Step 1: We have initialized variable ‘num = 1’.

Step 2: In while condition we are evaluating is ‘num’ value is less than or equal to 5, if ‘num’ becomes greater than 5 than this condition become False.

Step 3: For now ‘num = 1’, we enter the loop comparing 1 <= 5 which result true so the body of loop i.e. ‘num’ value 1 got printed.

Step 4: In this step ‘num’ value increased by 1 i.e now ‘num = 2’.

Now step 3 get repeated again with ‘num = 2’ and print the ‘num’ value 2, similarly 3,4,5. When ‘num’ got increase to 6 (num =6) while condition become FALSE & loop terminated than control goes back to main() function as there is nothing after loop do program exits with returning 0 indicating that everything went well.

Do-While Loop in C/C++

Do-while loop is almost similar to the while loop except that the body of a loop executed once before test condition is evaluated. It is an Exit-controlled loop.

The basic syntax of do-while loop is as follows:

Flow Chart of Do – While loop.

Do–while loop used in cases where we have to execute a body of the loop at least once irrespective of the condition. Unlike while loop, In do-while loop the body of a loop is always executed at least once then checks the condition. If the condition is true, then it will again execute the body of a loop else if condition becomes FALSE control goes out of the loop to main program.

Following program illustrates the do-while loop:

Output:

In the above program, we have initialized ‘num = 6’ and printed the ‘num =6’ without involving while condition which will result in FALSE as 6 > 5. After printing 6 we compared which turned out to be FALSE thus terminating the loop.

Important NOTE about while and Do-while loop:

We can use multiple test condition in both While and Do-while loop using binary operators, follow below program.

Multiple test conditions using binary operators in while loop.

Output:

Here the while loop body executed only if number is less than equal to 5 and less than 3. To manually compile you need to know Truth table.

Truth Table

Manually compiling above program.

Multiple test conditions in Do-While loop.

Output:

Here the loop body executed once irrespective of condition than ‘num’ value decreased & compared with while condition. Loop gets terminated only if either one or both the conditions become. To manually compile you need to know Truth table.

For Loop in C/C++

A for loop is a more efficient loop structure in C/C++ programming. A for loop is a repetition control structure which allows us to execute piece of code a specific number of times. The general syntax of for loop is as follows:

Flow Chart of FOR loop.

  • The variable assigned initial value only once in for loop.
  • The condition is a Boolean expression that tests and compares the counter (initialized value) for a fixed iteration and stops the for loop when the condition is false.
  • The increment/decrement increases (or decreases) the counter by a set value.

Following program illustrates the use of FOR loop:

Output:

The above program prints the number series from 0-10 using FOR loop.

Step 1. Declared a variable i of int data type to store values.

Step 2. In loop, we have initialized variable i = 1, than the condition part and the increment part.

Step 3. In loop body, we have a print function to print the value of variable i on a new line in the console. After printing i = 1, the value of i will be incremented, and it will become 2. Now the variable has the value 2. The condition will be evaluated again and since the condition is true loop will be executed, and it will print two on the screen. This loop will keep on executing until the value of the variable becomes 10. After that, the loop will be terminated, and a series of 0-10 will be printed on the screen.

In C/C++, the for loop can have multiple condition separated by commas in each part.

For example:

Output:

Above loop compile without any error, but the twist is the output will be 0-10 because 2nd condition is considered 1st condition is just evaluated and kept aside, whole loop executed on the basis of 2nd condition.

Now, if we you want to test both conditions, use the && operator.

Output:

And in FOR loop, we can skip the initial value assignment, condition and/or increment by adding a semicolon.

For example:

Nested Loops

Nested loops mean loop inside other loop for each iteration of the outer loop, the inner loop repeats its entire cycle.

Consider the following example printing a multiplication table:

Output:

Break Statement

The break in C/C++ is a loop control statement mainly in the switch statement to jump out of switch block after the desired case is met. BREAK also used to terminate the loop when encountered from within a loop, the loop iterations stops and control returns from the loop immediately to the first statement after the loop.

Syntax:

Basically break statements are used in the situations where the actual number of iterations not known or we want to terminate the loop based on some condition.

Output:

Continue Statement

Continue statement is similar to BREAK statement in opposite way, whenever continue statement encountered instead of terminating the loop, it forces loop to execute the next iteration and skips the current iteration in loop.

For example:

Output:

So, the value 5 is skipped.

Explanation

Consider the above situation where you need to write a program which prints number from 10 to 0 and but not 5. What we did here is we run a loop from 10 to 0 and every time we have to compare the value of iterator ‘n’ with 5. If n equal to 5 than the continue statement executed to force loop continue to next iteration without printing 5.

Please comment if you find anything incorrect or any error.

This UrIoTNews article is syndicated fromDzone