Loop
C programming language provides different types of loops that are used to execute a block of code multiple times based on the condition specified in the loop. Loops help to simplify repetitive tasks and save time in programming. In this post, we will focus on the while loop in C and how to use it effectively in your code.
While loop
The while loop is a basic loop that executes a block of code repeatedly until the condition specified in the loop is false. The syntax of the while loop in C is as follows: while (/* condition /) { / code / / code */ } The code within the while loop will execute repeatedly as long as the condition specified in the loop is true. If the condition is false, the code will skip the while loop and move on to the next statement in the program.
Example 1
Let's take a simple example to understand the while loop syntax and how it works in C.
copy
#include <stdio.h>
int main()
{
int a = 5, i = 0;
while (a == 5)
{
printf("I am while loop\n");
i = i + 1;
if (i == 5)
{
a = 4;
}
}
return 0;
}
In this example, the while loop will keep running until the value of 'a' is not equal to 5. As long as the value of 'a' is 5, the program will keep printing "I am while loop" five times and then exit the loop. Here, we have used an if statement to change the value of 'a' to 4 when the loop executes five times.
Example 2:
copy
#include <stdio.h>
int main()
{
int a, i = 1;
printf("enter any number\n");
scanf("%d", &a);
while (1)
{
printf(" %d X %d = %d\n", a, i, a * i);
i = i + 1;
if (i == 11)
{
break;
}
}
return 0;
}
In this example, the program will generate a multiplication table of the number entered by the user using a while loop. The while loop will execute until the value of 'i' is equal to 11, and the program will use the break statement to exit the loop. The break statement is used to force an exit from the loop regardless of whether the loop condition is true or false. Conclusion: Loops are an essential part of C programming language, and while loops are one of the simplest and most frequently used types of loops. They can be used to execute code repeatedly until a specified condition is met. In this post, we have discussed the syntax of the while loop in C and provided some examples to help you understand how to use it in your code. Additionally, we have also explained the use of the break statement to exit a loop prematurely.