C infinite while loop

   

Different Ways of Infinite While Loop in C

We can use While loop for looping purpose. We can use infinite while loop in C to iterate loop for infinite times. We can Even use Infinite while loop for operation in which we cannot decide how many iteration does it take at compile time.


Way 1 : Semicolon at the end of While

#include<stdio.h>
void main()
{
int num=300;
while(num>255);  //Note it Carefully
       printf("Hello");
}

Output : 

 It won't Print anything

Explanation of Above Infinite Loop :

  1. In the above program , Condition is specified in the While Loop
  2. Semicolon at the end of while indicated while without body.
  3. In the program variable num doesn’t get incremented , condition remains true forever.
  4. As Above program does not have Loop body , It won’t print anything

Way 2 : Non-Zero Number as a Parameter

#include<stdio.h>
void main()
{
while(1)
    printf("Hello");
}

Output :

 Infinite Time "Hello" word

How ?

  1. Note : We can specify any Non-Zero Positive Number inside while
  2. Non Zero is specified in the While Loop means Loop will have always TRUE condition specified inside.
  3. As  condition inside loop doesn’t get changed ,condition inside while remains true forever.

Way 3 : Subscript Variable Remains the same

#include<stdio.h>
void main()
{
int num=20;
while(num>10)
    {
    printf("Hello");
    printf(" C ");
    }
}

Output : 

 Infinite Time "Hello C" word

How ?

  1. Condition is specified in while Loop ,but Terminating Condition is not specified
  2. Also Subscript Variable [Variable used to Repeat action] is also not either incremented or decremented
  3. so while remains true forever.

Way 4 : Character as a Parameter in While Loop

#include<stdio.h>
void main()
{
while('A')
    printf("Hello");
}

Output : 

 Infinite Time "Hello" word

How ?

  1. Character is Represented in integer in the form of ASCII internally.
  2. Any Character is Converted into Non-zero Integer ASCII value
  3. Any Non-zero ASCII value is TRUE condition , that is why Loop executes forever

How to Break Infinite While Loop :

Whenever you decide to use infinite while loop while writing code , you must include terminating or ending condition in a while loop to ensure that your code will be terminated at some moment of time.

while(1) {

 ch = fgetc(fp);
 printf("%c",ch);
 fp++;

 if(ch == 'EOF') 
       break;
}

In the Above program we cannot decide , size of file while writing program so we decided to go with infinite while loop. Our main purpose is to read file so we have provided breaking condition inside loop which will takes control out of loop.