← Back to C Course | Chapter 4: Control Flow | Lesson 7 of 11

C while Loop

What is a while Loop?

A while loop checks its condition before every iteration, including the very first one -- if the condition starts out false, the loop body never runs at all, unlike a do-while loop which always runs once regardless.

Example: What is a while Loop?

c
#include <stdio.h>
int main() {
	int x = 10;
	while (x < 5) {
		printf("never runs");
	}
	printf("Loop skipped since condition was false");
	return 0;
}

Counting Up

Using a counter variable that increases each pass, a while loop can print an ascending sequence of numbers -- initializing the counter before the loop and incrementing it inside the body on each iteration.

Example: Counting Up

c
#include <stdio.h>
int main() {
	int i = 1;
	while (i <= 5) {
		printf("%d ", i);
		i++;
	}
	return 0;
}

Counting Down

By initializing a counter at a high value and decreasing it each iteration instead of increasing it, the same while structure counts downward -- useful for countdowns or processing a range in reverse.

Example: Counting Down

c
#include <stdio.h>
int main() {
	int i = 5;
	while (i >= 1) {
		printf("%d ", i);
		i--;
	}
	return 0;
}

Sum of First N Numbers

Accumulating a running total inside a while loop -- adding the current counter value to a separate sum variable on each pass -- is the standard pattern for computing something like the sum of the first N integers.

Example: Sum of First N Numbers

c
#include <stdio.h>
int main() {
	int i = 1, sum = 0;
	while (i <= 5) {
		sum += i;
		i++;
	}
	printf("%d", sum);
	return 0;
}

Infinite Loop Prevention

If the loop's condition never becomes false -- typically because you forgot to update the variable it depends on -- the loop runs forever, freezing the program; always double check that every code path inside the loop moves the condition toward becoming false.

Example: Infinite Loop Prevention

c
#include <stdio.h>
int main() {
	int i = 0;
	while (i < 5) {
		printf("%d ", i);
		i++;
	}
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.