Course Introduction to Programming

Command: doWhile

Course's Page 9 min Text by
User Image
Vitor Hugo Couto

In this lesson, we will learn a new repetition structure, doWhile. We will follow the topics:

  1. Task;
  2. doWhile structure;
  3. Coding.

Task

Make a program that reads an integer until the number entered is 2018. We have three options to solve the problem.

  • Use the while structure.
  • Use the for structure.
  • Use the doWhile structure.

doWhile Structure.

The doWhile structure is a repetition structure that performs a code snippet while a certain condition is true. The difference between doWhile and the while structure is that doWhile does not test the condition before the first loop.

Syntax

do{
	//Code
} while( condition );

We will 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 space in memory for an integer variable . Then, the code within do will be executed before checking the while condition. If the condition is true, the code between braces will be executed again until it is false, which is when is equal to 2018.

Now you know how to solve repetition problems using doWhile and its similarities and differences when compared to the while structure.