Menu
C++ Tutorials

C++

Do-While Loop



Tutorials > C++ > Do-While Loop

View Full Source

Introduction

In the last tutorial, you were exposed to the While Loop. Another very similar loop is the do-while loop.

The do-while loop takes the form :

    do { statements } while ( logical expression );

Why would anyone want to use this when they could just use the while loop? You may have already noticed that the loop terminating condition is only checked at the end of the loop. This results in the loop being run at least once. The while loop will not run if the logical expression is false whereas the do-while loop will always run at least once no matter what the result of the logical expression is.

An example of how this can be used effectively is shown in the code below.

Contents of main.cpp :


#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

int main()
{
	string data;

Virtually the same loop as the previous tutorial has been placed below. This code segment allows you to continue entering data until q is entered.

	do 
	{
		cout << "Enter Data (q to quit) : ";
		cin >> data;
	} while(data != "q");

This is a more efficient and logical way of accepting user input. In the previous tutorial we had to make sure that the data variable was initialized to some value other than q at startup to allow the loop to be entered at least once. We know that the user must always enter data at least once and therefore the do-while loop could be used.

	system("pause");

	return 0;
}

You should now be comfortable in using both the while and the do-while loops. Just remember that if the loop needs to be run at least once, it is usually better to use the do-while loop. If it is possible that the loop may not run, you need to use the while loop.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 15 - While Loop Tutorial 17 - For Loop >

Back to Top


All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer

Links