Additional loop presentation
Additional problems requiring loops Fibonacci sequence Euclid’s GCD algorithm Reading data from a file Changing base of numbers base b to base 10. Changing base 10 to base b
Fibonacci numbers These numbers – used in Biology (and in Computer Science!) are the sequence: 1, 1, 2, 3, 5 , 8, 13, 21, ?, ?, …. Using any two adjacent numbers in the sequence, you can generate the rest of the sequence. How?
Fibonacci numbers Fib(i+2)=Fib(i)+Fib(i+1) is the recurrence relation. Set old=1 and current=1. Build a loop for as many fibonacci values as you’d like… Display them in a listbox
Fibonacci numbers
Fibonacci numbers Should display first two Remember to declare a counter for your for loop Remember to subtract two from how many loop iterations
Fibonacci numbers: Button click code Dim i, old, cur As Integer old = 1 cur = 1 Dim n As Integer n = Integer.Parse(TextBox1.Text) 'print first two fibs ListBox1.Items.Add(cur) For i = 1 To n - 2 'need to count the first two already shown cur = cur + old old = cur - old Next
GCD…greatest common divisor
GCD discussion This application gets the greatest common divisor two ways and counts how many times it has to loop for each technique. The crude method: set your guess to be the smaller number. As long as your guess doesn’t evenly divide both numbers, keep subtracting 1 from it.
Euclid’s algorithm Get the remainder: Iterate the following: Rem=big mod small ‘note rem is reserved word If rem is zero quit, small is the gcd If not, set big to small and small to remainder, and do it again.
Button click Dim a, b, gcd, big, small As Integer Try a = Integer.Parse(TextBox1.Text) b = Integer.Parse(TextBox2.Text) If a > b Then big = a small = b Else big = b small = a End If gcd = getGCD1(big, small) Label3.Text = "gcd using crude method=" & gcd.ToString() gcd = getGCD2(big, small) Label4.Text = "gcd using Euclid=" & gcd.ToString() Label5.Text = "method looped" & loopct1.ToString() Label6.Text = "method looped" & loopct2.ToString Catch ex As Exception MessageBox.Show("must enter integers") End Try
Crude method code Function getGCD1(ByVal big, ByVal small) As Integer Dim diff As Integer = small Loopct1=0 Do While big Mod diff <> 0 Or small Mod diff <> 0 diff = diff - 1 loopct1 += 1 ‘loop1ct is a global integer Loop Return diff 'should be gcd End Function
Euclid’s method Function getGCD2(ByVal big, ByVal small) As Integer Dim remainder As Integer loopct2=0 remainder = big Mod small Do While remainder <> 0 loopct2 += 1 ‘loop2ct is a global integer big = small small = remainder Loop Return small End Function
Reading from a data file Nothing here especially requires a loop except processing a lot of data. Typically, the application needs to read numbers or names or whatever until it reaches end of file.
Notes on text files Create a data file by typing numbers (or something) into a file. I used Textpad. Wordpad and Notepad editors will also work. If you use MS Word, be sure to select save as option ascii text
Create a data file: save as txt
Save data file to project/thisproj/bin/debug
I built an ap with just a button and listbox
Button click code opens file and reads (strings) to end of file Private Sub btnread_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnread.Click Dim data As String Lstdisplay.Items.Clear() Dim sr As IO.StreamReader = IO.File.OpenText("data.txt") Do While sr.Peek <> -1 data = sr.ReadLine() Lstdisplay.Items.Add(data) Loop sr.Close() End Sub
Running form just displays the data
Improvements Sum the values in the data file Search for a name or number in the data file Allow user to enter a file name
Base changer In base b, only digits 0…b-1 may appear Remarks on Radix positional notation A number in any base consists of legal digits, each represents how many there are of the base to some power
Base changer So: 12345 base 10 represents 1*10000+2*1000+3*100 and so on 101111 in base 2 represents 1*1+1*2+1*4+1*8+0*16+1*32=47
Base changer Convert to base 10: 33221 in base 4 10101 in base 2
Base changer Putting together an ap that converts numbers from base b to base 10: Get input from user, a String (number in base b) and an integer (the original base). Set a sum value to 0 LOOP: Use the substring function to peel off digits from the string and multiply by the appropriate power of the base and add to the running total
Numbers in base 10 are unchanged
But if base was 5: 2*25+3*5+4=69
Handles any base up to & including 10
Buttonclick code Dim i, j, ans, base As Integer Dim x, y As String ans = 0 ' will hold answer base = Integer.Parse(Txtbase.Text) x = Txtnum.Text For i = 0 To x.Length - 1 y = x.Substring(i, 1) ' this short string 1 character long j = Integer.Parse(y) ans = ans * base + y Next Lblans.Text = ans.ToString
To handle larger bases Need a function to return proper character value
Going the other way: base 10 to base b
Use mod and div (\) to build a string representation of the answer Dim num, base As Integer Try num = Integer.Parse(txtnum.Text) base = Integer.Parse(txtbase.Text) Dim ans As String = "" Do While num <> 0 ans = ans & num Mod base num = num \ base Loop lblans.Text = "answer is" & ans Catch ex As Exception End Try
Still to do Handle bases bigger than 10 – I haven’t done that. If the remainder is larger than 9, you need to use alpha representation for the digits ‘A’ is 10, and so on.