3️⃣

6.3 Do-While Loops

 

Do-While Loop

A do-while loop is another type of loop used in programming. It is similar to the while loop, except it is always guaranteed to run at least once. For example, let’s say we want to prompt a user to enter a number between 1 and 10 for our program. A do-while loop for this would look like the following:
 
int num = 0; do { printf(“Enter a number between 1 and 10: ”); scanf(“%d”, &num); } while ((num < 1) || (num > 10));
 
In the above example, we have a variable of type int that is assigned the value of 0. Then, we have a do-while loop. The computer will run the code within this loop without checking any conditions. The code prompts the user to enter a number between 1 and 10, and stores the user’s number in num. After the closing curly brace of this loop, the computer checks the conditional. The conditional is placed after the loop because the computer needs to check it to confirm if it should run the loop again or be done with it altogether. In our case, if the user enters a number that is less than 1 or greater than 10, the computer will have to run through the loop again until the user cooperates.
 

Previous Section

Next Section

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.