Do While Loop
Part of the Fundamentals section of Coddy's C journey — lesson 39 of 63.
The do-while loop is similar to the while loop, but with one important difference: the code block is executed at least once, and then the condition is checked.
Create a do-while loop:
do {
// Code to be executed
} while (condition);Let's create a program that asks the user to enter a positive number:
int number;
do {
printf("Please enter a positive number: ");
scanf("%d", &number);
} while (number <= 0);
printf("You entered: %d\n", number);In this example:
- The code inside the do block runs first, asking for input
- After getting the input, the condition
number <= 0is checked
- If the condition is true (the number is not positive), the loop repeats
- If the condition is false (the number is positive), the loop stops
The do-while loop is perfect for situations where you need to execute the code at least once, regardless of the condition.
Challenge
EasyWrite a program that uses a do-while loop to do the following:
- Initialize a variable
sumto 0. - Initialize a variable
numberto 1. - In each iteration, add
numbertosum. - Increment
numberby 2 in each iteration (i.e., 1, 3, 5, ...). - print
numberandsum:Sum is: [The sum value]Num is: [The number value] - Continue the loop as long as
numberis less than or equal to 50. - Print the final value of
sumafter the loop finishes:Final Sum: [The final sum value]
Cheat sheet
The do-while loop executes code at least once, then checks the condition:
do {
// Code to be executed
} while (condition);Example asking for positive input:
int number;
do {
printf("Please enter a positive number: ");
scanf("%d", &number);
} while (number <= 0);
printf("You entered: %d\n", number);The do-while loop is ideal when you need to execute code at least once before checking the condition.
Try it yourself
#include <stdio.h>
int main() {
// Initialize variables
int sum = 0;
int number = 1;
// Your code here
// Print the final sum
printf("Final Sum: %d\n", sum);
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge