Types of Loops in C and C++?
Types of Loops in C and C++?
In this in-depth article, learn about the types of loops in C and C++.
Join the DZone community and get the full member experience.Join For Free
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).
In this tutorial, you will learn-
- Types of Loops
- While Loop
- Do-While loop
- For loop
- Nested loop
- Break Statement
- 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:
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:
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:
Multiple test conditions using binary operators in while loop.
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.
Manually compiling above program.
Multiple test conditions in Do-While loop.
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:
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.
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.
And in FOR loop, we can skip the initial value assignment, condition and/or increment by adding a semicolon.
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:
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.
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.
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.
So, the value 5 is skipped.
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.
Published at DZone with permission of Chand Pasha . See the original article here.
Opinions expressed by DZone contributors are their own.