Course Introduction to Programming
Command: doWhile
In this lesson, we will learn about a new repetition structure: the Do-While loop.
We will understand how it works, in which situations it is most advantageous, and how it differs from the while and for loops, as well as see a practical example of how to use this structure.
Problem
Write a program that reads an integer N until the number entered is 2018. We have three options to solve the problem.
- Use the whilestructure.
- Use the forstructure.
- Use the doWhilestructure.
The doWhile Structure
The doWhile structure is a repetition structure that executes a piece of code as long as a condition is true, just like the while loop. The main difference is that in the doWhile loop, the condition is checked after the code block is executed โ meaning, the code is executed at least once, regardless of the condition. This feature makes the doWhile loop especially useful in situations where we need to execute something before testing the condition, such as asking for user input and only then checking if the entered value is valid. So, in summary:
- In a whileloop, the program tests the condition first; if it is false, the code is not executed at all.
- In a doWhileloop, the program executes the block once and only then tests the condition.
Syntax
do{
	//Code
} while( condition );
Let's now use the structure to solve the problem.
#include<stdio.h>
int main(){
	int n;
	
	do{
		scanf("%d", &n);
	} while(n!=2018);
}
First, we ask the program to reserve memory space for an integer variable do will be executed before the while check is made, and if the condition is true, the code between the braces is executed again until it becomes false, which will be when 
When to use while and doWhile
The while loop is typically used when there might be no need to execute the code if the condition is false from the start.
- Example: reading numbers as long as the user wants to continue.
The doWhile loop, on the other hand, is used when you need to execute the code at least once before checking the condition.
- Example: displaying a menu of options and only then asking if the user wants to exit.
Conclusion
Throughout this lesson, you learned what the doWhile repetition structure is, understood its functionality and its main characteristics, such as the guaranteed execution at least once before the condition is checked. You also saw practical examples of how to use it, understanding its similarities and differences in relation to the while loop, as well as knowing when to apply each one appropriately, especially in situations that require reading or validating data before checking the condition.
Now you know how to solve repetition problems using the doWhile loop and its similarities and differences with the while structure. ๐
