Repetition Structures There are three main structures used in programming: sequential, decision and repetition structures. Sequential structures follow one line of code after another. Decision structures follow code based on conditions. Programmers use the repetition structure (also called looping or iteration structure) to instruct the computer to repeat one or more instructions, either a specified number of times OR until a condition (known as the loop condition) is met. Within the repetition structures there are three forms: For Next, Do While and Do Until. Although any of the three forms of repetition structure can be used to repeat instructions a specified number of times, the For Next loop is usually used in these situations as it requires less coding. The FOR NEXT Loop Syntax: The For Next loop takes the form: For counter = startvalue To endvalue Step stepvalue statements Next counter The For Next loop (or automatic counter loop) repeats one or more statements a specified number of times. notice that the syntax begins with the FOR statement and ends with the Next statement counter is the name of a numeric variable that keeps track of the number of times the loop is processed the startvalue, endvalue and stepvalue items control how many times to process the loop startvalue tells the loop where to begin stopvalue tells the loop where to stop stepvalue determines how much to add to (or subtract from) the counter each time loop is processed if Step and stepvalue are omitted, then VB uses a value of +1 The For Next loop performs the following 3 tasks 1. The loop initializes the counter to the startvalue. This is done just once at the beginning. 2. If stepvalue is positive, the loop checks to see if counter is greater than endvalue (if stepvalue negative then loop checks if counter less than endvalue). If it is, the loop stops, if not, then the loop statements are processed.
3. The loop adds the stepvalue onto the counter and repeats steps 1-2 until counter is greater than (or less than if stepvalue is negative) endvalue. In the example below the variable intcount is the counter, the startvalue is 1, the endvalue is 20 and the stepvalue is +1 For intcount = 1 to 20 txtcounter.text = intcount Next intcount Start Declare intcount variable for counter The For Next loop is represented in the flowchart by a hexagon. Four values are recorded inside the hexagon: the name of the counter, the startvalue, endvalue and stepvalue. Note that the endvalue is preceded by a > (greater than sign) intcount 1 >20 1 display intcount Stop The loop initializes the counter (intcount) to the startvalue 1. Loop then compares the current value of the counter to the end value. While every value of counter is less than 20, the loop continues and prints value of intcount. Finally the loop increments the counter by the step value 1, then the program flow loops back
Counters and Accumulators Counters are often required in algorithms to keep track of the number of times a user does something, such as the number of times a mark is entered in order to calculate an average. Counters are variables that are incremented by a constant value. The statement for incrementing or updating a counter takes the form: counter = counter + constant In an assignment statement, the expression on the right side of the equals sign is evaluated first and is then assigned to the variable on the left hand side. This makes it possible to use the current value of counter in the expression itself. Example intcounter = intcounter + 1 The above increments counter by + 1 each time statement executed A counter should be initialized when it is declared as a static variable, thus it will only be initialized once. Accumulators are useful for keeping a running total or sum of values, such as the total dollar value of items purchased. Accumulators are incremented by changing amounts. The statement for incrementing or updating an accumulator takes the form: accumulator= accumulator + value Example: sngtotal = sngtotal + sngitemcost The above adds value of sngitemcost to sngtotal each time the statement is executed
Lab #9 ~ Factorials The factorial of a number is the product of all the positive integers from 1 to the number. For example, 3 factorial, written as 3! = 3*2*1 = 6. Create an application using a For Next loop to compute the factorial of a number. Interface Form frmfactorial Factorial Calculator Label lblenternumber Enter A Number Text Box txtnumber Button cmdcalculate Calculate Factorial Label Label lblfactorialmessage lblfactorial Variables o Number o Factorial o Counter - integer entered by the user - integer result -integer to keep track of loop counter to number. Flowchart Start Get the number from the user. intcounter 1 >Number 1 Factorial = factorial *intcounter Display factorial End What does the pseudocode look like?
Code: Factorial Calculator written by your computer teacher, this day updated by you, today Public Class frmfactorial ***************************** Calculates the factorial based on the number enetered by the user. post: The factorial is shown in a label. Private Sub cmdcalculatefactorial_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles cmdcalculatefactorial.click variables declared - only used within this procedure Dim intnumber As Integer Dim intfactorial As Integer Dim intcounter As Integer intnumber = Val(txtNumber.Text) get number from user intfactorial = 1 factorial must be initialized to one (otherwise multiply by zero) For intcounter = 1 To intnumber intfactorial = intfactorial * intcounter Next intcounter lblmessage.text = "Factorial is: " lblfactorialresult.text = intfactorial ***************************** Resets the labels for the answer so that when the user enters a new number, the result is cleared. post: The labels for the answers are cleared. Private Sub txtnumber_textchanged(byval sender As System.Object, ByVal e As System.EventArgs) Handles txtnumber.textchanged lblmessage.text = Nothing lblfactorialresult = Nothing End Class Save often as you work through this lab and test that your program works.
The Do While and the Do Until Loops When it is not known exactly how many times the loop will be required to repeat a set of instructions, then a Do While loop or Do until loop must be used. Both loops require a condition which often contains variables, mathematical, relational or logical operators. Just like the condition in an If Then Else statement, the loop condition must also evaluate to True or false. The condition determines if the loops statements or will be executed. Syntax: The Do While loop takes the form: Do While condition statements Loop Syntax: The Do Until loop takes the form: Do statements Loop until condition The Do While loop repeats one or more statements while a condition is true. The Do While loop begins with the Do While statement and ends with the Loop statement. The condition is located at the start of the loop and loop statements are only executed if the condition evaluates to True. If the condition evaluates to False, then the statements are not executed. Programmers call the Do While loop a pre-test loop as the loop tests the condition before executing any statements in the loop. Depending on how the condition evaluates, the statements in a Do While loop may not be executed at all. The Do Until loop repeats one or more statements until a condition becomes true. The Do Until loop begins with the Do statement and ends with the Loop Until statement. The condition is located at the end of the loop and loop statements are only executed if the condition evaluates to False. If the condition evaluates to True, then the statements are not executed again. Programmers call the Do Until loop a post-test loop as the loop tests the condition only after executing the statements in the loop. The statements then in a Do Until loop are always executed at least once.
Examples: Dim intcount as integer intcount = 1 Do While intcount <= 3 Print intcount intcount = intcount + 1 Loop Dim intcount as integer intcount = 1 Do Print intcount intcount = intcount + 1 Loop Until intcount > 3 Lab # 10 ~ Average Scores The average of a set of scores is calculated by dividing the sum of the scores by the number of scores. Use one text box to enable user to enter as many scores as they would like, until a -1 is entered. The text box should be disabled until the user clicks the Enter Scores button. The form should look as follows, with the following control names and text: Form frmaveragescore Average Score Calculator labels lblinformation Select Enter Scores lblnumberscores lblaveragemessage lblaverage lblsumofscores # of Scores The Average is: Average Sum of Scores Buttons cmdenterscores Enter Scores cmdaveragescore Average Score Variables Number of scores integer, declared globally Sum of scores integer to represent the total of the scores entered tempscore string that represents the entered value new score to represent the value of the temp score FLAG constant to represent -1 (entered to indicate the end of the scores
Pseudocode: cmdenterscores_click Prompt user to enter score Do while entered score is not equal to Nothing and the score is not equal to -1 Increment counter by 1 Score = value of entered score Add score to sum of scores Prompt user for next score Loop Show sum of scores Show number of scores that have been entered cmdaveragescores If the number of scores = 0, then Average = 0 Else Average = sum of scores entered / number of scored entered Display the average in the label. End if
Code: Average Score Calculator written by your computer teacher, this day updated by you, today Users enter scores in Input Boxes and an entry of -1 terminates entering scores. Public Class frmaveragescores global variables Dim intnumberofscores As Integer Dim intsumofscores As Integer ******************************** Gets the scores from the user in the form of input boxes. -1 is entered to indicate the end of entered scores. post: sum of the scores and the number of scores entered Private Sub cmdenterscores_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles cmdenterscores.click Const FLAG As Integer = -1 Dim strtempscore As String Dim intnewscore As Integer lblaverage.text = Nothing lblnumberofscores.text = 0 get scores strtempscore = InputBox("Enter a score [ -1 to stop]", "Scores") Do While strtempscore <> Nothing And Val(strTempScore) <> -1 intnewscore = Val(strTempScore) intnumberofscores = intnumberofscores + 1 intsumofscores = intsumofscores + intnewscore strtempscore = InputBox("Enter a score [ -1 to stop]", "Scores") Loop lblsumofscores.text = intsumofscores lblnumberofscores.text = intnumberofscores ******************************** Calculates the average of entered scores pre: the number of scores and the sum of the scores entered post: the average is displayed for the user Private Sub cmdaveragescore_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles cmdaveragescore.click Dim sngaverage As Single
If intnumberofscores > 0 Then sngaverage = intsumofscores / intnumberofscores lblaverage.text = sngaverage Else lblaverage.text = 0 End If End Class Save often as you work through this lab and test that your program works.
Lab #11 ~ Fibonacci Sequence A Fibonacci sequence is a sequence of numbers that is generated from 2 starting values called seeds. The 2 seeds are the first 2 numbers in the sequence. The seeds are then added together to generate the third number in the sequence. Each additional number is created by adding the 2 previous numbers. For example if the 2 seeds are 1 and 1, then the sequence is 1, 1, 2, 3, 5, 8 while seeds of 3 and 6 will generate 3, 6, 9, 15, 24 Create an application that gets 2 seed values from the user that will generate a Fibonacci sequence of 50 numbers. To display such a long series of numbers you should use a textbox rather than a label. Use the Textbox properties below to display the sequence. Dock setting dock to bottom sizes textbox so bottom right and left borders are anchored to the form ReadOnly set to True when textbox used to display info, user cannot type into it Multiline set to true to display multiple lines WordWrap set to true to wrap lines of text Scrollbars set to vertical to allow vertical scrolling The Form should look as follows with the property changes listed: Form frmfibonacci Fibonacci Sequence Builder Labels lblfirstnumber First Number Text Boxes txtfirstnumber txtsecondnumber lblsecondnumber lblinformation lblfibonaccisequence Second Number Enter two numbers Fibonacci Sequence txtsequence Button cmdgenerate Generate Sequence
One possible solution is: Code: Fibonacci Sequence Calculator written by your computer teacher, this day updated by you, today Users enters two numbers and a Fibonacci like sequence is generated from these numbers and displayed for the user. Public Class frmfibonacci Generates the list of numbers based on two entered post: Fibonacci like sequence displayed if two numbers are entered. Private Sub cmdgenerate_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles cmdgenerate.click variables Dim lngfirstnumber As Long Long used otherwise overflow error Dim lngsecondnumber As Long Dim intcounter As Integer Dim lngnextnumber As Long End If End Class If txtfirstnumber.text = Nothing Or txtsecondnumber.text = Nothing Then MessageBox.Show("You must enter two numbers", "Two Numbers Required") Else lngfirstnumber = Val(txtFirstNumber.Text) lngsecondnumber = Val(txtSecondNumber.Text) txtsequence.text = lngfirstnumber & ", " & lngsecondnumber loop to generate next 48 numbers in sequence For intcounter = 3 To 50 lngnextnumber = lngfirstnumber + lngsecondnumber lngfirstnumber = lngsecondnumber lngsecondnumber = lngnextnumber txtsequence.text = txtsequence.text & ", " & lngnextnumber Next intcounter Can you think of another? Infinite Loops Logic errors can lead to infinite loops. If the program stops responding (cannot click on anything), right-clicking on the Windows Taskbar and selecting Close from the menu, and then select Close the Program to end the application.