0% found this document useful (0 votes)
82 views

Lecture 7 Code Samples Eric J. Schwabe IT 236 Spring 2008

This document contains code samples from several lecture examples demonstrating various programming concepts like functions, arrays, and searching algorithms. It includes code to round numbers up to the nearest integer using a ceiling function, count letters in a string, calculate pizza price per square inch from diameter and total price, display items and prices from arrays, and perform linear and binary searches on arrays. The samples are intended to illustrate concepts taught in an IT programming course.

Uploaded by

crutili
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

Lecture 7 Code Samples Eric J. Schwabe IT 236 Spring 2008

This document contains code samples from several lecture examples demonstrating various programming concepts like functions, arrays, and searching algorithms. It includes code to round numbers up to the nearest integer using a ceiling function, count letters in a string, calculate pizza price per square inch from diameter and total price, display items and prices from arrays, and perform linear and binary searches on arrays. The samples are intended to illustrate concepts taught in an IT programming course.

Uploaded by

crutili
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 12

Lecture 7 Code Samples

Eric J. Schwabe
IT 236 Spring 2008

=====

' CeilingFunction.sln
' Eric J. Schwabe
' IT 236 Spring 2008
' Demonstrates a user-defined function to round numbers up

Option Strict On

Public Class Form1


Inherits System.Windows.Forms.Form

' When the button is clicked, the value in the upper text box
' is stored in a variable, and the Ceiling function is called
' to round it up to the next integer. The result is displayed
' in the lower text box.

Private Sub roundButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles roundButton.Click

Dim oldNumber As Double = Double.Parse(inTextBox.Text)


Dim newNumber As Integer

newNumber = Ceiling(oldNumber)

outTextBox.Text = newNumber.ToString()

End Sub

' This user-defined function rounds the input value up to the


' nearest integer
' (Note that the Int function returns a Double, not an Integer,
' so we convert it with CInt...)

Private Function Ceiling(ByVal x As Double) As Integer

' MessageBox.Show("x is " & x.ToString(), "Argument Value")

Dim result As Integer


result = CInt(-Int(-x))

' MessageBox.Show("result is " & result.ToString(), "Return Value")

Return result

End Function

End Class

=====
=====

' CountLetters.sln
' Eric J. Schwabe
' IT 236 Spring 2008
' Sample for Lecture 6 in-class example

Option Strict On

Public Class Form1

' When the button is clicked, counts the number of each vowel and the total number of
' consonants in an input string, and reports these values. This process is repeated
' until the user enters an empty string.

Private Sub goButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles goButton.Click

Dim input, letter As String


Dim i, n As Integer
Dim aCount, eCount, iCount, oCount, uCount, consonantCount As Integer

Do
aCount = 0
eCount = 0
iCount = 0
oCount = 0
uCount = 0
consonantCount = 0

input = InputBox("Enter input string (empty string to quit):")


n = input.Length

For i = 0 To n - 1
letter = input.Substring(i, 1)
letter = letter.ToUpper
' outputListBox.Items.Add(i.ToString() & " : " & letter)
Select Case letter
Case "A"
aCount = aCount + 1
Case "E"
eCount = eCount + 1
Case "I"
iCount = iCount + 1
Case "O"
oCount = oCount + 1
Case "U"
uCount = uCount + 1
Case Else
If isConsonant(letter) Then
consonantCount = consonantCount + 1
End If
End Select
Next

If input <> "" Then


outputListBox.Items.Add(input)
outputListBox.Items.Add(aCount & ":" & eCount & ":" & iCount & ":" & oCount &
_
":" & uCount & " ... " & consonantCount)
outputListBox.Items.Add("==========")
End If

Loop Until input = ""

End Sub
' This function returns a true if the input argument is an upper case consonant,
' and false otherwise

Private Function isConsonant(ByVal character As String) As Boolean

MessageBox.Show("character is " & character, "Input Argument")

Dim result As Boolean

If "BCDFGHJKLMNPQRSTVWXYZ".IndexOf(character) <> -1 Then


result = True
Else
result = False
End If

MessageBox.Show("result is " & result, "Return Value")

Return result

End Function

End Class

=====
=====

' PizzaPrice.sln
' Eric J. Schwabe
' IT 236 Spring 2008
' Demonstrates a user-defined function

Option Strict On

Public Class Form1


Inherits System.Windows.Forms.Form

' When the button is clicked, read the pizza diameter and price
' from the two text boxes, and call the PricePerSquareInch function
' to compute the unit cost per square inch

Private Sub computebutton_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles computeButton.Click

Dim diameter As Integer = Integer.Parse(diameterTextBox.Text)


Dim price As Double = Double.Parse(priceTextBox.Text)
Dim unitCost As Double

unitCost = PricePerSquareInch(diameter, price)

Dim output As String = diameter & "'' costs " & _


price.ToString("C") & "... " & _
unitCost.ToString("N2") & _
" cents per square inch"

outputListBox.Items.Add(output)

End Sub

' Given a diameter d and price p (given in dollars), computes the price
' per square inch (returned in cents)

Function PricePerSquareInch(ByVal d As Integer, ByVal p As Double) As Double

' MessageBox.Show("d is " & d.ToString() & " , p is " & p.ToString, "Input
Arguments")

Dim area, cost As Double


area = 3.14159 * (d / 2) ^ 2
cost = (p * 100) / area

' MessageBox.Show("cost is " & cost, "Return Value")

Return cost

End Function

End Class

=====
=====

' LandsEnd.sln
' Eric J. Schwabe
' IT 236 Winter 2008
' Simple demonstration of arrays of strings and numbers

Option Strict On

Public Class Form1


Inherits System.Windows.Forms.Form

' Declarations of two form-level arrays

Dim itemName(5) As String


Dim itemPrice(5) As Double

' Initializes the two arrays when the form loads

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles


MyBase.Load

itemName(0) = "Gum Shoes"


itemName(1) = "SnugFoot Sandals"
itemName(2) = "T-Shirt"
itemName(3) = "Maine Handbag"
itemName(4) = "Nightshirt"

itemPrice(0) = 39.0
itemPrice(1) = 21.0
itemPrice(2) = 7.75
itemPrice(3) = 33.0
itemPrice(4) = 26.0

End Sub

' Displays all item names and prices when the button is clicked

Private Sub goButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles


goButton.Click

Dim output As String

' the obvious way to do it...

output = itemName(0) + ": " + itemPrice(0).ToString("C")


outputListBox.Items.Add(output)
output = itemName(1) + ": " + itemPrice(1).ToString("C")
outputListBox.Items.Add(output)
output = itemName(2) + ": " + itemPrice(2).ToString("C")
outputListBox.Items.Add(output)
output = itemName(3) + ": " + itemPrice(3).ToString("C")
outputListBox.Items.Add(output)
output = itemName(4) + ": " + itemPrice(4).ToString("C")
outputListBox.Items.Add(output)

' a smarter way to do it...

'Dim i As Integer
'For i = 0 To 4
' output = itemName(i) + ": " + itemPrice(i).ToString("C")
' outputListBox.Items.Add(output)
' Next

' ... or let the user decide which elements to display...

'Dim i As Integer
'Do
' i = Integer.Parse(InputBox("Enter an index:", "ARRAY INDEX PROMPT"))'
'
' doing bounds checking...
' If (i >= 0) And (i <= 4) Then
'output = itemName(i) + ": " + itemPrice(i).ToString("C")
'outputListBox.Items.Add(output)
'End If
'
' Loop Until (i = -1)

' ... finally, traversing the entire array (names only) with a For Each loop...
' ... note that in this case, we do not know the index of the element...

'itemName(5) = "NOTHING HERE."

'For Each name As String In itemName


'output = Name
'outputListBox.Items.Add(output)
'Next

End Sub
End Class

=====
=====

' Searching.sln
' Eric J. Schwabe
' IT 236 Spring 2008
' Demonstrate linear and binary searches of arrays

Option Strict On

Public Class Form1


Inherits System.Windows.Forms.Form

' Form-level array to be searched

Dim value() As Integer = {1, 4, 7, 19, 23, 25, 40, 86}


Dim size As Integer = 8

'Dim value() As Integer = {1, 3, 5, 8, 12, 15, 21, 22, 28, 34, 41, 49, _
' 55, 88, 91, 99}
'Dim size As Integer = 16

' Linear search: Check all positions of the array in order, keeping
' track of whether or not (and if so, where) the target value was found

Private Sub linearButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)


Handles linearButton.Click

Dim i As Integer
Dim found As Boolean = False
Dim position As Integer
Dim target As Integer = Integer.Parse(inTextBox.Text)

outputListBox.Items.Clear()

outputListBox.Items.Add("Target Value is " & target)

' Search the array

For i = 0 To size - 1
outputListBox.Items.Add("Position " & i & ":")
If value(i) = target Then
position = i
found = True
outputListBox.Items.Add(" YES!")
Else
outputListBox.Items.Add(" No.")
End If
Next

' Report the results


If (found) Then
outputListBox.Items.Add("Target found in position " & position)
Else
outputListBox.Items.Add("Target not found")
End If

End Sub

' Binary Search: For a sorted array, repeatedly check the middle element,
' and if it is not the target value, eliminate half of the values from
' consideration and try again. When either the target value is found or
' there are no elements unchecked, end the search and report the results.

Private Sub binaryButton_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles binaryButton.Click

Dim found As Boolean = False


Dim position As Integer
Dim target As Integer = CInt(inTextBox.Text)
Dim lower As Integer = 0
Dim upper As Integer = size - 1
Dim test As Integer

outputListBox.Items.Clear()

outputListBox.Items.Add("Target Value is " & target)

' Search until either all elements are eliminated or the


' target value is found

Do While (lower <= upper) And Not (found)


test = (lower + upper) \ 2
outputListBox.Items.Add(lower & " to " & upper & _
", testing " & test & " :")
If (value(test) < target) Then
outputListBox.Items.Add(" Too small.")
lower = test + 1
ElseIf (value(test) > target) Then
outputListBox.Items.Add(" Too big.")
upper = test - 1
Else
outputListBox.Items.Add(" FOUND IT!")
found = True
position = test
End If
Loop

' Report the results

If (found) Then
outputListBox.Items.Add("Target found in position " & position)
Else
outputListBox.Items.Add("Target not found")
End If

End Sub

End Class

=====
=====

' MultiplicationTable.sln
' Eric J. Schwabe
' IT 236 Spring 2008
' Demonstrates a two-dimensional array

Option Strict On

Public Class Form1


Inherits System.Windows.Forms.Form

' Declares a 11x11 array to store a mulitiplication table for numbers up


' to 10, prompts to user the number of rows and columns to display, and
' displays that section of the table...

Private Sub goButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles


goButton.Click

Dim rows, columns As Integer


Dim i, j As Integer
Dim output As String

' Declare a two-dimensional array to store that able


Dim table(11, 11) As Integer

' Prompt user for a positive value for the rows to display
Do
rows = Integer.Parse(InputBox("Enter the number of rows:", "ROW PROMPT"))
Loop Until (rows >= 1) And (rows <= 10)

' Prompt user for a positive value for the columns to display
Do
columns = Integer.Parse(InputBox("Enter the number of columns:", "COLUMN
PROMPT"))
Loop Until (columns >= 1) And (columns <= 10)

' Report the table size


outputListBox.Items.Clear()
outputListBox.Items.Add("Will show up to " & rows & " by " & columns)

' Fill in the table


For i = 1 To 10
For j = 1 To 10
table(i, j) = i * j
Next
Next

'Display the specified section of the table


For i = 1 To rows
output = ""
For j = 1 To columns
output = output & table(i, j) & " "
Next
outputListBox.Items.Add(output)
Next

' You can think about how to add row/column headings,


' and how to format the table more nicely...

End Sub
End Class

=====
=====

' CurrencyExchange.sln
' Eric J. Schwabe
' IT 236 Spring 2008
' Uses a two-dimensional array to store exchange rates

Option Strict On

Public Class Form1


Inherits System.Windows.Forms.Form

' A form-level array for exchange rates

Dim rate(3, 3) As Double

' Intiailize exchange rates when the program begins


' 0 = US Dollars
' 1 = EU Euros
' 2 = Japanese Yen

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles


MyBase.Load
rate(0, 0) = 1
rate(0, 1) = 0.83876
rate(0, 2) = 115.87
rate(1, 0) = 1.1923
rate(1, 1) = 1
rate(1, 2) = 138.18
rate(2, 0) = 0.0086316
rate(2, 1) = 0.0072363
rate(2, 2) = 1
End Sub

' When the button is clicked, reads the currencies in the two text boxes
' and uses them to find the correct row and column in the table of
' rates. If both currencies are valid, reads the input money amount
' and converts is using the appropriate exchange rate.

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles convertButton.Click

Dim currencyIn As String = fromCurrencyTextBox.Text


Dim currencyOut As String = toCurrencyTextBox.Text
Dim row, column As Integer
Dim oldAmount, newAmount As Double

Select Case currencyIn.Trim.ToUpper


Case "DOLLARS"
row = 0
Case "EUROS"
row = 1
Case "YEN"
row = 2
Case Else
row = -1
End Select

Select Case currencyOut.Trim.ToUpper


Case "DOLLARS"
column = 0
Case "EUROS"
column = 1
Case "YEN"
column = 2
Case Else
column = -1
End Select

If (row >= 0) And (column >= 0) Then


oldAmount = Double.Parse(fromAmountTextBox.Text)
newAmount = oldAmount * rate(row, column)
toAmountTextBox.Text = newAmount.ToString()
Else
toAmountTextBox.Text = "UNKNOWN!"
End If

End Sub

' Clear the output text box when the contents of any
' input text box are changed

Private Sub anyTextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)


Handles fromAmountTextBox.TextChanged, fromCurrencyTextBox.TextChanged,
toCurrencyTextBox.TextChanged
toAmountTextBox.Text = ""
End Sub

End Class

=====
=====

' RandomTest.sln
' Eric J. Schwabe
' IT 236 Spring 2008
' Test quality of random number generator using a control array

Option Strict On

Public Class Form1


Inherits System.Windows.Forms.Form

' A form-level control array of six text boxes

Dim output(6) As TextBox

' Assigns the six text boxes to the six elements of the control array

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles


MyBase.Load
output(1) = oneTextBox
output(2) = twoTextBox
output(3) = threeTextBox
output(4) = fourTextBox
output(5) = fiveTextBox
output(6) = sixTextBox
End Sub

' Generates 6000 random numbers from 1 to 6, and keeps track of the number
' of occurrences of each number in the array count. Displays the values
' in the count array in the six text boxes.

Private Sub goButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles goButton.Click

Dim count(6) As Integer


Dim i As Integer
Dim generator As New Random
Dim trials As Integer = 6000
Dim nextOne As Integer

' Initialize the count array to all zeroes


' (Notice that I am using locations 1-6 this time, not 0-5!)

For i = 1 To 6
count(i) = 0
Next

' For each trial, generate a random integer n from 1 to 6,


' and increment the count tracking occurrences of n

For i = 1 To trials
nextOne = generator.Next(1, 7) ' does not include 7!
count(nextOne) = count(nextOne) + 1
Next

' Display the contents of the count array

For i = 1 To 6
output(i).Text = count(i).ToString()
Next

End Sub

End Class

=====

You might also like