C

C – Example Of A While Loop In C Programming

A loop is used to execute a series of statements until a given condition returns false. We learned for loop in the previous tutorial. This guide will teach you how to use the while loop in C.

While loop in C

While loop syntax:

while (condition test)
{
      //Statements to be executed repeatedly 
      // Increment (++) or Decrement (--) Operation
}

While loop example

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

Output:

1 2 3 4

step 1: The variable count is initialized to 1 and then tested for the condition.
step2: If the condition returns true, the statements within the body of the while loop are executed; otherwise, control exits the loop.
step 3: The value of count is incremented using the ++ operator, and the loop condition is tested again.
Determine the outcome of this while loop.

#include <stdio.h>
int main()
{
     int var=1;
     while (var <=2)
     {
        printf("%d ", var);
     }
}

The program exemplifies an infinite while loop. Because the value of the variable var is the same (there is no ++ or – operator used on this variable within the body of the loop), the condition var=2 will always be true and the loop will never end.

Infinite while loop examples

Exemplification 1:

#include <stdio.h>
int main()
{
     int var = 6;
     while (var >=5)
     {
        printf("%d", var);
        var++;
     }
   return 0;
}

Infinite loop: var will always have a value greater than 5, so the loop will never end.
Exemplification 2:

#include <stdio.h>
int main()
{
    int var =5;
    while (var <=10)
    {
       printf("%d", var);
       var--;
    }
    return 0;
}

Infinite loop: var value will continue to decrease due to the — operator, so it will always be = 10.

While loop use of logical operators

Just like relational operators (<, >, >=, <=, ! =, ==), we can also use logical operators in while loop. The following possibilities exist:

while(num1<=10 && num2<=10)

-Using the AND(&&) operator, which means that both conditions must be true.

while(num1<=10||num2<=10)

– Using the OR(||) operator, this loop will continue to run until both conditions return false.

while(num1!=num2 &&num1 <=num2)

– We’re using the logical operators NOT (!) and AND here (&&).

while(num1!=10 ||num2>=num1)

While loop with logical operator example

In this example, we use the logical operator inside a while loop to test multiple conditions.

#include <stdio.h>
int main()
{
   int i=1, j=1;
   while (i <= 4 || j <= 3)
   {
	printf("%d %d\n",i, j);
	i++;
	j++;
   }
   return 0;
}

Output:

1 1
2 2
3 3
4 4

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button