80 likes | 169 Vues
Learn pre-test and post-test loops, false and true conditions, steps to repeat, Do While and Do Until loops, and how to use conditional loops effectively. Understand counting loops and prevent user errors with data validation techniques.
E N D
Pre-test Loops False condition Steps to repeat if False True True condition Steps to repeat if True False • Do While condition • Steps to repeat if condition is true • Loop • Do Until condition • Steps to repeat if condition is false • Loop
Post-test Loops Steps to repeat if False False condition True Steps to repeat if True True condition False • Do • Steps to repeat if condition is true • Loop While condition • Do • Steps to repeat if condition is false • Loop Until condition
When are conditional loops used? • Execute processing steps repeatedly • One or more times: post-conditional loops Do Do Loop body Loop body Loop While condition Loop Until condition • Zero or more times: pre-conditional loops Do While condition Do Until condition Loop body Loop body Loop Loop • Data Validation • Prevent user from moving on until valid value has been entered
FactNbr = CInt(txtFactNbr.Text) Factorial = 1 Multiplier = FactNbr Do While Multiplier > 0 Factorial = Factorial * Multiplier Multiplier = Multiplier - 1 Loop FactNbr = CInt(txtFactNbr.Text) Factorial = 1 Multiplier = FactNbr Do Until Multiplier <= 0 Factorial = Factorial * Multiplier Multiplier = Multiplier - 1 Loop Pre-test Loop to Find Factorial What is the minimum number of times the loop will repeat? What happens if txtFactNbr contains zero?
Dealer = 0 User = 0 Do Call PlayGame(Dealer, User) Again = InputBox(“Play again?”) Loop Until Ucase(Again) = “NO”Or Again = “” Dealer = 0 User = 0 Do Call PlayGame(Dealer, User) Again = InputBox(“Play again?”) Loop While Ucase(Again) <> “NO”And Again <> “” Post-test Loop to Play a Game What is the minimum number of times the game will be played? What happens if the user says No the first time? What happens if the user says NO? What happens if the user clicks the Cancel button ?
Counting: Pre-Test Conditional Loop Initialize counter Set Count = StartVal Count > EndVal? Check if done counting False True Steps to process repeatedly Steps to process after loop ends Count = Count + IncrVal Update counter
For/Next Loops Set Count = StartVal False Count > EndVal? True Steps to process repeatedly Steps to process after loop ends Count = Count + IncrVal Three Characteristics of a Counting Loop • Initialize counter • Increment counter in each loop iteration • Test counter before next iteration against final value ForCount = StartValToEndValStepIncrVal steps to process repeatedly NextCount steps to process after loop ends
For Next Loop Example FactNbr = CInt(txtFactNbr.Text) Factorial = 1 For Multiplier = FactNbr To 1 Step -1 Factorial = Factorial * Multiplier Next Multiplier