Practice Exercise 3
Selection and Iteration
 

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. 

Repeat this process on each resulting number until the result equals 1, displaying each value in a list box. When the process is completed display in a label the number of iterations required. 

Given an initial value of 9, example output would be: 

Initial value is 9
Next value is 28
Next value is 14
Next value is 7
Next value is 22
Next value is 11
Next value is 34
Next value is 17
Next value is 52
Next value is 26
Next value is 13
Next value is 40
Next value is 20
Next value is 10
Next value is 5
Next value is 16
Next value is 8
Next value is 4
Next value is 2
Final value 1, number of steps 19

If the input value is less than 1, print a message containing the word "Error"

Demo

Sample Solution

sln File