4

Loops | Programming - GeeksforGeeks

 1 year ago
source link: https://www.geeksforgeeks.org/loops-programming/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

In the field of programming, Iteration Statements are really 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.

What are Loops?

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, 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:

  • Python3
#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;
}
Output
0 1 2 3 4 
0 1 2 3 4 

2. Exit-controlled loops:

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 Exit Controlled loop. Below are the examples of Exit-controlled loops:

#include <iostream>
using namespace std;
int main()
{
// Exit controlled do-while loop
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
return 0;
}
Output
0 1 2 3 4 

For loop:

A 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.

The 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.

  • Python3
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
cout << endl;
return 0;
}
Output
0 1 2 3 4 

While Loop:

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.

The 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.

  • Python3
#include <iostream>
using namespace std;
int main() {
int i = 0;
while(i < 5) {
cout << i << " ";
i++;
}
return 0;
}
Output
0 1 2 3 4 

Do-While Loop:

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.

The 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.

#include <iostream>
using namespace std;
int main()
{
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
return 0;
}
Output
0 1 2 3 4 

Nested Loops:

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.

  • Python3
#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;
}
Output
i = 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  

Common mistakes to avoid:

  1. Infinite Loops: Not ensuring that the loop condition will eventually become false can lead to infinite loops, causing the program to hang.
  2. 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.
  3. Uninitialized Variables: Forgetting to initialize loop control variables properly can result in unpredictable behavior.
  4. Inefficient Nesting: Excessive or inefficient use of nested loops can lead to performance issues, especially with large datasets.
  5. 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 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.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.

Last Updated : 05 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK