An infinite loop is a looping construct that does not terminate and executes the loop forever. It is also called an indefinite loop or an endless loop. It either produces a continuous output or no output.
An infinite loop is useful for those applications that accept the user input and generate the output continuously until the user exits from the application manually.
In the following situations, this type of loop can be used:
- All the operating systems run in an infinite loop as it does not exist after performing some task. It comes out of an infinite loop only when the user manually shuts down the system.
- All the servers run in an infinite loop as the server responds to all the client requests. It comes out of an indefinite loop only when the administrator shuts down the server manually.
- All the games also run in an infinite loop. The game will accept the user requests until the user exits from the game.
We can create an infinite loop through various loop structures. The following are the loop structures through which we will define the infinite loop:
- for loop
- while loop
- do-while loop
- go to statement
- C macros
Let's see the infinite 'for' loop. The following is the definition for the infinite for loop:
for(; ;)
{ // body of the for loop.
} As we know that all the parts of the 'for' loop are optional, and in the above for loop, we have not mentioned any condition; so, this loop will execute infinite times.
Example:#include <stdio.h>
int main()
{
for(;;)
{
printf("Infinite Loop");
}
return 0;
}
Now, we will see how to create an infinite loop using a while loop. The following is the definition for the infinite while loop:
while(1) {
// body of the loop..
}
In the above while loop, we put '1' inside the loop condition. As we know that any non-zero integer represents the true condition while '0' represents the false condition.
Example:
#include <stdio.h> int main()
{
int i=0;
while(1)
{
i++;
printf("i is :%d",i);
}
return 0;
}
In the above code, we have defined a while loop, which runs infinite times as it does not contain any condition. The value of 'i' will be updated an infinite number of times.
The do..while loop can also be used to create the infinite loop. The following is the syntax to create the infinite do..while loop.
do {
// body of the loop..
}while(1);
- #include <stdio.h>
int main()
{ char ch;
do
{
ch=getchar();
if(ch=='n')
{
break;
}
}
- while(1)
return 0;
}
- this loop will exceute indefinitely till the use enter character 'n'.
We can also use the goto statement to define the infinite loop.
infinite_loop; // body statements.
goto infinite_loop;
In the above code, the goto statement transfers the control to the infinite loop.
Macros
We can also create the infinite loop with the help of a macro constant. Let's understand through an example.
#include <stdio.h> #define infinite for(;;)
int main()
{
infinite
{
printf("hello");
}
return 0;
}
Comments
Post a Comment