C While Loop
A loop repeats a block of code many times. The while loop checks the condition first, and runs the body while it is true. Use it when you do not know how many times to repeat.
Syntax
while (condition) {
// code to repeat
}
Print numbers 1 to 5
#include <stdio.h>
int main(void) {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Output:
Output of the above program is
1
2
3
4
5
The three steps are: set the start value (i = 1), check the condition (i <= 5) and change the value (i++). If you forget the last step, the loop never ends.
Sum of digits of a number
#include <stdio.h>
int main(void) {
int n = 4825, sum = 0;
while (n > 0) {
sum += n % 10; // last digit
n /= 10; // remove last digit
}
printf("Sum = %d\n", sum);
return 0;
}
Output:
Output of the above program is
Sum = 19
Infinite loop
A condition which is always true makes a loop that never stops. We stop it with break.
#include <stdio.h>
int main(void) {
int count = 0;
while (1) {
count++;
if (count == 3) break;
}
printf("Stopped at %d\n", count);
return 0;
}
Output:
Output of the above program is
Stopped at 3
Note:
If the condition is false at the start, the body of a while loop does not run even one time.
Next: C Do While Loop.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |