Infinite Loop
An infinite loop is executed when the test expression never becomes false and the body of the loop is executed repeatedly. A program is stuck in an Infinite loop when the condition is always true. Mostly this is an error that can be resolved by using Loop Control statements.
Using for loop:
C
// C program to demonstrate infinite // loops using for loop #include <stdio.h> // Driver code int main () { int i; // This is an infinite for loop // as the condition expression // is blank for ( ; ; ) { printf ( "This loop will run forever.\n" ); } return 0; } |
Output
This loop will run forever. This loop will run forever. This loop will run forever. ...
Using While loop:
C
// C program to demonstrate // infinite loop using while // loop #include <stdio.h> // Driver code int main() { while (1) printf ( "This loop will run forever.\n" ); return 0; } |
Output
This loop will run forever. This loop will run forever. This loop will run forever. ...
Using the do-while loop:
C
// C program to demonstrate // infinite loop using do-while // loop #include <stdio.h> // Driver code int main() { do { printf ( "This loop will run forever.\n" ); } while (1); return 0; } |
Output
This loop will run forever. This loop will run forever. This loop will run forever. ...
C – Loops
Loops in programming are used to repeat a block of code until the specified condition is met. A loop statement allows programmers to execute a statement or group of statements multiple times without repetition of code.
C
// C program to illustrate need of loops #include <stdio.h> int main() { printf ( "Hello World\n" ); printf ( "Hello World\n" ); printf ( "Hello World\n" ); printf ( "Hello World\n" ); printf ( "Hello World\n" ); printf ( "Hello World\n" ); printf ( "Hello World\n" ); printf ( "Hello World\n" ); printf ( "Hello World\n" ); printf ( "Hello World\n" ); return 0; } |
Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World
There are mainly two types of loops in C Programming:
- 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.
- 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.
Loop Type | Description |
---|---|
for loop | first Initializes, then condition check, then executes the body and at last, the update is done. |
while loop | first Initializes, then condition checks, and then executes the body, and updating can be inside the body. |
do-while loop | do-while first executes the body and then the condition check is done. |