Monday, November 29, 2010

lecture notes

For Loops
are an example of syntactic sugar

1) how do i start?
2) how do i end?
3) step

For i = 1 to 10
    ListBox1.Items.Add(i*i)
Next

When should I use a For loop?
1) you want to do something a fixed number of times
(In this instance, i don't *use* the variable i inside the loop at all)
2) when you want to generate a series of numbers

ex 1:

Dim year as Integer
pop = 300000
For year = 2006 To 2010
    LstTable.Items.Add(year & "  " & pop)
    pop = pop + pop * 0.03
Next


Alternatively:

pop = 300000
For year as integer = 2006 To 2010
    LstTable.Items.Add(year & "  " & pop)
    pop = pop + pop * 0.03
Next


if I have:
x operator= 6

x = x operator 6

for loops, 30-40 even

row = ""
for i = 1 to 10
    row = row & "*"
next
for i = 1 to 10
    listbox1.items.add(row)
next


for i = 1 to 10
    row = ""
    for i = 1 to 10
        row = row & "*"
    next
    listbox1.items.add(row)
next

Wednesday, November 24, 2010

lecture notes

Nesting: putting one loop in another
Loop thru values of X in (0 thru 2)
    Loop thru values of y in (0 thru 3)
        Print (x, y)
    End Loop
End Loop

LISTS.TXT
    ' the names of other phonebook files
    CLIENTS.TXT
    FRIENDS.TXT
    KINFOLK.TXT


Loop thru filenames in the LISTS.TXT file
    Open the current filename
    Loop thru the entries in the current file
        see if name occurs in current file
    End Loop
End Loop

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click
  Dim foundFlag As Boolean
  Dim fileName As String
  Dim name As String = ""
  Dim phoneNum As String = ""
  Dim sr1 As IO.StreamReader = IO.File.OpenText ("LISTS.TXT")

  txtNumber.Text = "Name not found."
  ' by the way, i use a goto to break out multiple
  ' levels when we find the actual word
  Do While sr1.Peek <> -1
    fileName = sr1.ReadLine
    Dim sr2 As IO.StreamReader = IO.File.OpenText(fileName)
    Do While sr2.Peek <> -1
      name = sr2.ReadLine
      phoneNum = sr2.ReadLine
      If name = txtName.Text Then
    txtNumber.Text = name & "     " & phoneNum
        Goto Here
      Endif
    Loop
  Loop
  sr1.Close()
Here:

End Sub

HW:
Processing Lists of Data with Do Loops
question 20-24, even

Write a program to find and display the largest of a collection of positive numbers contained in a text file. (Test the program with the collection of numbers 89, 77, 95, and 86.)

Dim max as Integer
max = 0

Do While sr.Peek <> -1
    current = sr.ReadLine
    ' is my optimistic assumption wrong?
    If current > max Then
        max = current
    EndIf
Loop

Debug.Print("The max value is: " & max)

Monday, November 22, 2010

lecture

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

Wednesday, November 17, 2010

lecture notes

q 23

c = -40

f = (9/5)*c + 32
ListBox1.Items.Add("c:" & c & vbTab & "f:" & f)


the actual code:
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        c = -40
        Do
            f = (9 / 5) * c + 32
            ListBox1.Items.Add("c:" & c & vbTab & "f:" & f)
            c += 5
        Loop Until c > 40
    End Sub
End Class

q 25:

1) where do we start (initialization)?
2) where do we end? (terminating condition)
3) how do we get there? each step (increment)

'Dim pop as Double
'pop = 6.5

Dim pop as Long
pop = 6.5 * 10 ^ 9
Const percent = 1.2 / 100
Dim year as Integer = 2006

Do
 ListBox1.Items.Add("year:" & year & vbTab & "pop:" & pop)
 year += 1
 pop = pop + pop * percent
Loop Until pop >= 10 * 10^9

ListBox1.Items.Add("year:" & year & vbTab & "pop:" & pop)

Different roles for variables when it comes to loops
1) loop control variable
2) counter
3) accumulator
4) flag

q 27:
Write a program to display all the numbers between 1 and 100 that are part of the Fibonacci sequence. The Fibonacci sequence begins 1, 1, 2, 3, 5, 8,..., where each new number in the sequence is found by adding the previous two numbers in the sequence.

prev = 1
cur = 1

Do
 ListBox1.Items.Add("num:" & vbTab & cur)
 temp = prev
 prev = cur
 cur = temp + cur
Loop Until cur > 100


' now, using mathematic notation
Fn = 1
Fn_1 = 0

Do
 ListBox1.Items.Add("num:" & vbTab & Fn)
 Fn_2 = Fn_1
 Fn_1 = Fn
 Fn = Fn_1 + Fn_2
Loop Until Fn > 100

using iteration to calculate Fibonacci

HW: Do Loops, q 24-36, evens

Monday, November 15, 2010

lecture

Goto statement
Goto label

jmp instruction in assembler
cmp, followed by a jnz instruction

for loop, while loop, examples of syntactic sugar


in BASIC, my first program:
10 Print "Hello"
20 Goto 10

in Visual Basic:
here:
    Debug.Print("Hello")
    Goto here
    Debug.Print("Goodbye")

an infinite loop never ends
how would we do this without Gotos?

Do
    Debug.Print("Hello")
Loop

    I = 0
here:
    Debug.Print("Hello" & I)
    I = I + 1
    If i < 3 Then
        Goto here
    EndIf

I = 0
Do
    Debug.Print("Hello" & I)
    I = I + 1
Loop While i < 3

' this is called a post-test

what if we want a pretest?
I = 0
Do While i < 3
    Debug.Print("Hello" & I)
    I = I + 1
Loop

I = 0
goto there
here:
    Debug.Print("Hello" & I)
    I = I + 1
there:
    If i < 3 Then
        Goto here
    EndIf

So why don't we use Gotos?!
1) simpler
2) higher
3) more controlled
4) spaghetti code

http://en.wikipedia.org/wiki/Spaghetti_code

10 i = 0
20 i = i + 1
30 PRINT i; " squared = "; i * i
40 IF i >= 10 THEN GOTO 60
50 GOTO 20
60 PRINT "Program Completed."
70 END

FOR i = 1 TO 10
    PRINT i; " squared = "; i * i
NEXT i
PRINT "Program Completed."
END

a move to eliminate gotos
Goto statement considered harmful

http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html

Goto statement considered harmful considered harmful

rules for using goto:
1) it should always be fairly close
2) only goto above you, never below you



  Dim response As Integer, quotation As String = ""

  Do
    response = CInt(InputBox("Enter a number from 1 to 3."))
  Loop Until response >= 1 And response <= 3

Wednesday, November 10, 2010

functions - return a value, which we can use


x = Int(2.6)
y = Int(7.6) + 6

Public Class Form1
    Function Foo() As String
        Dim x As Integer
        x = 7
        Return "Hello"
    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim s As String
        s = Foo()
        Button1.Text = s
    End Sub
End Class


y = f(x)

money today is worth more than money a year from now
FV = PV * (1+RATE)^NPER


but can compount mult times per year. need divide by freq

HW: Chapter 4 Programming Projects
 1-4

Monday, November 8, 2010

notes from lecture

static, local, class-level variables
lifetime vs. scope
final is wendesday, 12/15, from 4-6 PM in our regular room

Midterm answers

Midterm for class 1
Midterm for class 2

Wednesday, November 3, 2010

lecture notes

Subs, part II
ByVal
ByRef

actual vs. formal parameters

changes to ByVal parameters do not "stick"
changes to ByRef parameters do "stick"

a reference is an arrow we can follow to the variable
a reference is an alias to the variable; an alias is another name for the variable

passing them in order
keyword parameters

we got up to end of example 2

Another bit of feedback

regarding one of the practice midterms:

The question:
On the tracing ex. Y’s final value is 4. It therefore should be that the statement should be the else clause because  <>4 or <>5 is false.
Is that correct bec. On the exam’s answer you wrote that the answer is it is there, which is the then statement.

My Answer:
https://docs.google.com/document/pub?id=1ukHo2jysIGz1wXkkpsk80-d9n9vQIpzNb4lMqEUscJA&pli=1

this is a very tricky question which, if i recall correctly, nobody got right.

Indeed, Y's final value is 4.
Consider: If y <> 4 Or y <> 5 Then

y <> 4 evaluates to False
y <> 5 evaluates to True, because 4 is not 5
So, False Or True is True
This becomes If True Then

So it will go into the If clause rather than the Else clause.

As I noted, this is a very tricky question, but if you copy the code into Visual Basic, you will see that this is what happens. People get it wrong because of the disconnect between human speech, such as English, and programming languages. You read it as "if it not 4 or five" but that is not what it means.

Monday, November 1, 2010

lecture notes

HW:
Sub Procedures, Part I
question 6, 8, 36, 38, 48-54 even
look at answer to one of the odd questions to get a sense of how to do it.

answer to q 38 for If blocks
If year mod 400 = 0 Then
'leap
ElseIf year mod 100 = 0 Then
' not leap
ElseIf year mod 4 = 0 Then
'leap
Else
' not leap
Endif


' leap year
If year mod 400 = 0 Or (year mod 100 <> 0 And year mod 4 = 0) Then
MsgBox("Leap year!")
MessageBox.Show("Leap year!")
Else
MsgBox("Not a leap year!")
Endif

Write a program that allows the user to use a button to toggle the color of the text in a text box between black and red.
' this will NOT work
If textbox1.ForeColor = Color.Black Then
textbox1.ForeColor = Color.Red
Endif
If textbox1.ForeColor = Color.Red Then
textbox1.ForeColor = Color.Black
Endif

' this WILL work
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If TextBox1.ForeColor = Color.Black Then
            TextBox1.ForeColor = Color.Red
        Else ' If TextBox1.ForeColor = Color.Red Then
            TextBox1.ForeColor = Color.Black
        End If
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox1.ForeColor = Color.Black
    End Sub


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Visible = Not TextBox1.Visible
    End Sub

biggest:
Public Class Form1
    Dim biggest As Integer
    Dim secondBiggest As Integer

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim theNum As Integer
        theNum = Val(TextBox1.Text)

        If theNum >= biggest Then
            ' update my maxes
            secondBiggest = biggest
            biggest = theNum
        ElseIf theNum > secondBiggest Then
            secondBiggest = theNum
        End If
      
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox1.ForeColor = Color.Black
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Button2.Text = "Biggest: " & biggest & vbTab & "SecondBiggest: " & secondBiggest
    End Sub
End Class