Learning Sections show
While Loop in C
Example
#include<stdio.h> // Include the standard input-output library
int main() {
// Variable declaration
int count = 1;
// While loop to print numbers from 1 to 5
while (count <= 5) {
// Print the current value of count
printf("Number: %d\n", count);
// Increment count by 1
count++;
}
// End of the main function
return 0;
}
Explanation:
The while
loop in C is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The condition is evaluated before the execution of the loop's body.
In this example:
#include<stdio.h>
: Includes the standard input-output library which allows us to use theprintf
function.int main()
: The main function where the program execution begins.int count = 1;
: Declares an integer variablecount
and initializes it to 1.while (count <= 5)
: The loop continues to execute as long as the conditioncount <= 5
is true.printf("Number: %d\n", count);
: Prints the current value ofcount
to the console.count++;
: Increments the value ofcount
by 1.return 0;
: Ends the main function and returns 0 to the operating system, indicating that the program ended successfully.