Practice Exercise 3
Selection and Iteration

' Student Name
 ' CIS 220
 ' Practice Problem 3
 ' Due Date
 '
 ' Read a positive integer value from a text field, and perform the
 ' following calculations:
 ' * If the number is even, halve it.
 ' * If the number is odd, multiply by 3 and add 1.
 ' This process repeats on each resulting number until the result
 ' equals 1, displaying each value in a text box. When the process
 ' is completed it displays the number of iterations required.
 '----------------------------------------------------------------------

 Private Sub cmdProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdProcess.Click
     ' Declare local variables
     Dim input As Double = 0
     Dim output As String = ""
     Dim stepsCtr As Integer = 0
     'INPUT SECTION
     '--------------------
     input = Val(txtInput.Text) ' By adding Val it enables the error checking to work even if no value is entered.
     '--------------------
     'PROCESSING SECTION
     '====================================
     If input < 2 Then ' Some Error Checking
         MsgBox("Please enter a numeric value greater than 1.", MsgBoxStyle.Critical, "ERROR!")
         txtInput.Focus() ' sets focus to input box
         txtInput.SelectionStart = 0 ' Set cursor to beginning of box
         txtInput.SelectionLength = Len(txtInput.Text) ' Highlight text
     Else ' Unless error checking has passed will not enter this section

         output &= "Initial number is " & input & vbCrLf ' Displays original value
         Do While input <> 1 ' As long as value is not 1 it will stay in the loop
             If (input Mod 2) > 0 Then ' If evaluates to true number is odd
                 input = input * 3 + 1
             Else ' Numper is even
                 input = input / 2
             End If
             ' Add the current value to output string
             If input = 1 Then
                 output &= "Final value " & input
             Else
                 output &= "Next value is " & input & vbCrLf
             End If
             stepsCtr += 1
         Loop
         output &= ", Number of steps " & stepsCtr
         '===================================
         'OUTPUT SECTION
         '----------------------
         txtOutput.Text = output
         '----------------------
    End If
End Sub