In C++, a loop is a part of code that is executed repetitively till the given condition is satisfied. An infinite loop is a loop that runs indefinitely, without any condition to exit the loop. In this article, we will learn about infinite loops in C++, its types and causes and what are its applications.
Infinite Loop in C++
An infinity loop is any loop in which the loop condition is always true leading to the given block of code being executed repeatedly infinite number of times. They can also be called the endless or non-terminating loop which will run till the programs life.
Infinite loops are generally accidental that occurs due to some mistake by the programmer. But they are pretty useful too in different kind of applications such as creating a program that does not terminate till the command is given.
Types of Infinite Loops in C++
There are several ways to create an infinite loop in C++, using different loop constructs such as while, for, and do-while loops. Here, we will explore each method and provide examples.
1. Infinite Loop using While Loop
It is the most popular type of while loop due to its simplicity. We just pass the value that will result in true as the condition of the while loop.
Syntax
while(1)
or
while(true)
Example
C++
// Infinite loop in C++ using for loop
#include <iostream>
using namespace std;
int main() {
for (;;) {
cout << "This is an infinite loop." << endl;
}
return 0;
}
Output
This is an infinite loop.
This is an infinite loop.
This is an infinite loop.
This is an infinite loop.
...........
2. Infinite Loop using For Loop
In for loop, if we remove the initialization, comparison and updation condition, then it will result in infinite loop.
Syntax
for(;;)
Example
C++
// Infinite loop in C++ using for loop
#include <iostream>
using namespace std;
int main() {
for (;;) {
cout << "This is an infinite loop." << endl;
}
return 0;
}
Output
This is an infinite loop.
This is an infinite loop.
This is an infinite loop.
This is an infinite loop.
.......
3. Infinite Loop using do-while Loop
Just like other two loops, we can also create an infinite loop using do while loop. Although, this loop is not preferred much due to longer syntax.
Syntax
do{
}while(1)
Example
C++
// Infinite loop in C++ using do-while loop
#include <iostream>
using namespace std;
int main() {
do {
cout << "This is an infinite loop." << endl;
} while (true);
return 0;
}
Output
This is an infinite loop.
This is an infinite loop.
This is an infinite loop.
This is an infinite loop.
........
Common Causes of Accidental Infinite Loops in C++
Infinite loops can be both intentional and accidental. Accidental loops are those which was not intended by the programmer but are caused due to some error in the program. Following are some of the causes due to which users may face infinite loops in their programs unintentionally:
1. Missing Update Statements
Infinite loops are caused when a user forgets to add an update condition inside the loop which will terminate the loop in the future. The following program illustrates such a scenario:
C++
// Infinite loop caused due to missing update statement
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i < 5) {
cout << i <<endl;
// Missing update: i++;
}
return 0;
}
Output
1
1
1
1
.......
2. Incorrect Loop Conditions
The conditions mentioned inside the loop body is very crucial to terminate a loop. Incorrect loop condition can result into an infinite loop. The following program illustrates such a scenario:
C++
// Infinite loop caused due to incorrect loop conditions
#include <iostream>
using namespace std;
int main() {
int i = 2;
while (i >= 0) { // Should likely be i < some_value
cout << "Hello Geeks " << endl;
}
return 0;
}
Output
Hello Geeks
Hello Geeks
Hello Geeks
Hello Geeks
Hello Geeks
........
3. Logical Erros in the Loop
In many scenarios infinite loops are caused due to small logical errors in the code. The following program illustrates such a scenario:
C++
#include <iostream>
using namespace std;
int main() {
for (int i = 3; i >2; i += 2) { // i is always > 2
cout <<"This is an infinite loop" << endl;
}
return 0;
}
Output
This is an infinite loop
This is an infinite loop
This is an infinite loop
This is an infinite loop
........
Applications of Infinite Loops in C++
Infinite loops does not only occur by accident, they are also created by the programmer for different purposes. Following are some of the common applications where the infinite loops are used intentionally:
- Event Loops: Many Graphical User Interfaces(GUI) uses infinite loops to keep the program running and responsive to user actions.
- Server Applications: Web servers use infinite loops to continuously listen to client connections or requests.
- Embedded Systems: Embedded systems such as microcontrollers frequently uses infinite loops as their main program loops to continuously respond to external events.
- User Inputs: Infinite loops are also used to wait for valid user inputs. The loop keeps running until a valid input if provided by the user.
Using Infinite Loops to Take User Input in C++
Infinite loops are commonly used in scenarios where a program need to continuously take user input until a specific condition is met, such as exiting the program or getting a valid user input. The following program demonstrates how we can take user input from the user until a specific condition is met:
C++
// C++ Program to take user input from users using infinite loops
#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
while (true) {
cout << "Enter a command (type 'exit' to quit): ";
getline(cin, input);
if (input == "exit") {
break; // Exit the loop if the user types 'exit'
}
cout << "You entered: " << input << endl;
// Process the input
}
cout << "Program exited." << endl;
return 0;
}
Output
Enter a command (type 'exit' to quit): Hello
You entered: Hello
Enter a command (type 'exit' to quit): Geeks
You entered: Geeks
Enter a command (type 'exit' to quit): exit
Program exited.
Time Complexity: O(1)
Auxiliary Space: O(1)
Related Articles
You can read the following articles if you want to improve your understanding about the loops in C++:
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read