A while loop checks its condition before each iteration. The body runs only while that condition remains true, so it may run zero times.
while (condition) {
// statements
// update something used by the condition
}
#include <stdio.h>
int main(void) {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Output
1
2
3
4
5
If the condition never becomes false, the loop does not end. For example, this loop never changes i:
int i = 1;
while (i <= 5) {
printf("%d\n", i);
// Missing i++ means the condition never changes.
}
Infinite loops can be intentional in event-driven or embedded programs, but beginner loops should normally make the terminating condition clear.
#include <stdio.h>
int main(void) {
int i = 1;
while (i <= 5) {
if (i == 4) {
break;
}
printf("%d\n", i);
i++;
}
return 0;
}
Output
1
2
3
#include <stdio.h>
int main(void) {
int i = 0;
while (i < 5) {
i++;
if (i == 3) {
continue;
}
printf("%d\n", i);
}
return 0;
}
Output
1
2
4
5
When using continue in a while loop, update the loop-control variable before the continue path if needed. Otherwise the loop can become infinite.
#include <stdio.h>
int main(void) {
int i = 50;
while (i >= 0) {
printf("%d\n", i);
i -= 10;
}
return 0;
}
Output
50
40
30
20
10
0
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "plus2net";
size_t length = strlen(text);
while (length > 0) {
putchar(text[length - 1]);
length--;
}
putchar('\n');
return 0;
}
Output
ten2sulp
#include <stdio.h>
int main(void) {
int sum = 0;
int i = 1;
while (i <= 5) {
sum += i;
i++;
}
printf("Sum: %d\n", sum);
return 0;
}
#include <stdio.h>
int main(void) {
int number;
printf("Enter a number from 1 to 10: ");
while (scanf("%d", &number) == 1 && (number < 1 || number > 10)) {
printf("Out of range. Enter 1 to 10: ");
}
if (number >= 1 && number <= 10) {
printf("Valid number: %d\n", number);
} else {
printf("Invalid input.\n");
}
return 0;
}
See another example: keep adding user-entered numbers until 0 is entered.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
21-01-2020 | |
| Write a program that finds the sum of even numbers between zero and twenty use while loop | |