Loops or Iteration Statements in Programming are helpful when we need a specific task in repetition. They're essential as they reduce hours of work to seconds. In this article, we will explore the basics of loops, with the different types and best practices.
Loops in ProgrammingWhat are Loops in Programming?
Loops, also known as iterative statements, are used when we need to execute a block of code repetitively. Loops in programming are control flow structures that enable the repeated execution of a set of instructions or code block as long as a specified condition is met. Loops are fundamental to the concept of iteration in programming, enhancing code efficiency, readability and promoting the reuse of code logic.
Types of Loops in Programming:
In programming, loops are categorized into two main types based on the control mechanism: entry-controlled loops and exit-controlled loops.
1. Entry-Controlled loops:
In Entry controlled loops the test condition is checked before entering the main body of the loop. For Loop and While Loop is Entry-controlled loops.
Below are the examples of Entry-controlled loops:
C++
#include <iostream>
using namespace std;
int main()
{
// Entry-controlled for loop
int i;
for (i = 0; i < 5; i++) {
cout << i << " ";
}
cout << endl;
// Entry-controlled while loop
i = 0;
while (i < 5) {
cout << i << " ";
i++;
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Entry-controlled for loop
int i;
for (i = 0; i < 5; i++) {
System.out.print(i + " ");
}
System.out.println();
// Entry-controlled while loop
i = 0;
while (i < 5) {
System.out.print(i + " ");
i++;
}
}
}
Python
# Entry-controlled for loop
for i in range(5):
print(i, end=" ")
print()
# Entry-controlled while loop
i = 0
while(i < 5):
print(i, end=" ")
i += 1
C#
// c# code for the above approach
using System;
class Program {
static void Main()
{
// Entry-controlled for loop
for (int i = 0; i < 5; i++) {
Console.Write(i + " ");
}
Console.WriteLine();
// Entry-controlled while loop
int j = 0;
while (j < 5) {
Console.Write(j + " ");
j++;
}
}
}
JavaScript
let outputFor = '';
let outputWhile = '';
// Entry-controlled for loop
for (let i = 0; i < 5; i++) {
outputFor += i + ' ';
}
// Entry-controlled while loop
let j = 0;
while (j < 5) {
outputWhile += j + ' ';
j++;
}
console.log(outputFor);
console.log(outputWhile);
Output0 1 2 3 4
0 1 2 3 4
2. Exit-Controlled loops:
In Exit controlled loops the test condition is evaluated at the end of the loop body. The loop body will execute at least once, irrespective of whether the condition is true or false. Do-while Loop is an example of Exit Controlled loop.
Below are the examples of Exit-controlled loops:
C++
#include <iostream>
using namespace std;
int main()
{
// Exit controlled do-while loop
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Exit controlled do-while loop
int i = 0;
do {
System.out.print(i + " ");
i++;
} while (i < 5);
}
}
Python
# Exit controlled do-while loop
i = 0
while True: # In Python, there's no direct equivalent of a do-while loop, so we use a while loop with a conditional break
print(i, end=" ") # Print the current value of i followed by a space
i += 1 # Increment i
if i >= 5: # Check if i is greater than or equal to 5
break # If so, exit the loop
C#
using System;
class Program
{
static void Main()
{
// Initialize the counter variable
int i = 0;
// Exit-controlled do-while loop
do
{
// Print the current value of i
Console.Write($"{i} ");
// Increment the counter
i++;
} while (i < 5);
// Return 0 to indicate successful completion
Environment.Exit(0);
}
}
JavaScript
let i = 0;
let output = '';
do {
output += i + ' ';
i++;
} while (i < 5);
console.log(output);
For loop in programming is a control flow structure that iterates over a sequence of elements, such as a range of numbers, items in a list, or characters in a string. The loop is entry-controlled because it determines the number of iterations before entering the loop.
Below is the implementation of For loop in Programming
for-loopThe basic syntax for a for loop often includes a variable that takes on each value in the sequence, and the loop body contains the code to be executed during each iteration.
Below is the implementation of For Loop in Programming:
C++
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
cout << endl;
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Entry-controlled for loop
for (int i = 0; i < 5; i++) {
System.out.print(i + " ");
}
System.out.println();
}
}
Python
# Entry-controlled for loop
for i in range(5):
print(i, end=" ")
print()
C#
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Console.Write(i + " ");
}
Console.WriteLine();
}
}
JavaScript
let output = '';
for (let i = 0; i < 5; i++) {
output += i + ' ';
}
console.log(output);
A while loop in programming is an entry-controlled control flow structure that repeatedly executes a block of code as long as a specified condition is true. The loop continues to iterate while the condition remains true, and it terminates once the condition evaluates to false.
while loopThe basic syntax for a for loop often includes a condition which is checked before each iteration and if the condition evaluates to true, the loop body containing the code gets executed otherwise the loop gets terminated.
Below is the implementation of While Loop in Programming:
C++
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 0;
while (i < 5) {
System.out.print(i + " ");
i++;
}
}
}
Python
# code
i = 0
while i < 5:
print(i, end=" ")
i += 1
C#
using System;
class Program
{
static void Main()
{
// Initialize the counter variable
int i = 0;
// Execute the loop while the condition is true
while (i < 5)
{
// Print the current value of i
Console.Write($"{i} ");
// Increment the counter
i++;
}
// Return 0 to indicate successful completion
Environment.Exit(0);
}
}
JavaScript
function main() {
let i = 0;
while (i < 5) {
process.stdout.write(i + " ");
i++;
}
}
// Call the main function
main();
A do-while loop in programming is an exit-controlled control flow structure that executes a block of code at least once and then repeatedly executes the block as long as a specified condition remains true. The distinctive feature of a do-while loop is that the condition is evaluated after the code block, ensuring that the block is executed at least once, even if the condition is initially false.
Do-while loopThe basic syntax for a for loop includes a block of code followed by a condition which is checked after each iteration and if the condition evaluates to true, the next iteration takes place otherwise the loop gets terminated.
Below is the implementation of Do while Loop in Programming:
C++
#include <iostream>
using namespace std;
int main()
{
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 0;
do {
System.out.print(i + " ");
i++;
} while (i < 5);
}
}
Python
# Python program to demonstrate a simple do-while loop
def main():
# Initialize the counter variable
i = 0
# Execute the loop at least once, and continue while the condition is true
while True:
# Print the current value of i
print(i, end=" ")
# Increment the counter
i += 1
# Check if the loop condition is no longer true
if i >= 5:
break
# Call the main function
main()
C#
using System;
class Program
{
static void Main()
{
// Initialize the counter variable
int i = 0;
// Execute the loop at least once
do
{
// Print the current value of i
Console.Write($"{i} ");
// Increment the counter
i++;
} while (i < 5);
// Return 0 to indicate successful completion
Environment.Exit(0);
}
}
JavaScript
// Define the main function
function main() {
// Initialize the variable i
let i = 0;
// Start a do-while loop
do {
// Print the current value of i
process.stdout.write(i + " ");
// Increment i
i++;
} while (i < 5); // Continue looping while i is less than 5
}
// Call the main function
main();
Nested loops in programming are when one loop is placed inside another. This allows for the iteration of one or more loops within the body of another loop. Each time the outer loop executes, the inner loop completes its full iteration. Nested loops are commonly employed for tasks involving multidimensional data processing, pattern printing, or handling complex data structures. Efficient use of nested loops is essential, considering potential impacts on code readability and execution time for larger datasets.
Nested Loop
Below is the implementation of Nested Loop in Programming:
C++
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 3; i++) {
int j = 0;
while (j < 5) {
cout << "i = " << i << " j = " << j << " ";
j++;
}
cout << endl;
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 3; i++) {
int j = 0;
while (j < 5) {
System.out.print("i = " + i + " j = " + j
+ " ");
j++;
}
System.out.println();
}
}
}
Python
for i in range(3):
j = 0
while j < 5:
print(f"i = {i} j = {j} ", end="")
j += 1
print()
C#
using System;
class Program
{
static void Main()
{
for (int i = 0; i < 3; i++)
{
int j = 0;
while (j < 5)
{
Console.Write($"i = {i} j = {j} ");
j++;
}
Console.WriteLine();
}
}
}
JavaScript
// Define the main function
function main() {
// Start a for loop to iterate from 0 to 2
for (let i = 0; i < 3; i++) {
// Initialize j
let j = 0;
// Start a while loop to iterate while j is less than 5
while (j < 5) {
// Print the values of i and j
console.log("i = " + i + " j = " + j + " ");
// Increment j
j++;
}
// Print a newline after each inner loop iteration
console.log();
}
}
// Call the main function
main();
Outputi = 0 j = 0 i = 0 j = 1 i = 0 j = 2 i = 0 j = 3 i = 0 j = 4
i = 1 j = 0 i = 1 j = 1 i = 1 j = 2 i = 1 j = 3 i = 1 j = 4
i = 2 j = 0 i = 2 j = 1 i = 2 j = 2 i = 2 j = 3 i = 2 j = 4
Characteristic | for Loop | while Loop | do-while Loop |
---|
Syntax | for (initialization; condition; update) | while (condition) | do { } while (condition); |
---|
Condition Check | Checked before each iteration. | Checked before entering the loop. | Checked after executing the loop body. |
---|
Update/Increment | Executed after each iteration. | Should be included within the loop body. | Executed after each iteration. |
---|
Use Cases | Suitable when the number of iterations is known. | Useful when the loop condition is based on a state that can change anywhere in the loop body. | Ensures the loop body is executed at least once before checking the condition. |
---|
Common mistakes to avoid in Programming:
- Infinite Loops: Not ensuring that the loop condition will eventually become false can lead to infinite loops, causing the program to hang.
- Off-by-One Errors: Mismanaging loop counters or conditions can lead to off-by-one errors, either skipping the first iteration or causing an extra, unintended iteration.
- Uninitialized Variables: Forgetting to initialize loop control variables properly can result in unpredictable behavior.
- Inefficient Nesting: Excessive or inefficient use of nested loops can lead to performance issues, especially with large datasets.
- Modifying Loop Variable Inside the Loop: Changing the loop variable inside the loop can lead to unexpected behavior. For example, modifying the iterator variable in a for loop.
In conclusion, loops in Programming are very useful in programming as they help to repeat and automate tasks. Whether through entry-controlled loops like for and while, or exit-controlled loops like do-while, loops form the backbone of algorithmic logic, enabling the creation of robust software that can handle repetitive operations, iterate through data structures, and execute complex tasks. Mastering loop structures is fundamental for any programmer seeking to optimize code, enhance readability, and master algorithm design.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem