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

C do-while Loop

What is a do-while Loop?

A do-while loop is a post-test loop: it runs its body first and only checks the condition afterward, guaranteeing at least one execution even if the condition would have been false from the very start.

Example: What is a do-while Loop?

c
#include <stdio.h>
int main() {
	int x = 10;
	do {
		printf("Runs at least once");
	} while (x < 5);
	return 0;
}

Simple Countdown

You can print a countdown sequence with a do-while loop by decrementing the counter inside the body on each pass, similar to a while loop, but with the guarantee that the first value is always printed at least once.

Example: Simple Countdown

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

User Input Validation

do-while is well suited for input validation, since you typically need to prompt the user and read their input at least once before you have anything to check -- a plain while loop can't guarantee that first prompt happens.

Example: User Input Validation

c
#include <stdio.h>
int main() {
	int value;
	do {
		sscanf("7", "%d", &value);
	} while (value < 0);
	printf("%d", value);
	return 0;
}

Sum Accumulation

Just like a while loop, a do-while loop can accumulate a running total across iterations by updating a sum variable inside its body each time it executes.

Example: Sum Accumulation

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

while vs. do-while

The key difference from a while loop is timing: while checks its condition before the first run and may execute zero times, while do-while checks after the first run and always executes at least once.

Example: while vs. do-while

c
#include <stdio.h>
int main() {
	int x = 10;
	while (x < 5) {
		printf("while: never runs\n");
	}
	do {
		printf("do-while: runs once");
	} while (x < 5);
	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.