Write a function that returns n factorial
txtBox1.Text = fact(5)
1) where do i start?
2) where do i end?
3) how do i get to the next step?
Function fact(byval n as integer) As integer
dim i as integer
dim prod as integer
i = 1
prod = 1
Do
prod = prod * i
i += 1
Loop Until i = n + 1
Return prod
End Function
prod is a accumulator
off by one error
we calculated factorial using "iteration"
"iteration" is a fancy name for loops
write me a function which is the SUM of the nums from 1 to n:
Function sum(byval n as integer) As integer
dim i as integer
dim total as integer
i = 1
total = 0
Do
total = total + i
i += 1
Loop Until i > n
Return total
End Function
sr.Peek will return -1 if reached EOF (end of file)
lets say i want to read firstname, lastname, and print it out.
1) where do i start?
2) where do i end?
3) how do i get to the next step?
Dim sr As IO.StreamReader
sr = IO.File.OpenText("c:\josh\Names.txt")
Dim firstname, lastname as String
Do While sr.Peek <> -1
firstname = sr.ReadLine
lastname = sr.ReadLine
ListBox1.Items.Add("first: " & firstname, & vbTab & "last" & lastname)
Loop
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click
Dim name, phoneNum As String
Dim sr As IO.StreamReader = IO.File.OpenText("PHONE.TXT")
' pessimistic assumption
txtNumber.Text = "Name not found."
Do While sr.Peek <> -1
name = sr.ReadLine
phoneNum = sr.ReadLine
If name = txtName.Text Then
' my pessimistic assumption was proven false
txtNumber.Text = name & " " & phoneNum
' make things faster; this is optional
Exit Do
EndIf
Loop
sr.Close()
End Sub
No comments:
Post a Comment