C infinite while loop

In previous tutorial we have seen the while loop concept in c programming. In this tutorial we are looking into another form of while loop i.e infinite while loop

Ways of infinite while loop

If we want to iterate loop
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 loop

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

Output :

 It won't Print anything

Explanation :

  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

Above statement can be interpreted as -

while(num>255){
}

Way 2 : Non-Zero Number as a Parameter

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

Output :

 Infinite Time "Hello" word

Explanation :

  1. We can specify any non-zero positive number inside while loop
  2. Non zero number is specified in the while loop which means that while loop will remains true forever.

Way 3 : Subscript variable remains the same

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

Output :

 Infinite Time "Hello C" word

Explanation :

  1. Condition is specified in while Loop, but terminating condition is not specified and even we haven’t modified the condition variable.
  2. In this case our subscript variable (Variable used to Repeat action) is 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.