Enrich your knowledge with our informative blogs
Loops: Loops are elements that help in executing repeated code in minimum lines of code. The loop is run till a specified condition and the control exits from the loop when the condition becomes false.
Parts of a Loop
There are two parts of a loop:
1). Block of statements or body
2). Conditions that control the loop
There are three essential statements that need to be taken care of, else the loop will either won’t work or enter into an infinite loop.
Before moving on to types of loops, understand
Why do we need Loops?
If you want to print 1 to 5, there are two ways to do that.
Method 1 Iterative Method
Here you need to give the print statement 5 times, one each for every number.
Why to avoid this approach?
All these problems are solved by using loops.
Method 2 Loops
Loops are used when you need to repeatedly execute the block of statements. They use minimum lines and deliver maximum efficiency.
Loops make the code look simple, easy and well optimized.
Loops fall under two types of categories:
1). Entry controlled Loops:
Here the test condition is tested before sending the control of the program inside the loop.
The body of the loop is executed only if the condition turns out to be true. For example: while loop, for loop
2). Exit Controlled Loops
Here, the body of the loop is executed atleast once and the test condition is checked after the end of the loop. So, irrespective that the condition is true or false, the loop gets executed. For example: do-while loop
Now, Let’s discuss how to print 1 to 5 or even beyond that by using different types of loops.
Types of Loops
1. While Loop
Generally ‘while’ loop is used when we don’t know about the number of iterations. The condition is tested before entering the loop and the body of the loop gets executed only when the condition turns out to be true.
Working of while Loop:
Here’s how while loop will be used to print 1 to 5.
When you know the number of iterations, it always better to use ‘for’ loop. It not only helps to execute the statements multiple times in one go but also reduces LOC (Lines of code) significantly.
It allows performing initialization, testing condition and updating expression in just one line.
How for loop works?
Let’s how to print 1 to 5 using a for loop:
3. Do-while loop
This loop is just like while loop with just a change that the testing condition is checked at the end of the loop.
How does a do-while loop works?
Example: Let’s learn how to write 1 to 5 using the do-while loop.