While Loop in C


1.What is while loop in C ?

Ans: The while Loop is an entry-controlled loop in C programming language. This loop can be used to iterate a part of code while the given condition remains true.


Simple Explanation :

In this image we can see that the boy is thinking on question of math. Then he will check that the formula which will be true. Then he solves the sum.

While loop also work in the same way. It will first check the condition and execute the following function till the condition becomes false.



Working of while loop :


Syntax  :

while (test expression)
{
   // body consisting of multiple statements
}


 Example:

1. Write a C program to print numbers from 0 to 10 and 10 to 0 using two while loops


#include <stdio.h> int main()
{ int i = 0; // Initialize the loop counter // First while loop: Print numbers from 0 to 10 printf("Numbers from 0 to 10:\n"); while (i <= 10)
{ printf("%d ", i); // Print the current value of i i++; // Increment the loop counter
} }

 Output :



2. Write a C program that calculates the product of numbers from 1 to 5 using a while loop.

#include <stdio.h> int main()
{ int number = 1; // Initialize the variable to store the current number int product = 1; // Initialize the variable to store the product // Start a while loop to iterate from 1 to 5 while (number <= 5)
{ // Update the product by multiplying it with the current number product *= number; // Print the current number and product in each iteration printf("Current number: %d, Current product: %d\n", number, product); // Increment the number for the next iteration number++; } }

Output :