This is an alternative format for the "while" command, in which the condition is checked at the end. The repetition starts at the point labeled with the command "do", like this:
do
statement;
while (condition)
As in the previous case, if we want to repeat several statements (which is usual), we enclose them in braces.
As an example, let's see how would look a typical program which asks the user for a password and does not go on until the correct password is entered:
/*---------------------------*/
/* C# Example #17: */
/* example17.cs */
/* */
/* "do..while" statement */
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
using System;
public class Example17
{
public static void Main()
{
int validPassword = 711;
int password;
do
{
Console.Write("Enter your numeric password: ");
password = Convert.ToInt32(Console.ReadLine());
if (password != validPassword)
Console.WriteLine("Not valid!");
}
while (password != validPassword);
Console.WriteLine("Access granted.");
}
}
In this case, the condition is checked at the end, so the password will be asked at least once. While the answer given is not correct, it will be asked again. Finally, when the correct password is entered, the computer displays "Access granted" and the program finished.
As we will see a bit later, if we prefer a text password rather than a number, changes to the program are minimal:
/*---------------------------*/
/* C# Example #18: */
/* example18.cs */
/* */
/* "do..while" statement (2)*/
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
using System;
public class Example18
{
public static void Main()
{
string validPassword = "secret";
string password;
do
{
Console.Write("Enter your password: ");
password = Console.ReadLine();
if (password != validPassword)
Console.WriteLine("Not valid!");
}
while (password != validPassword);
Console.WriteLine("Acces granted.");
}
}
Suggested exercises:
· Write a program that accepts positive numbers from the user, and calculates the sum of them all (and stops when the user enters a negative number or zero).
· Create a program to display on screen the numbers 1 to 10, using "do .. while".
· Create a program to write on screen the even numbers from 26 to 10 (downwards), using "do .. while".
· Prepare a program that asks the user for a numeric id and a numeric password, and does not end until he enters 1234 as an id and 1111 as the password.
· Prepare a program that asks the user for a name and a password, and does not end until he enters the name "Pedro" and the password "Peter".
No comments:
Post a Comment