C Language | Flow Control | while Statement
The while statement repeats code while its condition is true.
Creating a Loop
Repetition is a fundamental part of program control. A while statement repeats a statement until its condition becomes false.
while (condition) statement
A counter variable is often updated inside the loop so that the condition eventually becomes false.
Code 1
#include <stdio.h>
int main() {
int iCount;
printf("Enter the number of repetitions. >");
scanf("%d", &iCount);
while (iCount > 0) {
printf("counter = %d\n", iCount);
iCount--;
}
return 0;
}
The loop repeats while iCount is greater than zero and decreases the counter after each iteration.
Use break to leave a loop immediately, including an intentional infinite loop.
Code 2
#include <stdio.h>
int main() {
int iCount = 0;
while (1) {
if (iCount == 1000) break;
printf("iCount = %d\n", iCount++);
}
return 0;
}
The postfix increment operator updates iCount after its current value is passed to printf(). The same operation can be written on two lines.
printf("iCount = %d\n", iCount);
iCount++;
Loops can also be nested. This is common when processing two-dimensional data.
Code 3
#include <stdio.h>
int main() {
int iOp1 = 1, iOp2 = 1;
while (iOp1 < 10) {
while (iOp2 < 10) {
printf("%2d ", iOp1 * iOp2);
iOp2++;
}
printf("\n");
iOp2 = 1;
iOp1++;
}
return 0;
}
This prints a multiplication table. In %2d, 2 specifies a minimum field width of two characters.
Returning to the Top of a Loop
Use continue to skip the remainder of the current iteration and evaluate the loop condition again.
Code 4
#include <stdio.h>
int main() {
int iCount = 0;
while (iCount++ < 100) {
if (iCount % 2) continue;
printf("%d ", iCount);
}
return 0;
}
This program prints only even numbers. When iCount % 2 is nonzero, the number is odd and continue skips the call to printf().