While loop in C Language

0


While loop in C Language 




GAIN AND SHINE



Introduction to While Loop in C

    C programming language offers several types of loops, including for loop, while loop, and do-while loop. In this blog, we will explore the while loop, which is a powerful and versatile loop that allows you to execute a block of code repeatedly as long as a specific condition is true.

    The while loop in C is a pretest loop, meaning that the condition is tested before executing the loop body. If the condition is true, the loop body is executed, and the condition is tested again. This process continues until the condition becomes false, at which point the loop terminates, and control transfers to the next statement in the program.


Syntax of While Loop in C

The syntax for a while loop in C is as follows:

while (condition) {

   // statement to be executed repeatedly

}

    Here, the condition is a Boolean expression that is tested before each iteration of the loop. If the condition is true, the statements inside the loop are executed. If the condition is false, the loop terminates, and the program control moves to the next statement after the loop.


Example of While Loop in C

    Let's take a simple example to illustrate the working of the while loop in C. Suppose we want to print the first 5 natural numbers using a while loop.

We can write the following code:

#include <stdio.h>

   int main() {

   int i = 1;

   while (i <= 5) {

      printf("%d ", i);

      i++;

   }

   return 0;

}

Output:

1 2 3 4 5

    In this example, the loop starts with i = 1, and the condition i <= 5 is true. Therefore, the statements inside the loop body are executed, which prints the value of i and increments i by 1. This process continues until i becomes 6, at which point the condition becomes false, and the loop terminates.


Infinite While Loop

A while loop can also become infinite if the condition is always true.

For example:

while (1) {

   // statement to be executed repeatedly


    This loop will never terminate, and the statements inside the loop body will be executed infinitely.



Conclusion

    The while loop is a fundamental construct in C programming that allows you to execute a block of code repeatedly as long as a specific condition is true. It is a pretest loop, meaning that the condition is tested before executing the loop body. With the help of examples, we have demonstrated how to use the while loop in C and how to avoid infinite loops.



Post a Comment

0Comments

Share Your Feedback Here !!

Post a Comment (0)