ME 142 Engineering Computation I Do Loops Calendar Items VBA Exam – In Class Only Units 3-6 Hard deadline for VBA 6/11 Do… Loop Statement The Do… Loop statement is used to repeatedly execute a block of statements until a specified condition is met. Conditions are tested using While and Until at either the beginning or end of the loop. Do… Loop Statement Do [While condition] [statements] Loop Do [Until condition] [statements] Loop Do [statements] Loop [While condition] Do [statements] Loop [Until condition] Do [statements] Loop Example Problem Create a factorial function using Do loops. Pass the function the number whose factorial is to be computed. After computing the factorial, the results should be displayed in the cell from which the function is called. Use the factorial function you created to compute the factorials for the integers 1 through 10. Example Problem Soln Function factorial(n) 'computes the factorial of a number Total = 1 I = 1 Do While I <= n Total = Total * I I = I + 1 Loop factorial = Total End Function Do...Loop Statement Do… Loop Statement The Do… Loop statement is used to repeatedly execute a block of statements until a specified condition is met. Conditions are tested using While and Until at either the beginning or end of the loop. Do… Loop Statement Do [While condition] [statements] Loop Do [Until condition] [statements] Loop Do [statements] Loop [While condition] Do [statements] Loop [Until condition] Do [statements] Loop Do… Loop Example x = 1 Do Cells(x,1) = x x = x + 1 Loop Until x = 5 x = 1 Do Until x =5 Cells(x,1) = x x = x + 1 Loop Do… Loop Example x = 10 Do Cells(x,1) = x x = x + 1 Loop Until x = 5 Use Ctrl+Break or Esc to stop execution of infinite loop Do… Loop Example x = 10 Do Cells(x,1) = x x = x + 1 Loop Until x> = 5 x = 10 Do Until x >=5 Cells(x,1) = x x = x + 1 Loop Example Problem Create a factorial function using Do loops. Pass the function the number whose factorial is to be computed. After computing the factorial, the results should be displayed in the cell from which the function is called. Use the factorial function you created to compute the factorials for the integers 1 through 10. Example Problem Soln Function factorial(n) 'computes the factorial of a number Total = 1 I = 1 Do While I <= n Total = Total * I I = I + 1 Loop factorial = Total End Function Review Questions Review Question What is the value of Count after the loop has finished executing: x=1 Count=0 Do Count = Count + x x = x + 1 Loop Until x = 5 A. B. C. D. E. 0 5 10 15 None of the above Homework Help ‘n Hints
© Copyright 2025 Paperzz