Tuesday, December 14, 2010

review of first practice test

first sample test
1) b
2) b
3) d
4) c
5) not necessary, but (a)
6) c
7) d
8) d
9) B
10) b
11) wasn't covered, but it is called a recursive function
12) d
13) True
14) d
15) b
16) c

Debugging:
1) a logic error. shouldv'e used ReDim Preserve
2) a logic error. you can't swap if these are passed byval. change to byref
3) syntax error. should be Next, rather than End For

Programming:
1) skip this. it won't be this high-level.
2)
For I = 1 to 10
Debug.Print(I^3)
Next

3) don't worry about it. but it would be a nested loop.

Monday, December 13, 2010

Final review

general format:

60 points of m/ch and short answer
40 points of programming (choose 4 of 5)
20 points of tracing

Tracing example:
from 6.1, q 5

focus on arrays and loops
a LITTLE on functions and subs
general knowledge from previous sections

review of second practice exam
m/ch:
1) c
2) c
3) b
4) b
5) a
6) d
2D arrays
Dim myVar(8, 8) As Double
81 slots
7.5 two dimensional arrays

7) a
8) c
9) c
10) c
11) c
12) a

Part III
1) Write a SubRoutine called NumbersInSequence that takes two integer parameters, I and J, and prints out all the numbers from I to J.
Sub NumbersInSequence(ByVal I as Integer, ByVal J as Integer)
    For K = I to J
        ListBox1.Items.Add(K)
    Next
End Sub

2)
Sub PrintUntilSeven(ByVal x() as Integer)
    For i = 0 to UBound(x)
        Debug.Print(x(i))
        If x(i) = 7 Then
            Exit For
        Endif
    Next
End Sub

Sub PrintUntilSeven(ByVal x() as Integer)
    For each t in x
        Debug.Print(t)
        If t = 7 Then
            Exit For
        Endif
    Next
End Sub


Sub PrintUntilSeven(ByVal x() as Integer)
    i = 0
    Do While x(i) <> 7
        Debug.Print(x(i))
    Loop
End Sub

Select Case letter
    Case "A"
        Debug.Print("Apple")
    Case "B"
        Debug.Print("Banana")
    Case "C"
        Debug.Print("Cookie")
    Case "D"
        Debug.Print("Deer")
End Select

Wednesday, December 8, 2010

lecture notes

sorted array
linear search - can speed up; we can end prematurely
binary search

search algorithm

why "Or n = 9"?
do not want OutOfArrayBounds exception

  Dim name2Find As String
  Dim n As Integer = -1
  name2Find = txtName.Text.ToUpper
  ' start as pessimist
  txtResult.Text = "Not found."
'  for i = 0 to 9
'    if nom(i) = name2Find then...
'  next
  For Each x in nom
    if x = name2Find Then
      txtResult.Text = "Found."
    Elseif x = name2Find Then
      exit for
    Endif
  Next

' that was my version of linear search as found in book
 Dim list1() As String = {"Al", "Carl", "Don", "Greg", "Jack"}
  Dim list2() As String = {"Bob", "Carl", "Eric", "Greg", "Herb"}

to merge, I COULD first copy contents of both, and then sort
Bad idea!

do while ia <= Ubound(a) and ib <= Ubound(B)
if A(ia) <= B(ib) Then
C(ic) = A(ia)
ia+= 1
else
C(ic) = B(ib)
ib +=1
endif
ic +=1
loop
for ia = ia to Ubound(A)
   C(ic) = A(ia)
   ic += 1
next
for ib = ib to Ubound(B)
   C(ic) = A(ib)
   ic += 1
next

Some sample exams

Topics differ from semester to semester, so there might be some questions you aren't able to answer.
One final.
Another.

Monday, December 6, 2010

last time: redim
resize an array

using a for each loop

  For Each letter in sentence.ToCharArray()
    If (letter >= "A") And (letter <= "Z") Then
      index = Asc(letter) - 65  'The ANSI value of "A"is 65
      charCount(index) += 1
    End If
  Next

how freq table might be useful
huffman trees



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

AN example of using freq tables

"If arrayOne() and arrayTwo() have been declared with the same data type, then the statement

arrayOne = arrayTwo
makes arrayOne() an exact duplicate of arrayTwo(). It will have the same size and contain the same information.

"

This comment is false. fixed in later versions of the book




so, how DO we copy an array?

two ways:
1)
Dim a(4) As Integer = {6, 8, 2, -8, 0}
Dim b() as Integer
' i want to make b an exact duplicate of a
ReDim b(UBound(a))
For I = 0 to UBound(a)
    b(i) = a(i)
Next

2)
b = a.Clone()

HW: arrays, creating and accessing
q 28, 32

Wednesday, December 1, 2010

Array
a collection

the "problem" with dealing with a collection as a bunch of separate variables.
1) unweildy
2) not easily changable to diff number of variable

Dim score(29) As Double
Dim student(29) As String

score(0) = 87
score(1) = 92

If you write programs involving large arrays
a good idea is to test using small arrays first

For i As Integer = 0 To 29
  lstBox.Items.Add(score(i))
Next


a new loop!
For Each x in score
    lstBox.Items.Add(x)
Next

we can make the array a class-level variable
and fill it in the Form_Load event
Dim teamName(3) As String = {"Packers", "Packers", "Jets", "Chiefs"}

often, we will use loops to iterate thru an array.
easier way: use for each loop
harder way: for i = 0 to whatever the upper bound is

problem: 29 is a "magic number". makes code hard to read. introduces errors. let us say i change to 60 students!

for i = 0 to UBound(scores)
    scores(i) = 90
next

for i = 0 to scores.GetUpperBound(0)
    scores(i) = 90
next


Dim scores() As Double
realize that scores, or any array, is a reference type
ReDim scores(29)
ReDim scores(n)

dynamic memory allocation

Dim scores(3) As Integer
scores(0) = 58
scores(1) = 78
scores(2) = 100
scores(3) = 98

ReDim scores(4)
' alternatively
ReDim Preserve scores(4)

will preserve the values

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

Thursday, October 28, 2010

Some useful feedback

The question:
Hello Professor ive been having trouble with # 50 on the 3.4 strings hw assignment #7
i got the first half but dont know what to do after....

Public Class Form1

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        TextBox2.Text = Int(TextBox1.Text)
        TextBox3.text = decimal?????(textbox1.Text)

    End Sub
End Class

My answer:
there are two approaches you could use for this:

strategy #1, which i think they wanted people to use:
1) use a string function, IndexOf, to find the POSITION of the period character, "."
2) use the string function, SubString, to take a slice of the string up to the period
3) use the string function, SubString, to take a slice of the string from after the period until the end.

this fits in quite well with the contents of the section, which is strings and string functions.

you could also employ strategy #2:
1) Put the entire number into a Double variable, x.
2) What you did, calling Int or CInt to get the portion before the decimal. But get it from the variable x, rather than directly from the Text property of your textbox. Assign this value to y.
3) x minus y will be just the stuff after the decimal point. assign it to a variable z.
4) then, output all these results.

of course, there are better variable names than x, y, z.

Wednesday, October 27, 2010

lecture notes

An intro to subroutines

Sub DisplayName()
Dim FirstName As String = "Josh"
Dim LastName As String = "Waxman"
Dim FullName as String
FullName = FirstName & " " & LastName
MsgBox FullName
End Sub

Private Sub Button1_Click(...) Handles ...
DisplayName
End Sub

Private Sub Button2_Click(...) Handles ...
DisplayName
End Sub


----

Private Sub Button1_Click(...) Handles btnAdd.Click
  'Display the sum of two numbers
  DisplayOpeningMessage
  DisplaySum(2, 3)
End Sub

Sub DisplayOpeningMessage()
  lstResult.Items.Clear()
  lstResult.Items.Add("This program displays a sentence")
  lstResult.Items.Add("identifying two numbers and their sum.")
  lstResult.Items.Add("")
End Sub

Sub DisplaySum(num1 As Double, num2 As Double)
  lstResult.Items.Add("The sum of " & num1 & " and " _
                      & num2 & " is " & num1 + num2 & ".")
End Sub

formal parameters
as opposed to actual parameters
we COPY the actual parameters into the formal parameters


' Get Input

' Processing

' Output Results

top-down design
stepwise refinement
stack
FILO (first in, last out)
push operation (put onto top of stack)
pop operation (taking off top of stack)
call stack
stack frames
use this to understand firstpart, secondpart example

Exams, with answers

But you may wish to use these to study:
https://docs.google.com/document/pub?id=1ukHo2jysIGz1wXkkpsk80-d9n9vQIpzNb4lMqEUscJA

http://docs.google.com/View?id=ajbqhgmq9qdz_79dcp4v5v5

Monday, October 25, 2010

lecture notes

Format of the test
_____________________

10 short answers (30 points)
6 m/choice questions (30 points)
4 Debugging (20 points)
4 Programming questions (20 points)
1 Tracing question (10 points)

Dim pos as Long
pos = TextBox1.Text

if pos = 1 Then
  txtOutcome.Text = "Win"
elseif pos = 2 Then
  txtOutcome.Text = "Place"
elseif pos = 3 Then
  txtOutcome.Text = "Show"
elseif pos = 4 or pos = 5 Then
  txtOutcome.Text = "You almost placed in the money."
else
  txtOutcome.Text = "Out of the money."
endif

syntactic sugar
 Select Case


if position >= 1 Or position <= 3 Then
instead, in a Select Case, we could say
Case 1 To 3

Assignment 9
HW: "Select Case"
10-36, even

Public Class Form1
    Sub Moo()
        MessageBox.Show("Mooooooooo!")
        MessageBox.Show("Baaaaaaaaa!")
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Moo()
        Moo()

    End Sub
End Class

Wednesday, October 20, 2010

lecture notes

Midterm: November 3rd
Chapter 1-3; Chapter 5 (meaning decision making)

ElseIf will let us accomplish three-way (or more) branching

Private Sub btnShow_Click(...) Handles btnShow.Click
  Dim costs, revenue, profit, loss As Double
  costs = CDbl (txtCosts.Text)
  revenue = CDbl (txtRev.Text)
  If costs = revenue Then
    txtResult.Text = "Break even"
  ElseIf costs < revenue Then
    profit = revenue - costs
    txtResult.Text = "Profit is " & FormatCurrency(profit)
  Else
    loss = costs - revenue
    txtResult.Text = "Loss is " & FormatCurrency(loss)
  End If
End Sub

10 gallon hat
we used And for intersection, Or for union

Chr(65) = "A"
Asc("A") = 65

Dim code As Integer
code = Asc(TextBox1.text)
If code < Asc("A") Or code > Asc("Z") Then
    txtOutput.Text = "not a capital letter"
Else
    txtOutput.Text = "a capital letter"
EndIf


Magic numbers
Asc("A") instead of 65
self-documenting

HW:
If Blocks
28-44, even


Assignment 6 is due this coming Monday

Monday, October 18, 2010

lecture notes

Decision making (ch 5)
we skip the chapter on "General Procedures" for now

Relational operators
>
<
>=
<=
=
<>

yields a Boolean type value (true or false)
Dim x as Boolean
x = 5 > 6
Button1.Text = x


x = 5 = 6
Dim y as Integer
x = y = 6
is y equal to 6? if it is, assign True to x
else assign False to x

context dependent

Comparing strings, lexicographical order
Compares it using ASCII value

gives a number to each symbol

Option Compare Text
Option Compare Binary

Dim x as String
x = "A"
' Convert to a number
' add 32 to it
' Convert back to a string
' A = 65; 65 + 32 = 97; 97 = a
' B = 66; 66 + 32 = 98; 98 = b

remember your truth tables from High School

de Morgan's laws

Do

Loop While x = 5 And (y = 7 Or z <> 2)

rewrite it using Until

Do

Loop Until Not(x = 5 And (y = 7 Or z <> 2))

Loop Until x <> 5 Or Not (y = 7 Or z <> 2)

Loop Until x <> 5 Or y <> 7 And z = 2

n = 4; answ = "Y"

(( 2 < n) And (n = 5 + 1)) Or (answ = "No")
(( True) And (False)) Or (False)
(False) Or (False)
False


Short Circuiting


Dim x as String
' maybe x = "bob"
If x.Length = 3 Then

' crashes

' but short circuiting cab be our friend
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim x As String
        If x IsNot Nothing And x.Length = 3 Then
            Button1.Text = x
        End If
    End Sub

This does NOT provide short circuiting
AndAlso OrElse

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim x As String
        If x IsNot Nothing AndAlso x.Length = 3 Then
            Button1.Text = x
        End If
    End Sub


If condition Then
  action1
  action2
  action3
Else
  action4
  action5
End If

If block

example 1 is find the Max



Private Sub btnFindMin_Click(...) Handles btnFindLarger.Click
  Dim num1, num2, min As Double
  num1 = txtFirstNum.Text
  num2 = txtSecondNum.Text
  If num1 < num2 Then
    min = num1
  Else
    min = num2
  EndIf
  txtResult.Text = "The smaller number is " & min
End Sub


example 2 is Nesting of ifs


next time, show how to remove the nesting in this example


If

Select Case

Wednesday, October 13, 2010

notes from lecture

String.Format
zone formatting
String.Format("{0, 10}{1, 3}{0,5}", "hi", 6)
TextBox1.Text = String.Format("{0, -10}{1, 3:N3}{0,5}", "hi", 0.6)

all these format function take in parameters of various types, but they ALL generate Strings

josh.txt
this will sit in a specific folder

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Text = String.Format("{0, -10}{1, 3:N3}{0,5}", "hi", 0.6)
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim sr As IO.StreamReader
        sr = IO.File.OpenText("C:\vbfiles\josh.txt")
        Dim sentence As String
        sentence = sr.ReadLine()
        Dim myNumber As Double
        myNumber = CDbl(sr.ReadLine())
        TextBox1.Text = myNumber & ";" & sentence
        sr.Close()
    End Sub
End Class

how it will work with Loops
        Do While sr.Peek() <> -1

        Loop


Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim t As String
        t = InputBox("Please enter a name", "Give a name", "Josh")
        TextBox1.Text = t
    End Sub

Wednesday, October 6, 2010

notes

Immediate window
X = 6
? X
6 {Integer}
    Integer: 6
Y = ""
? Y
"" {String}
    String: ""
? Y.Length
0 {Integer}
    Integer: 0
Y = "hello"
? Y
"hello" {String}
    String: "hello"
Y.ToUpper()
? Y
"hello" {String}
    String: "hello"
Z = Y.ToUpper()
? Z
"HELLO" {String}
    String: "HELLO"
? Y.ToUpper()
"HELLO" {String}
    String: "HELLO"
Y = "WORLD"
? Y
"WORLD" {String}
    String: "WORLD"
? Y.ToLower()
"world" {String}
    String: "world"
Y = "               Hello                         World"
The expression could not be evaluated because a build error occurred.Build Failed. For a list of build errors see the Error List. For detailed information about a build error select an item and press F1.
Y = "               Hello                         World"
? Y
"               Hello                         World" {String}
    String: "               Hello                         World"
Y = Y.Trim()
? Y
"Hello                         World" {String}
    String: "Hello                         World"


HW: String section
questions 24 - 36
questions 42 - 50
evens


book assumes option strict is on

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim result As String
        Dim t As Double = 6.75471
        result = FormatCurrency(t)
        Debug.Print(result)
        ' $6.75
    End Sub

result = FormatNumber(t, 2)

if you want to read up on Style for Format, read this article:
http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(MICROSOFT.VISUALBASIC.STRINGS.FORMAT);k(TargetFrameworkMoniker-%22.NETFRAMEWORK,VERSION%3dV4.0%22);k(DevLang-VB)&rd=true

String.Format is different from just regular Format!

Formatting Output with Zones
WWWWW
iiiii

Dim fmtStr As String = "{0, 15}{1, 10}{2, 8}"

Monday, October 4, 2010

notes

assignment 4:
due next monday, Oct 11

assignment 5:
due wednesday, Oct 13

String data type
collection of character

4 is an integer literal
"today" is a string literal

today in the example is a string variable

Primitive types vs Reference types

A Double, Integer, Boolean are primitive types

A String is a reference type, starts with Nothing (equivalent to NULL). when assign a string value to it, it points to that value on the heap.

If it is nothing and you try to use it, you will get a NullReferenceException

"" is the empty string. it is not Nothing

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim today As String
        today = ""

        With lstOutput.Items
            .Clear()
            .Add(today.Length)
            .Add("today")
            .Add(today)
        End With

    End Sub

        If today IsNot Nothing Then

        End If

What is an exception? Why should I use it?

instead of:
step 1
check for errors and fix
step 2
check for errors and fix
step 3
check for errors and fix
step 4
check for errors and fix

        Try
            step 1
            step 2
            step 3
            step 4
        Catch ex As Exception
            attempt to fix the problem
        End Try

Wednesday, September 29, 2010

notes from lecture

Hint for the Loop assignment:
look into
=
<>
keywords: Not, While, Until
Not y = 5
y <> 5

Do
Loop While I = 6

same as
Do
Loop Until Not I = 6

Do
Loop Until I <> 6

     _____
x = v  3

we started the section called Numbers
Constant as Opposed a Variable

constant value never changes

Const PI As Double = 3.14159

avoid Magic numbers
instead of * 4
we would write * ArraySize

scope:
Local variables
Global (class-level) variables

scope: where a variable has a definition
related to lifetime: how long a variable exists

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim x As Integer
        x = 6
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' this is a syntax error
        'Button1.Text = x
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

    End Sub
End Class

Public Class Form1
    ' this is a class-level
    ' or non-local, or global
    ' variable
    Dim x As Integer
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        x = 0
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' this is NOT a syntax error
        x = x + 1
        Button1.Text = x
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

    End Sub
End Class


the With construct:
  With lstResults.Items
    .Clear()
    .Add(Math.Sqrt(5 * b + 1))
    .Add(Int(a ^ b + 0.8))
    .Add(Math.Round(a / b, 3))
  End With


Alternatively:

lstResults.Items.Clear()
lstResults.Items.Add(...)
lstResults.Items.Add(...)
lstResults.Items.Add(...)


Office Hour:
Wed 3-4 Adjunct Room, across from Cs Dept Office
joshwaxman@gmail

Trace through a program

Assignment 6
"Numbers"
questions 30 - 46
60-72
even numbers only
NOT even assigned yet

Monday, September 27, 2010

Tutors and tutor schedule

is available here.

code from class

Public Class Form1
    Private Sub btnTokenize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTokenize.Click
        Dim Sentence As String
        Sentence = TextBox1.Text & " "

        'Dim startPos, spacePos, wordLen As Integer
        'Dim word As String
        'startPos = 0
        'spacePos = Sentence.IndexOf(" ", startPos)
        'wordLen = spacePos - startPos
        'word = Sentence.Substring(startPos, wordLen)
        'lstOutput.Items.Add(word)

        'startPos = spacePos + 1

        'Dim midterm1, final1 As Integer
        'Dim midterm2, final2 As Integer
        'Dim midterm3, final3 As Integer
        'Dim midterm4, final4 As Integer

        'Dim midterm(3) As Integer
        'Dim final(3) As Integer
        'Dim mid_avg As Integer

        'Dim total As Integer
        'For Each x In midterm
        '    total = total + x
        'Next
        'mid_avg = total / (UBound(midterm) + 1)

        Dim words() As String = Sentence.Split(" ")
        For Each x In words
            lstOutput.Items.Add(x)
        Next
    End Sub

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        btnTokenize.Focus()
    End Sub
End Class

Wednesday, September 22, 2010

lecture 6 notes

* For loop
* How to use debugger
* assignments
* Controls and Events

Do Loop
For Loop

syntactic sugar

Dim I as Integer = 1
Do
listBox1.Items.Add(word1)
I = I + 1
Loop While I < 16

debugger
* setting a breakpoint
breakpoint: a place in your program where execution stops

Step Over; alternatively, F10

hover over variable to see its current value.
also, Watch window
you can change variables in watch window, see value and data type of variables and expressions

For I = 1 To 15
listBox1.Items.Add(I)
Next

Assignment 5

No date announced yet for it yet, but just putting it out there so that you can start on this if you want.

Read through the chapter in the book about Controls and Events.

In the section called "Visual Basic Events" do the even exercises, # 38, 40, 42, 44

The due date for assignment 2 and 3

is moved until next Monday, rather than midnight this Wednesday night.

I'll try to give answers, either in lecture or in a post on the blog, after each due date.

Monday, September 20, 2010

lecture 5 notes

some hints for assignments 2 and 3

assignment 2:
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim degreeType As String
        degreeType = TextBox1.Text
        If degreeType = "Celsius" Then
            ' convert to other type

            ' output statement
        Else
            ' convert to other type

            ' output statement
        End If
    End Sub
End Class

assignment 3:
see the spreadsheet on Blackboard for the strategy

Loops:
Be careful about infinite loops

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim answer As String

        Do
            answer = InputBox("Pete and Repeat were on a boat. Pete fell off. Who was left?", "Important question", "Repeat")
        Loop While answer = "Repeat"
    End Sub
End Class

Assignment 4:
HW: Modify the above to count how many times the person chose "Repeat". Output this somewhere at the end.

HW: Your program requires a password to get into it. That password is "swordfish". At the start of your program, prompt for the password and keep asking them until they finally say "swordfish".

Due date: Next Wednesday

Sunday, September 19, 2010

Don't forget!

Assignment #1 (with three parts) is due Monday night! Right now, only about 1/10 of the class has handed it in. In case it is because you don't know how to submit via BlackBoard, I'll demonstrate this in class on Monday.

Assignment #2 and #3 are due on Wednesday night. I'll be discussing a bit of strategy for assignment #3 (the rain in Spain) in class Monday, but if you can have something to discuss tomorrow with your lab instructor, you can get a jump on it.

Wednesday, September 15, 2010

notes for lecture #4

If conditionals
String data type
Methods

Calculate student's grade
* Midterm grade
* Final grade
* Bribe amount

Text property of a textbox has data type of String
Automatically, implicitly, Convert from one data type to another
CDbl
Option Strict On
Val

Option Strict On
Public Class Form1

    Private Sub btnCalcGrade_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalcGrade.Click
        ' declare variables
        Dim midtermGrade, finalGrade, bribe As Double
        Dim semesterAvg As Double

        ' get input
        midtermGrade = Val(txtMidterm.Text)
        finalGrade = Val(txtFinal.Text)
        bribe = Val(txtBribe.Text)

        ' processing
        If bribe >= 50 Then
            semesterAvg = 100
        Else
            semesterAvg = (midtermGrade + finalGrade) / 2
        End If

        ' print out output
        lblAverage.Text = CStr(semesterAvg)
    End Sub
End Class

HW: convert from f to c, from c to f, based on an if and the value in a textbox

HW: Take the text "The rain in Spain falls mainly on the ground" and separate it into separate words. Print each word on a separate line in a ListBox.

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim s As String
        s = "hello"
        s = s & " " & "world"
        s = s.ToUpper()
        s = s.Replace("WORLD", "EARTH")
        Dim i As Integer
        i = s.IndexOf("EARTH")
        MessageBox.Show(i.ToString())
        s = s.Substring(6, 5)


        Button1.Text = s
    End Sub
End Class

Monday, September 13, 2010

notes for lecture #3

1) Draw your GUI
2) Write your code

A bug
A syntax error causes build errors
A logic error
Runtime errors


Hello world program
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Label1.Text = "Hello, world!"
    End Sub
End Class

Plato perfect age
Option Explicit On
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim manAge As Integer
        Dim wifeAge As Integer

        ' Get input
        manAge = TextBox1.Text

        ' Processing
        wifeAge = manAge / 2 + 7

        ' Display output
        Label3.Text = wifeAge
    End Sub
End Class

I'm naming controls (though not other variables) using "Hungarian"

camelCase

Apply a 10 point curve
Option Explicit On
Public Class Form1

    Private Sub btnCalculateCurve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculateCurve.Click
        Dim grade As Integer
        Dim curvedGrade As Integer

        ' Get input
        grade = txtGrade.Text

        ' Processing
        curvedGrade = grade + 10

        ' Display output
        lblCurvedGrade.Text = curvedGrade
    End Sub
End Class

Tuesday, September 7, 2010

Looking for a note-taker for this class

The Office of Special Services is requesting a volunteer to drop off a copy of their notes for CS80 once a week.

If you are interested, come to me, and I will give you a letter to bring to Kiely 171, so you can sign in with them and receive the note-taker guidelines. They will be pleased to give letters of recommendation for your assistance with this matter.

Some notes for lecture #2

syntax: the rules of the language. what is a verb, what is a noun, the order in which various words need to appear.

variable:
a "box" in memory with a name and a value. that value can change over time.

declaration:
Dim x as Integer

data types:
Integer, Long
String
Single, Double
Boolean

Initialization:
Dim x as Integer = 3

GUI: Graphical user interface
draw GUI, then VB code as the "codebehind"
asignment statement. use = operators. stuffs a value into a variable. does NOT establish a relationship, as if it were an equation.

Thursday, September 2, 2010

Assignment 1

For each of these, make a VB program, complete with GUI.
1) Given speed and time, calculate distance and display it.

2) Given a temperature in Celsius, convert to Fahrenheit and display it.

3) Given a title, first name and last name, calculate and display it.

I haven't announced a due date for this homework yet.
Submit it via blackboard, once you have completed it.

Tuesday, August 31, 2010

Monday, August 30, 2010

qccs80.blogspot.com

Visual Basic .NET 2008
2005, 2010 equivalent

Visual Basic for Applications

David I. Schneider
Introduction to Programming Using Visual Basic .NET 2008

http://www.amazon.com/Introduction-Programming-Microsoft-Express-Package/dp/0131565613/ref=sr_1_2?ie=UTF8&s=books&qid=1283201115&sr=8-2
0130306541

Microsoft Academic Alliance (for CS majors)
DreamSpark
Express Edition
http://www.microsoft.com/express/Downloads/#2010-Visual-Basic

2 Midterms - 15%, 15%
1 Final - 30%
HW - 10%
Semester project - 10%
Labs - 20%

joshwaxman@gmail.com


Interpreter
Compiler

Microsoft Visual Basic 2010 express edition