C - While Loop: A Comprehensive Guide
Learn about the while
loop in C, an entry-verified loop that allows for repeated execution of code based on a specified condition. This section covers the syntax of the while loop and provides examples to enhance your understanding of its use.
C - While Loop
In C, while
is a keyword to form loops. It's often called the entry verified loop. The other loops are for
and do-while
.
Syntax of C while Loop
Syntax
while(expression){
statement(s);
}
The while
keyword is followed by a parenthesis with a Boolean expression and a block of statements inside curly brackets.
How while Loop Works in C?
The compiler evaluates the expression. If true, it executes the block. If false, it skips the block and moves to the next statement. The while
loop is tested before entering the loop, so it might not execute at all if the condition is false initially.
Example: Printing "Hello World" 5 Times
Example
#include <stdio.h>
int main() {
int a = 1;
while(a <= 5) {
printf("Hello World \n");
a++;
}
printf("End of loop");
return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
End of loop
The variable a
controls the repetitions. It starts at 1, increments by 1 each loop, and stops when it reaches 6. Changing a
to 10 initially skips the loop entirely as the condition is false.
Using while as a Conditional Loop
A while
loop can continue till a condition is satisfied.
Example
#include <stdio.h>
int main() {
int x = 0;
while(x >= 0) {
(x % 2 == 0) ? printf("%d is Even \n", x) : printf("%d is Odd \n", x);
printf("\n Enter a positive number: ");
scanf("%d", &x);
}
printf("\n End of loop");
return 0;
}
Output
0 is Even
Enter a positive number: 12
12 is Even
Enter a positive number: 25
25 is Odd
Enter a positive number: -1
End of loop
While Loop with break and continue
break
terminates a loop:
Example
while (expr) {
if (condition)
break;
}
continue
makes a loop repeat from the beginning:
Example
while (expr) {
if (condition)
continue;
}
More Examples of C while Loop
Example: Printing Lowercase Alphabets
Example
#include <stdio.h>
int main() {
char a = 'a';
while(a <= 'z') {
printf("%c", a);
a++;
}
printf("\n End of loop");
return 0;
}
Output
abcdefghijklmnopqrstuvwxyz
End of loop
Example: Equate Two Variables
Example
#include <stdio.h>
int main() {
int a = 10, b = 0;
while(a != b) {
a--;
b++;
printf("a: %d b: %d\n", a, b);
}
printf("\n End of loop");
return 0;
}
Output
a: 9 b: 1
a: 8 b: 2
a: 7 b: 3
a: 6 b: 4
a: 5 b: 5
End of loop
while Vs. do while Loops
The do-while
loop is called the exit verified loop and has a different syntax. Differences are explained in the do-while chapter.