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
isfinite() function in C++ The isfinite() function is a builtin function in C++ and is used to determine whether a given value if finite or not. A finite value is a value that is neither infinite nor NAN. If the number is finite then the function returns 1 else returns zero.Syntax: bool isfinite(float x); or, bool isfinite(do
2 min read
Infinity in Maths The infinity symbol (â) is a powerful representation of something limitless and unbounded. First introduced in mathematics by John Wallis in 1655, the symbol has evolved to hold significance in various fields, including mathematics, spirituality, and pop culture.This article will explore the infinit
14 min read
Infinite Product Infinite product is a mathematical expression that represents the product of an infinite sequence of terms. Infinite series is a mathematical expression of an infinite number of terms which are arranged in a specific relation like sum or products. This number of terms are mainly in the form of numbe
8 min read
log() Function in C++ The std::log() in C++ is a built-in function that is used to calculate the natural logarithm (base e) of a given number. The number can be of any data type i.e. int, double, float, long long. It is defined inside the <cmath> header file.In this article we will learn about how to use std::log()
1 min read
log1p() in C++ The log1p() function takes an argument x and returns the natural logarithm of the base-e logarithm of x+1. Here e is a mathematical constant with value equal to 2.71828. Syntax: double log1p (double x); float log1p (float x); long double log1p (long double x); Parameter: The log1p() function takes a
2 min read
log10() Function in C++ The std::log10() in C++ is a built-in function that is used to calculate the base-10 logarithm of a given number. It is defined inside <cmath> header file. In this article, we will learn about log10() in C++ and its behavior for different values.Example:C++// C++ Program to illustrate the use
2 min read
strol() function in C++ The strtol() function in C++ interprets the contents of a string as an integral number of the specified base and return its value as a long int.This function also sets an end pointer that points to the first character after the last valid numeric character of the string, if there is no such characte
3 min read
(limits.h) in C/C++ The maximum and minimum size of integral values are quite useful or in simple terms, limits of any integral type plays quite a role in programming. Instead of remembering these values, different macros can be used. <climits>(limits.h) defines sizes of integral types. This header defines consta
4 min read
Facts about Infinity Infinity is an idea that has amazed and puzzled thinkers for a very long time. It means something that has no end, something that goes on forever. Unlike regular numbers, which have a set value, infinity is not an actual number but a concept that describes things bigger than any number we can think
7 min read
Stack Unwinding in C++ Stack Unwinding is the process of removing function call frames from function call stack at run time. The local objects are destroyed in reverse order in which they were constructed.Stack unwinding is a normal process that occurs when a function returns a value. But it can also occur due to exceptio
4 min read