Infinite Loops in C

Infinite Loop in C

An infinite loop is a looping construct that does not terminate and executes forever.
It is also called an indefinite loop or an endless loop.
It may either produce continuous output or no output.


When to Use an Infinite Loop

An infinite loop is useful for applications that continuously accept user input and generate output until the user exits manually.

Common situations where infinite loops are used

  • Operating systems run in an infinite loop and stop only when the user shuts down the system.

  • Servers run continuously and respond to client requests until the administrator stops them.

  • Games run in a loop and continue accepting user input until the player exits.


Ways to Create an Infinite Loop in C

  • for loop

  • while loop

  • do...while loop

  • goto statement

  • Macros


1. Infinite for Loop

Syntax

for(;;) { // body of the loop }

All parts of the for loop are optional. Since no condition is specified, the loop runs forever.

Example

#include <stdio.h> int main() { for(;;) { printf("Infinite Loop"); } return 0; }

This program prints "Infinite Loop" continuously.


2. Infinite while Loop

Syntax

while(1) { // body of the loop }

Any non-zero value represents true, so the loop runs indefinitely.

Example

#include <stdio.h> int main() { int i = 0; while(1) { i++; printf("i is :%d", i); } return 0; }

The value of i increases endlessly.


3. Infinite do...while Loop

Syntax

do { // body of the loop } while(1);

Example

#include <stdio.h> int main() { char ch; do { ch = getchar(); if(ch == 'n') { break; } } while(1); return 0; }

This loop runs indefinitely until the user enters the character 'n'.


4. Infinite Loop Using goto

Example

infinite_loop: // body statements goto infinite_loop;

The goto statement transfers control back to the label, creating an endless loop.


5. Infinite Loop Using Macros

Example

#include <stdio.h> #define infinite for(;;) int main() { infinite { printf("hello"); } return 0; }

Here, the macro infinite expands to for(;;), producing an infinite loop.

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays