Repetition Structures - Jones & Bartlett Learning

Transcription

24785 CH06 BRONSON.qrk11/10/049:05MPage 301Repetition Structures6.2 Do While Loops6.3 Interactive Do While Loops6.4 For/Next Loops6.5 Nested LoopsGoals6.1 Introduction6.6 Exit-Controlled Loops6.7 Focus on Program Design and Implementation: After-theFact Data Validation and Creating Keyboard Shortcuts6.8 Knowing About: Programming Costs6.9 Common Programming Errors and Problems6.10 Chapter Review

24785 CH06 BRONSON.qrk302 11/10/049:05MPage 302Chapter 6: Repetition StructuresThe applications examined so far have illustrated the programming concepts involved ininput, output, assignment, and selection capabilities. By this time you should havegained enough experience to be comfortable with these concepts and the mechanics ofimplementing them using Visual Basic. However, many problems require a repetitioncapability, in which the same calculation or sequence of instructions is repeated, overand over, using different sets of data. Examples of such repetition include continualchecking of user data entries until an acceptable entry, such as a valid password, ismade; counting and accumulating running totals; and recurring acceptance of inputdata and recalculation of output values that only stop upon entry of a designated value.This chapter explores the different methods that programmers use to constructrepeating sections of code and how they can be implemented in Visual Basic. A repeatedprocedural section of code is commonly called a loop, because after the last statement inthe code is executed, the program branches, or loops back to the first statement andstarts another repetition. Each repetition is also referred to as an iteration or passthrough the loop.6.1IntroductionThe real power of most computer programs resides in their ability to repeat the same calculation or sequence of instructions many times over, each time using different data,without the necessity of rerunning the program for each new set of data values. Thisability is realized through repetitive sections of code. Such repetitive sections are writtenonly once, but include a means of defining how many times the code should be executed.Constructing repetitive sections of code requires four elements:1. A repetition statement that both defines the boundaries containing the repeatingsection of code and controls whether the code will be executed or not. There arethree different forms of Visual Basic repetition structures: Do While structures, Forstructures, and Do/Loop Until structures.2. A condition that needs to be evaluated. Valid conditions are identical to those usedin selection statements. If the condition is True, the code is executed; if it is False,the code is not executed.3. A statement that initially sets the condition. This statement must always be placedbefore the condition is first evaluated, to ensure correct loop execution the first time.4. A statement within the repeating section of code that allows the condition tobecome False. This is necessary to ensure that, at some point, the repetitions stop.Pretest and Posttest LoopsThe condition being tested can be evaluated either at the beginning or the end of therepeating section of code. Figure 6–1 illustrates the case where the test occurs at thebeginning of the loop. This type of loop is referred to as a pretest loop, because the condition is tested before any statements within the loop are executed. If the condition is

24785 CH06 BRONSON.qrk11/10/049:05MPage 3036.1IntroductionPreviousstatementIsthe conditionTrueYesLoopstatementNoNextstatementFigure 6–1A Pretest LoopTrue, the executable statements within the loop are executed. If the initial value of thecondition is False, the executable statements within the loop are never executed, andcontrol transfers to the first statement after the loop. To avoid infinite repetitions, thecondition must be updated within the loop. Pretest loops are also referred to asentrance-controlled loops. Both the Do While and For loop structures are examples ofsuch loops.A loop that evaluates a condition at the end of the repeating section of code, asillustrated in Figure 6–2, is referred to as a posttest or exit-controlled loop. Such loopsalways execute the loop statements at least once before the condition is tested. BecausePreviousstatementLoopstatementIsthe conditionTrueYesNoNextstatementFigure 6–2A Posttest Loop 303

24785 CH06 BRONSON.qrk304 11/10/049:05MPage 304Chapter 6: Repetition Structuresthe executable statements within the loop are continually executed until the conditionbecomes False, there must always be a statement within the loop that updates the condition and permits it to become False. The Do /Loop Until construct is an example of aposttest loop.Fixed Count Versus Variable Condition LoopsIn addition to where the condition is tested (pretest or posttest), repeating sections ofcode are also classified as to the type of condition being tested. In a fixed-count loop,the condition is used to keep track of how many repetitions have occurred. For example,we might want to produce a very simple fixed design such ***In each of these cases, a fixed number of calculations is performed or a fixed number of lines is printed, at which point the repeating section of code is exited. All ofVisual Basics repetition statements can be used to produce fixed-count loops.In many situations, the exact number of repetitions is not known in advance or theitems are too numerous to count beforehand. For example, if we are working with alarge amount of market research data, we might not want to take the time to count thenumber of actual data items that must be entered and so we would use a variable-condition loop. In a variable-condition loop, the tested condition does not depend on acount being achieved, but rather on a variable that can change interactively with eachpass through the loop. When a specified value is encountered, regardless of how manyiterations have occurred, repetitions stop. All of Visual Basic’s repetition statements canbe used to create variable-condition loops. In this chapter we will encounter examplesof both fixed-count and variable-condition loops.6.2Do While LoopsIn Visual Basic, a Do While loop is constructed using the following syntax:Do While expressionstatement(s)LoopThe expression contained after the keywords Do While is the condition tested todetermine if the statements provided before the Loop statement are executed. Theexpression is evaluated in exactly the same manner as that contained in an If-Elsestatement—the difference is in how the expression is used. As we have seen, when theexpression is True in an If-Else statement, the statement or statements following the

24785 CH06 BRONSON.qrk11/10/049:05MPage 3056.2Do While Loopsexpression are executed once. In a Do While loop, the statement or statements followingthe expression are executed repeatedly as long as the expression remains True. Considering the expression and the statements following it, the process used by the computerin evaluating a Do While loop is:1. Test the expression.2. If the expression is True:a. Execute all statements following the expression up to the Loop statement.b. Go back to step 1.ElseExit the Do While statement and execute the next executable statement followingthe Loop statement.Note that step 2b forces program control to be transferred back to step 1. Thistransfer of control back to the start of a Do While statement, in order to reevaluate theexpression, is what forms the loop. The Do While statement literally loops back on itselfto recheck the expression until it becomes False. This means that somewhere in theloop, it must be possible to alter the value of the tested expression so that the loop ultimately terminates its execution.This looping process produced by a Do While statement is illustrated in Figure 6–3.A diamond shape is used to show the two entry and two exit points required in thedecision part of the Do While statement.To make this process more understandable, consider the code segment below. Recallthat the statement lstDisplay.Items.Add(count) will display each value of countinto a List Box.Do While count 10lstDisplay.Items.Add(count)LoopEnter theWhile LoopTest theCondition(step 1)Conditionis FalseExittheLoopConditionis TrueLoopFigure 6–3ExecuteStatement 1throughStatement n(step 2a)Anatomy of a Do While Loop 305

24785 CH06 BRONSON.qrk306 11/10/049:05MPage 306Chapter 6: Repetition StructuresAlthough this loop structure is valid, the alert reader will realize that we have created a situation in which the lstDisplay statement either is called forever (or until westop the program) or it is not called at all. Let us examine why this happens.If count has a value less than or equal to 10 when the expression is first evaluated,the lstDisplay statement is executed. When the Loop statement is encountered, thestructure automatically loops back on itself and retests the expression. Because we havenot changed the value stored in count, the expression is still true and the lstDisplaystatement is again executed. This process continues forever, or until the program containing this statement is prematurely stopped by the user. However, if count starts witha value greater than 10, the expression is false to begin with and the lstDisplay statement is never executed.How do we set an initial value in count to control what the Do While statementdoes the first time the expression is evaluated? The answer is to assign values to eachvariable in the tested expression before the Do While statement is encountered. Forexample, the following sequence of instructions is valid:Dim count As Integercount 1Do While count 10lstDisplay.Items.Add(count)LoopUsing this sequence of instructions, we ensure that count starts with a value of 1.We could assign any value to count in the assignment statement—the important thingis to assign a value. In practice, the assigned value depends upon the application.We must still change the value of count so that we can finally exit the Do Whileloop. This requires an expression such as count count 1 to increment the value ofcount each time the Do While statement is executed. All that we have to do is add astatement within the Loop structure that modifies count’s value so that the loop ultimately terminates. For example, consider the following expanded loop:count 1' initialize countDo While count 10lstDisplay.Items.Add(count)count count 1 ' increment countLoopNote that the Do While structure begins with the keywords Do While and ends withthe keyword Loop. For this particular loop, we have included two statements within theLoop structure:lstDisplay.Items.Add(count)count count 1 ' increment countNow we need to analyze the complete section of code to understand how it operates. The first assignment statement sets count equal to 1. The Do While structure is

24785 CH06 BRONSON.qrk11/10/049:05MPage 3076.2Do While Loopsthen entered and the expression is evaluated for the first time. Because the value ofcount is less than or equal to 10, the expression is True and the two statements internalto the Loop structure are executed. The first statement within the loop is a lstDisplaystatement that displays the value of count. The next statement adds 1 to the value currently stored in count, making this value equal to 2. The Do While statement now loopsback to retest the expression. Since count is still less than or equal to 10, the loopstatements are executed once again. This process continues until the value of countreaches 11. Event Procedure 6–1 illustrates these statements within the context of acomplete Button1 Click event procedure:Event Procedure 6–1Private Sub frmMain Click(ByVal sender As Object,ByVal e As System.EventArgs) Handles MyBase.ClickDim count As Integercount 1' initialize countDo While count 10lstDisplay.Items.Add(count)count count 1 ' increment countLoopEnd SubThe output that will appear on the screen in the List Box when Event Procedure 6–1is activated is:12345678910There is nothing special about the name count used in Event Procedure 6–1. Anyvalid integer variable could have been used.Note that if a text box had been used instead of a list box,the lstDisplay.Items.Add(count) statement would be replaced withtxtDisplay.AppendText(' ' & count) and the output would be:1 2 3 4 5 6 7 8 9 10 307

24785 CH06 BRONSON.qrk308 11/10/049:05MPage 308Chapter 6: Repetition StructuresBefore we consider other examples of the Do While statement, two comments concerning Event Procedure 6–1 are in order. First, the statement count 1 can bereplaced with any statement that increases the value of count. A statement such ascount count 2, for example, would cause every second integer to be displayed.Second, it is the programmer’s responsibility to ensure that count is changed in a waythat ultimately leads to a normal exit from the Do While statement. For example, if wereplace the expression count 1 with the expression count - 1, the value of countwill never exceed 10 and an infinite loop will be created. An infinite loop is a loop thatnever ends. With the above example, the computer continues to display numbers, untilyou realize that the program is not working as you expected.Now that you have some familiarity with the Do While structure, see if you canread and determine the output of Event Procedure 6–2.Event Procedure 6–2Private Sub frmMain Click(ByVal sender As Object, ByVal e AsSystem.EventArgs) Handles MyBase.ClickDim I As IntegerI 10' initialize IDo While I 1lstDisplay.Items.Add(I)I I - 1' subtract 1 from ILoopEnd SubThe assignment statement in Event Procedure 6–2 initially sets the integer variableI to 10. The Do Whilestatement then checks to see if the value of I is greater than orequal to 1. While the expression is True, the value of I is displayed by the lstDisplaystatement and the value of I is decremented by 1. When I finally reaches zero, theexpression is False and the program exits the Do While statement. Thus, the followingdisplay is obtained when Event Procedure 6–2 is activated:10987654321To illustrate the power of the Do While loop, consider the task of printing a table ofnumbers from 1 to 10 with their squares and cubes. This can be done with a simple DoWhile statement, as illustrated by Event Procedure 6–3.

24785 CH06 BRONSON.qrk11/10/049:05MPage 3096.2Do While LoopsEvent Procedure 6–3Private Sub frmMain Click(ByVal sender As Object,ByVal e As System.EventArgs) Handles MyBase.ClickDim num As Integernum 1lstDisplay.Items.Clear() ' clear the List boxlstDisplay.Items.Add("NUMBER SQUARE CUBE")Do While num 11lstDisplay.Items.Add("" & num & "& "" & (num 3))num num 1LoopEnd Sub" & (num 2)When Event Code 6–3 is activated, the following display is produced in the List box:NUMBER12345678910SQUARE e that the expression used in Event Procedure 6–3 is num 11. For the integervariable num, this expression is exactly equivalent to the expression num 10. Thechoice of which to use is entirely up to you.If we want to use Event Procedure 6–3 to produce a table of 1,000 numbers, all thatneeds to be done is to change the expression in the Do While statement from num 11to num 1001. Changing the 11 to 1001 produces a table of 1,000 lines—not bad for asimple five-line Do While structure.All the program examples illustrating the Do While statement are examples offixed-count loops because the tested condition is a counter that checks for a fixed number of repetitions. A variation on the fixed-count loop can be made, where the counteris not incremented by one each time through the loop, but by some other value. Forexample, consider the task of producing a Celsius to Fahrenheit temperature conversiontable. Assume that Fahrenheit temperatures corresponding to Celsius temperatures rang- 309

24785 CH06 BRONSON.qrk310 11/10/049:05MPage 310Chapter 6: Repetition Structuresing from 5 to 50 degrees are to be displayed in increments of five degrees. The desireddisplay can be obtained with the following series of statements:celsius 5' starting Celsius valueDo While celsius 50fahren 9.0/5.0 * celsius 32.0lstDisplay.Items.Add(celsius & " " & fahren)celsius celsius 5LoopAs before, the Do While loop consists of everything from the words Do Whilethrough the Loop statement. Prior to entering the Do While loop, we have made sure toassign a value to the counter being evaluated and there is a statement to alter the valueof celsius within the loop (in increments of 5), to ensure an exit from the Do Whileloop. Event Procedure 6–4 illustrates the use of this code within the context of a complete Form Click event.Event Procedure 6–4' A procedure to convert Celsius to FahrenheitPrivate Sub frmMain Click(ByVal sender As Object,ByVal e As System.EventArgs) Handles MyBase.ClickConst MAX CELSIUS As Integer 50Const START VAL As Integer 5Const STEP SIZE As Integer 5Dim celsius As IntegerDim fahren As ("Degrees" & "lstDisplay.Items.Add("Celsius" & "Degrees")Fahrenheit")celsius START VALDo While celsius MAX CELSIUSfahren (9.0 / 5.0) * celsius 32.0lstDisplay.Items.Add("" & celsius & "celsius celsius STEP SIZELoopEnd Sub" & fahren)

24785 CH06 BRONSON.qrk11/10/049:05MPage 3116.2Do While LoopsAfter this code is activated, the list box will hrenheit41505968778695104113122Exercises 6.21. Rewrite Event Procedure 6–1 to print the numbers 2 to 10 in increments of two. Thelist box in your program should display the following:2468102. Rewrite Event Procedure 6–4 to produce a table that starts at a Celsius value of 10and ends with a Celsius value of 60, in increments of ten degrees.3. a. Using the following code, determine the total number of items displayed. Alsodetermine the first and last numbers printed.Dim num As IntegerNum 0Do While Num 20Num Num 1lstDisplay.Items.Add(Num)Loopb. Enter and run the code from Exercise 3a as a Button Click event procedure toverify your answers to the exercise.c. How would the output be affected if the two statements within the compoundstatement were reversed; i.e., if the lstDisplay statement were made before then n 1 statement? 311

24785 CH06 BRONSON.qrk312 11/10/049:05MPage 312Chapter 6: Repetition Structures4. Write a Visual Basic program that converts gallons to liters. The program should display gallons from 10 to 20 in one-gallon increments and the corresponding literequivalents. Use the relationship of 3.785 liters to a gallon.5. Write a Visual Basic program to produce the following display within a multilinetext box.01234567896. Write a Visual Basic program to produce the following displays within a list box.a. ****b.****************************7. Write a Visual Basic program that converts feet to meters. The program should display feet from 3 to 30 in three-foot increments and the corresponding meter equivalents. Use the relationship of 3.28 feet to a meter.8. A machine purchased for 28,000 is depreciated at a rate of 4,000 a year for sevenyears. Write and run a Visual Basic program that computes and displays in a suitably sized list box a depreciation table for seven years. The table should have thefollowing ---------4000800012000160002000024000280009. An automobile travels at an average speed of 55 miles per hour for four hours. Writea Visual Basic program that displays in a list box the distance driven, in miles, thatthe car has traveled after 0.5, 1.0, 1.5 hours, and so on. until the end of the trip.

24785 CH06 BRONSON.qrk11/10/049:05MPage 3136.3Interactive Do While Loops10. An approximate conversion formula for converting temperatures from Fahrenheit toCelsius is:Celsius (Fahrenheit 30) / 2a. Using this formula, and starting with a Fahrenheit temperature of zero degrees,write a Visual Basic program that determines when the approximate equivalentCelsius temperature differs from the exact equivalent value by more than fourdegrees. (Hint: Use a Do While loop that terminates when the difference betweenapproximate and exact Celsius equivalents exceeds four degrees.)b. Using the approximate Celsius conversion formula given in Exercise 10a, write aVisual Basic program that produces a table of Fahrenheit temperatures, exact Celsius equivalent temperatures, approximate Celsius equivalent temperatures, andthe difference between the exact and approximate equivalent Celsius values. Thetable should begin at zero degrees Fahrenheit, use two-degree Fahrenheit increments, and terminate when the difference between exact and approximate valuesdiffers by more than four degrees. Use a list box to display these values.6.3Interactive Do While LoopsCombining interactive data entry with the repetition capabilities of the Do While loopproduces very adaptable and powerful programs. To understand the concept involved,consider Program 6–1, where a Do While statement is used to accept and then displayfour user-entered numbers, one at a time. Although it uses a very simple idea, the program highlights the flow of control concepts needed to produce more useful programs.Figure 6–4 shows the interface for Program 6–1.For this application the only procedure code is the Click event, which is listed inProgram 6–1’s event code.Figure 6–4Program 6–1’s Interface 313

24785 CH06 BRONSON.qrk314 11/10/049:05MPage 314Chapter 6: Repetition StructuresTable 6–1The Properties Table for Program NameTextfrmMainProgram 6–1lstDisplaybtnRun&Run ProgrambtnExitE&xitListBoxButtonButtonProgram 6–1’s Event CodePrivate Sub btnRun Click(ByVal sender As Object,ByVal e As System.EventArgs) Handles btnRun.ClickConst MAXNUMS As Integer 4Dim count As IntegerDim num As ("This Program will ask you to enter " & MAXNUMS& " numbers")count 1Do While count MAXNUMSnum Val(InputBox("Enter a number", "Input Dialog", 0))lstDisplay.Items.Add("The number entered is " & num)count count 1LoopEnd SubPrivate Sub btnExit Click(ByVal sender As Object, ByVal e AsSystem.EventArgs) Handles btnExit.ClickBeep()EndEnd SubFigure 6–5 illustrates a sample run of Program 6–1 after four numbers have beeninput. The InputBox control that is displayed by the program for the data entry isshown in Figure 6–6.Let us review the program to clearly understand how the output illustrated in Figure6–5 was produced. The first message displayed is caused by execution of the first

24785 CH06 BRONSON.qrk11/10/049:05MPage 3156.3Figure 6–5Figure 6–6Interactive Do While LoopsA Sample Run of Program 6–1The InputBox Displayed by Program 6–1lstDisplay statement. This statement is outside and before the Do While loop, so it isexecuted once before any statement within the loop.Once the Do While loop is entered, the statements within the loop are executedwhile the test condition is True. The first time through the loop, the following statementis executed:num Val(InputBox("Enter a number", "Input Dialog", "0"))The call to the InputBox function displays the InputBox shown in Figure 6–6, whichforces the computer to wait for a number to be entered at the keyboard. Once a numberis typed and the Enter key is pressed, the lstDisplay statement within the loop displayson a new line the number that was entered. The variable count is then incremented byone. This process continues until four passes through the loop have been made and thevalue of count is 5. Each pass causes the InputBox to be displayed with the messageThe number entered is. Figure 6–7 illustrates this flow of control.Program 6–1 can be modified to use the entered data rather than simply displayingit. For example, let us add the numbers entered and display the total. To do this we mustbe very careful about how we add the numbers, because the same variable, num, is used 315

24785 CH06 BRONSON.qrk316 11/10/049:05MPage 316Chapter 6: Repetition StructuresStartPrint aMessageSet CountEqual to 1Test theCondition(step 1)NoEnd(Condition is False)Yes(Condition is True)Display anInputboxDialogLoopRead aNumberPrint theNumberAdd 1to CountFigure 6–7Flow of Control Diagram for the btnRun Click Event Procedurefor each number entered. As a result, the entry of a new number in Program 6–1 automatically causes the previous number stored in num to be lost. Thus, each numberentered must be added to the total before another number is entered. The requiredsequence is:Enter a numberAdd the number to the totalHow do we add a single number to a total? A statement such as total total num is the solution. This is the accumulating statement introduced in Section 3.3. Aftereach number is entered, the accumulating statement adds the number to the total, as

24785 CH06 BRONSON.qrk11/10/049:05MPage 3176.3Interactive Do While LoopsNumberRead andStoreinto numnumThe Variable totalNewtotalOldtotaltotaltotal total numFigure 6–8Accepting and Adding a Number to a Totalillustrated in Figure 6–8. The complete flow of control required for adding the numbersis illustrated in Figure 6–9.Observe that in Figure 6–9 we have made a provision for initially setting the totalto zero before the Do While loop is entered. If we cleared the total inside the Do Whileloop, it would be set to zero each time the loop was executed and any value previouslystored would be erased. As indicated in the flow diagram shown in Figure 6–9, thestatement total total num is placed immediately after the call to the InputBoxfunction. Putting the accumulating statement at this point in the program ensures thatthe entered number is immediately added to the total.Program 6–2 incorporates the necessary modifications to Program 6–1 to total thenumbers entered. The significant difference between Program 6–1 and Program 6–2 isthe Run Program button event code. The event code for Program 6–2 is shown below.Program 6–2’s Event CodePrivate Sub btnRun Click(ByVal sender As Object,ByVal e As System.EventArgs) Handles btnRun.ClickConst MAXNUMS As Integer 4Dim count As IntegerDim num, total As ("This Program will ask you to enter " & MAXNUMS &" numbers")count 1Do While count MAXNUMSnum Val(InputBox("Enter a number", "Input Dialog", 0)) 317

24785 CH06 BRONSON.qrk318 11/10/049:05MPage 318Chapter 6: Repetition StructuresStartSet totalto ZeroIs Count 4?NoPrinttotalYesInputnumEndAdd numto totalFigure 6–9Accumulation Flow of Controltotal total numlstDisplay.Items.Add("The number entered is " & num)lstDisplay.Items.Add("The total is now " & total)count count 1LooplstDisplay.Items.Add("The final total is " & total)End SubLet us review this event code. The variable total was created to store the total ofthe numbers entered. Prior to entering the Do While statement, the value of total is setto zero. This ensures that any previous value present in the storage locations assigned tothe variable total is erased. Within the Do While loop, the statement total total num is used to add the value of the entered number into total. As each value isentered, it is added into the existing total to create a new total. Thus, totalbecomes a running subtotal of all the values entered. Only when all numbers areentered does total contain the final sum of all the numbers. After the Do While loop isfinished, the last lstDisplay statement displays the final sum.Using the same data we entered in the sample run for Program 6–1, the sample runof Program 6–2 produces the total shown in Figure 6–10.Having used an accumulating assignment statement to add the numbers entered, wecan now go further and calculate the average of the numbers. However, first we have todetermine whether we calculate the average within the Do While loop or outside of it.

24785 CH06 BRONSON.qrk11/10/049:05MPage 3196.3Interactive Do While LoopsFigure 6–10 A Sample Run of Program 6–2In the case at hand, calculating an average requires that both a final sum and thenumber of items in that sum be available. The average is then computed by dividing thefinal sum by the number of items. We must now answer the questions ”At what point inthe program is the correct sum available, and at what point is the number of itemsavailable?” In reviewing Program 6–2’s event code, we see that the correct sum neededfor calculating the average is available after the Do While loop is finished. In fact, thewhole purpose of the Do While loop is to ensure that the numbers are entered andadded correctly to produce a correct sum. With this as background, see if you can readand understand the event code used in Program 6–3.Program 6–3’s Event CodePrivate Sub btnRun Click(ByVal sender As Object,ByVal e As System.EventArgs) Handles btnRun.ClickConst MAXNUMS As Integer 4Dim count As IntegerDim num, total, average As ("This Program will ask you to enter " & MAXNUMS &" numbers")count 1Do While count MAXNUMSnum Val(InputBox("Enter a number", "Input Dialog", 0))total total numlstDisplay.Items.Add("The number entered is " & num)count count 1 319

24785 CH06 BRONSON.qrk320 11/10/049:05MPage 320Chapter 6: Repetition StructuresLoopAverage total/MAXNUMSlstDisplay.Items.Add("The average of these numbers is " & average)End SubProgram 6–3 is almost identical to Program 6–2, except for the calculation of theaverage. We have also removed the constant display of the total within and after the DoWhile loop. The loop in Program 6–3 is used to enter and add four numbers. Immediately after the loop is exited, the average is computed and displayed.A sample run of Program 6–3 is illustrated in Figure

ering the expression and the statements following it, the process used by the computer in evaluating a DoWhileloop is: 1. Test the expression. 2. If the expression is True: a. Execute all statements following the expression up to the Loopstatement. b. Go back to step 1. Else Exit the Do While statement and execute the next executable statement .