×

C++ Infinite loop

The term "infinite loop" refers to a loop that does not terminate the loop according to the condition. In some cases, an infinite loop may be required in programming, or a loop may become infinite when the exit condition becomes false again and again.

Applications

An infinite loop is useful for programs that receive user input and continuously generate output until the user exits the program manually.

The infinite loop can be utilized in the following scenarios:

1) If you're developing an application that allows the user to submit the long data having the loop 30,000 or 300,000,000 times. The code run infinitely and receiving the user input until the user presses Ctrl-C to terminate the application.

2) If you have a constant monitoring operation running on your servers.

3) As the server answers all client requests, it runs in an eternal loop. It breaks the endless cycle when the administrator manually shuts down the server.

4) When your server script listens for connections on a socket, this could be a useful feature.

5) Infinite loops are frequently used in video game programming.

There are various loop structures in C that can be used to produce an infinite loop. Following are the looping structures that define the endless loop:

  • For loop
  • While loop
  • Do-While loop

Infinite For Loop

A condition in for loop terminates the loop. The condition can be left blank if we wanted. We may also remove the initialization and repeat statements from the for loop. These fields are optional and can be left empty. Because the condition will never be false, the control will never exit the loop, which produce an infinite loop.

For loop syntax

for (
  <initial statement(s)>;
  <Condition expression>;
  <Repeat step(s)>
      )
{
  <Loop statement(s)>;
}

Infinite For loop:

for(;;);
     for(;;)
         {
            }

Infinite For Loop with True for Condition

For loop uses a boolean expression that evaluates the condition to be true or false. Instead of giving an expression, we can substitute the boolean value “true” for the condition which results an infinite loop.

Program:

#include <iostream>
using namespace std;
 int main()
 {
   for (; true; ) 
     {
      cout << "javaTpoint" << endl;
   }
}

Output:

javaTpoint
javaTpoint
javaTpoint
javaTpoint
javaTpoint
..
..
..

The string ‘’javaTpoint” will print at a time on the console infinitely. To terminate the execution of the program press CTRL and C together on the keyboard.

Infinite while loop in C

There is a condition statement in the while loop. This is a required expression that cannot be omitted. As a result, we must provide a true condition here. "TRUE", "1", "1==1", and so on are the TRUE statements.

While loop syntax

while (<Condition expression>)
{
  <Loop statement(s)>;
}

Infinite While loop

while (1);


while (1)
     {
       }

Infinite While Loop with TRUE condition

You can use a condition that always evaluates to true. But, you cannot use a TRUE boolean value in the condition of the while loop for infinite loop. The criterion 1 == 1 or 0 == 0 is always true.
The condition is always true and the loop will While loop run infinitely.

Program:

#include <iostream>
using namespace std;
 int main()
 {
While(1==1)
{
      cout << "javaTpoint" << endl;
   }
}

Output:

javaTpoint
javaTpoint
javaTpoint
javaTpoint
javaTpoint
..
..

The string “javaTpoint” prints one by one infinitely as the given condition is always true. To terminate the execution of the program press CTRL+C on the keyboard.


Infinite Do-While loop:

There is a condition statement in the while loop. This is a required expression that cannot be omitted. As a result, we must provide a true condition here. "TRUE", "1", "1==1", and so on are the TRUE statements.

Do-While loop syntax

do
{
  <Loop statement(s)>;
} while (<Condition expression>);

Infinite Do-While loop:

do {
      } while(1);

Infinite do-while Loop with No Update to Control Variables

When you forget to update the variables involved in the condition, you can end up with infinite loops.   

We have set variable “i” to 0 in the below example and want to print a string to the console until the value of i becomes 10.

In the example below, we would not use the update statement to increment ”i” for printing javaTpoint 10 times. So, the value of i would never change and the code will run infinitely with value of i. This result in an infinite do-while loop.

Program:

#include <iostream>
using namespace std;
 int main()
 {
i=0;
do
{
      cout << "javaTpoint" << endl;
   }while(i<10)
}

Output:

javaTpoint
javaTpoint
javaTpoint
javaTpoint
javaTpoint
..
..

Long Running Loops

It's recommended to add some delay to each loop. Otherwise, the process may consume all CPU cycles and cause the system to freeze. This may be required when the programmer is waiting for a condition to occur. A sleep statement releases the task to the scheduler and allowing other tasks to continue normally. This statement causes the current thread to suspend execution for a specified period.

For Loop;

for(;;)
{
Sleep(1);
}

While Loop:

while(1)
{
  Sleep(1);
}

Do-While Loop:

do
{
  Sleep(1);
}
while(1);

Debug infinite loops

A program enters an infinite loop and continue to execute the body of the loop. This type of problem may not occur very often and may occur due to a rare instance. On the other hand, these problems are simple to troubleshoot or debug.

We should write the break statement for checking the condition from where the loop become infinite. To get to the root of the problem, we need to figure out why the condition isn't becoming false.


Related Topics

C++ Iterators

What are iterators ? Iterators are among the four foundations of the C++ Standard Template Library, also known as the STL. The memory address of the STL container classes is pointed...

15 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

Two dimension array

C++ Two dimension (2D) Array Two dimension (2D) array is an array of arrays. It is represented in the form of row and column. The elements of 2D array are accessed through the...

2 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.

C++ | C Plus Plus While loop

In this article, we will discuss the C++ while loop with its syntax, use, key features, key points, pseudo code, and examples. What is the While Loop? The “while loop” is a...

4 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

Difference between "int main( ) and int main(void)" in C/C++

int main( ) function In the C/C++ programming language, int main() indicates a function that returns an integer at the end of the program execution. In general, a value of '0' indicates...

3 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

Top 5 IDEs for C++ That You Should Try Once

In the past decades, creating an application or interface from the very basic idea, the developer has to struggle a lot for it. Because an application is a combination of...

3 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

System() function in C++

As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We...

2 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.