Do While Loop
Part of the Fundamentals section of Coddy's C# journey — lesson 43 of 69.
The do-while loop is similar to the while loop, but with one key difference: the code block is executed at least once before the condition is checked. This means that the loop's body will always run the first time, regardless of whether the condition is true or false.
Here's the basic structure of a do-while loop:
do {
// Code to be executed
} while (condition);The do keyword marks the beginning of the loop, followed by the code block in curly braces. After the code block, the while keyword introduces the condition. The loop will continue to execute as long as the condition is true.
Here's an example:
int count = 0;
do {
Console.WriteLine("Count: " + count);
count++;
} while (count < 5);In this example, the code inside the do block will execute first, printing "Count: 0" and incrementing count to 1. Then, the condition count < 5 is checked. Since it's true, the loop continues.
This process repeats until count becomes 5, at which point the condition becomes false and the loop terminates.
The output of this code will be:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4Challenge
BeginnerWrite a C# 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 the code block at least once before checking the condition:
do {
// Code to be executed
} while (condition);Example:
int count = 0;
do {
Console.WriteLine("Count: " + count);
count++;
} while (count < 5);The loop body runs first, then the condition is checked. The loop continues as long as the condition is true.
Try it yourself
using System;
public class Program {
public static void Main(string[] args) {
// Initialize variables
int sum = 0;
int number = 1;
// Your code here
// Print the final sum
Console.WriteLine("Final Sum: " + sum);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3