CS 113 - Introduction to Computers

Spring-2011

Classes: TR 5:55 pm - 7:10 pm,  Maria Sanford Hall 210
Instructor: Dr. Zdravko Markov, 30307 Maria Sanford Hall, (860)-832-2711, http://www.cs.ccsu.edu/~markov/, e-mail: markovz at ccsu dot edu
Office hours: TR 10:45am - 1:15pm, or by appointment

Catalog description: Introduction to computer programming together with the consideration of the impact of computers on society. Emphasis on logical problem-solving and algorithms. No credit given to students with credit for CS 151, CS 213 or Math 446, 471. Mode 2.

General description: This course is an introduction to the basic principles of computer programming. It focuses on developing problems solving skills through writing programs in Visual Basic 2008.  Students learn to develop graphical user interfaces (GUI’s) and use basic programming language structures to develop algorithms for solving various kinds of problems.

Course objectives: Having completed this course successfully, the student should:

Required textbook: David Schneider, An Introduction to Programming Using Visual Basic 2008, Seventh Edition, Prentice Hall, 2009, ISBN-10: 0136060722, ISBN-13:  9780136060727. Programs are available from http://media.pearsoncmg.com/ph/esm/bridgepages/schneider/Programs_7e.zip

Projects and tests: There will be 5 programming projects and 4 tests (including the final). The due dates for the projects and tests are shown below in the schedule of classes. All projects must be submitted through the Vista course management system available through CentralPipeline (Student > Blackboard Vista Courses > CS-113) or directly at https://vista.csus.ct.edu/webct/logon/16588872290071

Grading: The final grade is based 50% on test grades and 50% on project grades and will be affected by classroom participation, conduct and attendance. The letter grade will be calculated according to the following table:
 
A A- B+ B B- C+ C C- D+ D D- F
95-100 90-94 87-89 84-86 80-83 77-79 74-76 70-73 67-69 64-66 60-63 0-59

Class Participation: Regular attendance and active class participation is expected from all students. If you must miss a class, try to inform the instructor of this in advance.

Unexcused late submission policy: Projects submitted more than two days after the due date will be graded one letter grade down. Projects submitted more than a week late will receive two letter grades down. No submissions will be accepted more than two weeks after the due date.

Honesty policy: It is expected that all students will conduct themselves in an honest manner (see the Academic Misconduct section), and NEVER claim work which is not their own. Violating this policy will result in a substantial grade penalty, and may lead to expulsion from the University. However, students are allowed to discuss projects with others and receive debugging help from others.

Academic Misconduct: All students are expected to demonstrate integrity in the completion of their coursework. Academic integrity means doing one's own work and giving proper credit to the work and ideas of others. It is the responsibility of each student to become familiar with what constitutes academic dishonesty and plagiarism and to avoid all forms of cheating and plagiarism. Students who engage in plagiarism and other forms of academic misconduct will face academic and possibly disciplinary consequences. Academic sanctions can range from a reduced grade for the assignment to a failing grade for the course. From a disciplinary standpoint, an Academic Misconduct Report may be filed and a Faculty Hearing Board may impose sanctions such as probation, suspension or expulsion. You may find the full Academic Misconduct Policy online at http://web.ccsu.edu/academicintegrity/UndergradAcadMisconductPolicy.htm. Please read it carefully.
 

Tentative schedule of classes, assignments, projects and tests (by week)

Note: Dates will be posted for all classes, projects and test. Check the schedule regularly for updates!
  1. January 25, 27: Introduction to programming by example. Problem solving by programming.
  2. February 8, 10: Visual Basic programming environment and basic programming structures.
  3. February 15, 17, 22: Relational Expressions, If-Then-Else, String manipulation.
  4. February 24: Select Case block
  5. March  1: Test 1 (10%). Review topics and example problems for Test 1
  6. March  3, 8: Do-While/Until-Loops, Do-Loop-While/Until, Counters, Accumulators, Flags.
  7. March  10, 15, 17: For-Next Loops, Nested Loops
  8. March  29: Test 2 (10%). Review topics and example problems for TEST 2
  9. April 7, 12: General Sub Procedures, Parameters, Class-level variables
  10. April 14: Passing Parameters, Returning values, Fucntion procedures
  11. April 19, 21: Scope of variables, Call by reference, Call by value
  12. April 26: Test 3 (10%). Review topics and example problems for TEST 3
  13. April 28: Review of Sub Procedures and Functions: String manipulation
  14. May 3, 5: Sequential Files, One-Dimensional Arrays.
  15. May 10: Recursion. Recursion is not in tests or projects.
  16. Sorting. Sorting is not in tests or projects.
  17. May 19,  4:30 - 6:30 pm: Final Exam (see Review Problems)

Lecture 1

A little history and general perspective

Introduction to Programming by Example

Problem 1: This morning was 31°F. How much is this in Celsius.
  1. Using a calculator:  31, -, 32, =, *, 5, =, /, 9, = -0.5556
  2. Programming: calculating an arithmetic expression and printing the result. Program output (screen, window).
Public Class Form1
    Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
        lstBox.Items.Add(5 * (31 - 32) / 9)
    End Sub
End Class

Problem 2: Write a program that reads the temperature in Fahrenheit and prints the result in Celsius. Using variables, assignment, input and output.

Public Class Form1
    Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
        Dim F, C As Integer
        F = InputBox("Enter the temperature in Fahrenheit")
        C = 5 * (F - 32) / 9
        lstBox.Items.Add(CStr(F) & " Fahrenheit is eqivalent to " & CStr(C) & " Celsius")
    End Sub
End Class

Problem 3: Write a program to print a table with Fahrenheit temperatures and their Celsius equivalent. Using repetition (loops).

0   –18
20  –7
40  4
60  16
...
300 149

Public Class Form1
    Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
        Dim F, C As Integer
        F = 0
        Do While F <= 300
            C = 5 * (F - 32) / 9
            lstBox.Items.Add(CStr(F) & Chr(9) & CStr(C))
            F = F + 20
        Loop
    End Sub
End Class


Problem Solving by Programming

Program Development Cycle

  1. Analyze: Define the problem
  2. Design: Plan the solution to the problem
  3. Choose the Interface: Select the objects
  4. Code: Translate the algorithm into a programming language.
  5. Debug and Test: Locate and remove any errors in the program.
  6. Complete the Documentation: Organize all the materials that describe the program.

Tools used for the design stage

  1. Flowchart
  2. Pseudocode
  3. Hierarchy Chart (Structure chart)

Standard (non-visual) programming cycle (e.g. using C or Java)

  1. Type in and edit the program code as a text and store it in a file.
  2. Compile the file into executable code.
  3. If compile time errors occur go to step 1 and correct the code.
  4. Run the executable code (the actual program).
  5. If run time errors occur go to step 1 and correct the code.
  6. Type in what the program asks for and see the results on the screen.

Visual programming (in Visual Basic) using an Integrated Development Environment (IDE)

  1. Create the graphical user interface (GUI)
  2. Write procedural code
  3. Run the program (the application)

Visual Basic programming example

  1. Create a form named "Form1" (the default) and with a caption "Form1" (the default).
  2. Set the form properties (if necessary) or use the defaults.
  3. Bring up the code window (Select View/Code or Right Click/View Code ). You get:
    1.  
      Public Class Form1

      End Class
       

  4. Select (Form1 Events) from Class Name and Click from Method Name. You get:
    1. Public Class Form1

          Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click

          End Sub

      End Class
       

  5. Add  MsgBox("Hello World") inside the Form1_Click procedure:

  6. Public Class Form1

        Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
            MsgBox("Hello World")
        End Sub

    End Class
     

  7. Run the program

Lecture 2

Visual Basic Programming Environment: Objects (Controls), Events, Event Procedures

Steps to Create a Visual Basic Program

  1. Create the Objects
  2. Set Properties
  3. Write the Code for each Event

Most useful Visual Basic Controls

  1. Text Boxes
  2. Labels
  3. Buttons
  4. List Boxes

Creating a Text Box

  1. Double-click on TextBox to add a Text Box to your form
  2. Activate the Properties window (Press F4)
  3. Set values of Properties for Text Box

Rules for Naming Objects

  1. Use the Property window to change the Name property of an object
  2. Good Programming habit is that each name begins with three letter prefix that identifies the type of the object
  3. For Example:

Visual Basic Events

  1. Code is a set of statements that will be executed when you run a program.
  2. Write Code for each Event.
  3. Most Events are associated with Objects.
  4. The code for each event is called an “Event Procedure”.

Create An Event Procedure

  1. Create the interface.
  2. Set Properties.
  3. Get the Code window  through View/Code (F7) or double click on the object to create a template of the event procedure.
  4. Click on Class name to select (or create) the procedure.
  5. Click on the Method name to find/select an event.
  6. Write the code for the event.

Accessing the object properties

  1. Form is the default object.
  2. ObjectName.Property accesses Property of ObjectName.
  3. ObjectName.Procedure executes the Procedure associated with Object Name. Example: txtOutput.Clear() will clear the TextBox named txtOutput.

Example: Basic Controls


Variables, Assignment, Built-in Functions, Input, Output, Named Constants (page 212)

Example 1: Concatenation and addition. Convert strings into numbers - Val, CDbl, and CInt functions. Convert numbers to strings - CStr function. Public Class Form1

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        txtResult.Text = Val(txtInput1.Text) + Val(txtInput2.Text)
    End Sub

    Private Sub btnConcatenate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConcatenate.Click
        txtResult.Text = txtInput1.Text & txtInput2.Text  ' & may be replaced with +
    End Sub

End Class

Example 2: Using variables: Option Explicit, assignments, conversions, widening and narrowing, Option Strict\

Option Explicit Off

Public Class Form1
    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        X = txtInput1.Text
        Y = txtInput2.Text
        Result = X + Y
        txtResult.Text = Result
    End Sub

End Class

Option Explicit On
Option Strict On

Public Class Form1
    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim Result As Integer, X As Double, Y As Integer
        X = CDbl(txtInput1.Text)
        Y = CInt(txtInput2.Text)
        Result = CInt(X + Y)
        txtResult.Text = CStr(Result)
    End Sub

End Class

Example 3: Scope of variables, class-level variables. Compare the programs below and explain the results.

Program #1:
Public Class Form1

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        txtResult.Text = Val(txtResult.Text) + Val(txtInput1.Text)
    End Sub

End Class

Program #2:
Public Class Form1

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim Sum As Integer
        Sum = Sum + Val(txtInput1.Text)
        txtResult.Text = Sum
    End Sub

End Class

Program #3:
Public Class Form1

    Dim Sum As Integer

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Sum = Sum + Val(txtInput1.Text)
        txtResult.Text = Sum
    End Sub

End Class
 

Problem: Calculation of age (years and months lived) based on month and year of birth (Current month is 2, year - 2011, MOB is 3, YOB is 1956). Formula ("\" is integer division, "Mod" returns the remainder from integer division):

Solution 1: Direct calculation using numeric expression and activation by clicking on the form.

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        txtYears.Text = "Years = " & CStr((2 + 2011 * 12 - 3 - 1956 * 12) \ 12)
        txtMonths.Text = "Months = " & CStr((2 + 2011 * 12 - 3 - 1956 * 12) Mod 12)
    End Sub

Solution 2: Using variables and named constants - the Dim statement.

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim MOB, YOB, Months, Years, MonthsLived As Integer
        Const CurrentMonth As Integer = 2
        Const CurrentYear As Integer = 2011
        MOB = 3       ' Set up the value for MOB
        YOB = 1956   ' Set up the value for YOB
        MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
        Months = MonthsLived Mod 12  ' Remainder from integer division
        Years = MonthsLived \ 12     ' Integer division
        txtYears.Text = "Years = " & Years
        txtMonths.Text = "Months = " & Months
    End Sub

Solution 3: Using input boxes to enter data. Replace the constants 3 and 1956 with input boxes. Why do we need the CInt function?
           ...
        MOB = CInt(InputBox("Enter Month of Birth"))
        YOB = CInt(InputBox("Enter Year of Birth"))
        ...
Solution 4: Elaborating the interface - text boxes for input, one-line output. Why do we need the CInt and CStr functions?
        ...
        MOB = CInt(txtMOB.Text)
        YOB = CInt(txtYOB.Text)
        ...
        txtOutput.Text = " You are " & CStr(Years) & " years and " & CStr(Months) & " months old"
        ...


Lecture 3

Relational Expressions, If-Then-Else block

Example 1: Check if X belongs to the interval (5,10)?

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X As Integer
        X = CInt(txtX.Text)
        txtOutput1.Text = CStr(X) & " > 5 = " & CStr(X > 5)
        txtOutput2.Text = CStr(X) & " < 10 = " & CStr(X < 10)
        txtOutput3.Text = CStr(X) & " > 5 And " & CStr(X) & " < 10 = " & CStr(X > 5 And X < 10)
    End Sub

Example 2: Check if X does not belong to the interval (5,10)

Check the input type - The IsNumeric function

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        txtOutput.Text = CStr(IsNumeric(txtInput.Text))
    End Sub

Example 3: Add or concatenate inputs depending on their type. Use If-Then block.

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        If IsNumeric(txtInput.Text) = True Then
            txtOutput.Text = CStr(Val(txtInput.Text) + Val(txtInput.Text))
        End If
        If IsNumeric(txtInput.Text) = False Then
            txtOutput.Text = txtInput.Text & txtInput.Text
        End If
    End Sub

Example 4: Boolean variables.

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim Num As Boolean
        Num = IsNumeric(txtInput.Text)
        If Num = True Then
            txtOutput.Text = CStr(Val(txtInput.Text) + Val(txtInput.Text))
        End If
        If Num = False Then
            txtOutput.Text = txtInput.Text & txtInput.Text
        End If
    End Sub

Example 5: If-Then-Else block (Num may be used instead of Num=true)

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim Num As Boolean
        Num = IsNumeric(txtInput.Text)
        If Num = True Then
            txtOutput.Text = CStr(Val(txtInput.Text) + Val(txtInput.Text))
        Else
            txtOutput.Text = txtInput.Text & txtInput.Text
        End If
    End Sub

Elaboration: Add or concatenate two items (add if both are numeric, otherwise concatenate).I

Problem 1: Calculation of age based on month and year of birth

Solution 1:  No input data validation (see TOP 25 Most Dangerous Programming Errors)

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim MOB, YOB, Months, Years, MonthsLived As Integer
        Const CurrentMonth As Integer = 9
        Const CurrentYear As Integer = 2010
        MOB = CInt(InputBox("Enter Month of Birth"))
        YOB = CInt(InputBox("Enter Year of Birth"))
        MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
        Months = MonthsLived Mod 12  ' Remainder from integer division
        Years = MonthsLived \ 12     ' Integer division
        txtOutput.Text = " You are " & CStr(Years) & " years and " & CStr(Months) & " months old"
    End Sub

Solution 2:  Data validation

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim MOB, YOB, Months, Years, MonthsLived As Integer
        Const CurrentMonth As Integer = 9
        Const CurrentYear As Integer = 2010
        MOB = CInt(InputBox("Enter Month of Birth"))
        YOB = CInt(InputBox("Enter Year of Birth"))
        If YOB > 2010 Or YOB < 1900 Then         ' Check if YOB is out of the interval [1900,2010]
            MsgBox(CStr(YOB) & " - Wrong year")
        Else
            MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
            Months = MonthsLived Mod 12  ' Remainder from integer division
            Years = MonthsLived \ 12     ' Integer division
            txtOutput.Text = " You are " & CStr(Years) & " years and " & CStr(Months) & " months old"
        End If
    End Sub

Solution 3: More elaborated verification - ElseIf clause.

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim MOB, YOB, Months, Years, MonthsLived As Integer
        Const CurrentMonth As Integer = 9
        Const CurrentYear As Integer = 2010
        MOB = CInt(InputBox("Enter Month of Birth"))
        YOB = CInt(InputBox("Enter Year of Birth"))
        If YOB > 2010 Or YOB < 1900 Then         ' Check if YOB is out of the interval [1900,2010]
            MsgBox(CStr(YOB) & " - Wrong Year")
        ElseIf MOB > 12 Or MOB < 1 Then          ' Check if MOB is out of the interval [1,12]
            MsgBox(CStr(MOB) & " - Wrong Month")
        Else
            MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
            Months = MonthsLived Mod 12  ' Remainder from integer division
            Years = MonthsLived \ 12     ' Integer division
            txtOutput.Text = " You are " & CStr(Years) & " years and " & CStr(Months) & " months old"
        End If
    End Sub

Exercises:

More Numeric and String functions

Example 6: Generate random numbers between 1 and 6 and print them as words (one, two, three, four, five, six). Remove one blank after six and explain what happens and why.

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Const S As String = "one  two  threefour five six  "
        Dim Pos As Integer
        Pos = CInt(Rnd() * 5) * 5
        txtOutput.Text = S.Substring(Pos, 5)
    End Sub

Example 7:  Enter a number as a word (one, two, three, four, five, six) and print its numeric equivalent (1, 2, 3, 4, 5, 6). What happens if the input is not from the list?

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Const S As String = "one  two  threefour five six "
        Dim Pos, Num As Integer
        Pos = S.IndexOf(txtInput.Text)
        Num = (Pos \ 5) + 1
        txtOutput.Text = CStr(Num)
    End Sub


Lecture 4

Select Case Block

Problem: Implement a simple calculator using the following VB objects:
  1. Labels: lblOperand1 (Text: Operand1), lblOperand2 (Text: Operand2), lblOperation (Text: Operation)
  2. Text Boxes: txtOperand1, txtOperand2, txtOperation, txtResult
  3. Button: btnCalc (Text: Calculate)
Operand1 and Operand1 are numeric values (of type Double) and Operation (of type String) is one of following: "+", "-", "*", "/", "\", "mod". When you press the Calculate button the result of computing the expression <Operand1> <Operation> <Operand2> will be displayed in txtResult.

Solution 1: Using If-Then-ElseIf structures

Public Class Form1
    Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
        Dim X, Y As Double
        Dim Op As String
        X = Val(txtOperand1.Text)
        Y = Val(txtOperand2.Text)
        Op = txtOperation.Text
        If Op = "+" Then
            txtResult.Text = CStr(X + Y)
        ElseIf Op = "-" Then
            txtResult.Text = CStr(X - Y)
        ElseIf Op = "*" Then
            txtResult.Text = CStr(X * Y)
        ElseIf Op = "/" Then
            If Y <> 0 Then
                txtResult.Text = CStr(X / Y)
            Else
                txtResult.Text = "Division by 0"
            End If
        ElseIf Op = "\" Then
            If Y <> 0 Then
                txtResult.Text = CStr(X \ Y)
            Else
                txtResult.Text = "Division by 0"
            End If
        ElseIf Op = "mod" Then
            txtResult.Text = CStr(X Mod Y)
        Else
            txtResult.Text = "Incorrect operation"
        End If
    End Sub
End Class

Solution 2: Using Select Case structures

Public Class Form1
    Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
        Dim X, Y As Double
        Dim Op As String
        X = Val(txtOperand1.Text)
        Y = Val(txtOperand2.Text)
        Op = txtOperation.Text
        Select Op
            Case "+"
                txtResult.Text = CStr(X + Y)
            Case "-"
                txtResult.Text = CStr(X - Y)
            Case "*"
                txtResult.Text = CStr(X * Y)
            Case "/"
                If Y <> 0 Then
                    txtResult.Text = CStr(X / Y)
                Else
                    txtResult.Text = "Division by 0"
                End If
            Case "\"
                If Y <> 0 Then
                    txtResult.Text = CStr(X \ Y)
                Else
                    txtResult.Text = "Division by 0"
                End If
            Case "mod"
                txtResult.Text = CStr(X Mod Y)
            Case Else
                txtResult.Text = "Incorrect operation"
        End Select
    End Sub
End Class

Exercises:


Lecture 5

Do-While/Until-Loops, Counters, Accumulators

Example 1: Find the total and the average of a seqence of numbers (counters and accumulators). Elaboration: Display the numbers in a list box.

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X, Total, Average As Double
        Dim N, Count As Integer
        N = InputBox("How many numbers?")
        Count = 0
        Total = 0
        Do While Count < N
            X = Val(InputBox("Enter a number"))
            Count = Count + 1
            Total = Total + X
        Loop
        Average = Total / Count
        txtOutput1.Text = "You entered " & Count & " numbers totaling " & Total
        txtOutput2.Text = "The average of these numbers is " & Average
    End Sub
End Class

Example 2: Print Fahrenheit to Celsius conversion table for 0, 10, 20, ..., 90, 100. Using a fixed-count loop - the number of repetitions is known in advance. The stopping condition is based on a counter or accumulator. Elaboration: Change the step (S), use Double instead of Integer.

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Const F0 As Integer = 0
        Const F1 As Integer = 100
        Const S As Integer = 10
        Dim F, C As Integer
        F = F0
        lstOutput.Items.Add("Fahrenheit" & Chr(9) & "Celsius")
        Do While F <= F1
            C = (F - 32) * 5 / 9
            lstOutput.Items.Add(CStr(F) & Chr(9) & Chr(9) & CStr(C))
            F = F + S
        Loop
    End Sub
End Class

Example 3: Calculating Greatest Common Divisor (GCD) of two integers - Euclid's algorithm. See an applet implementation of Euclid here. More about Euclid can be found here. Using a variable-condition loop - the number of repetitions is NOT known in advance.
Public Class Form1
    Private Sub btnGCD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGCD.Click
        Dim A, B As Integer
        Dim X, Y, T As Integer
        A = Val(txtVal1.Text)
        B = Val(txtVal2.Text)
        X = A
        Y = B
        Do While Y > 0
            T = X Mod Y
            X = Y
            Y = T
        Loop
        txtOutput.Text = "The GCD of " & CStr(A) & " and " & CStr(B) & " is " & CStr(X)
    End Sub
End Class

Exercises:


Do-Loop-While/Until, Sentinel loops, Flags

Example 1: Counting the tries to guess a number

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim Number, Guess, Count As Integer
        Number = Second(Now()) Mod 11     ' Generate an unknown number using current time
        Count = 0
        Do
            Guess = InputBox("Enter a number between 0 and 10")
            Count = Count + 1
            If Guess > Number Then MsgBox("It's smaller")
            If Guess < Number Then MsgBox("It's bigger")
            If Guess = Number Then MsgBox("OK, the number is " & Number)
        Loop While Guess <> Number        ' Until Guess = Number
        MsgBox(Count & " tries")
    End Sub
End Class

Example 2: Counting, totaling, averaging a sequence of numbers. Exit the loop using a sentinel value.

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim Number, Total, Average As Double
        Dim Count As Integer
        Count = 0
        Total = 0
        Do
            Number = InputBox("Enter a number (0 to exit)")
            If Number <> 0 Then
                Count = Count + 1
                Total = Total + Number
            End If
        Loop While Number <> 0        ' Until Number = 0
        Average = Total / Count
        MsgBox("You entered " & Count & " numbers totaling " & Total)
        MsgBox("The average of these numbers is " & Average)
    End Sub
End Class

Example 3: Counting, totaling, averaging a sequence of numbers. Exit the loop using a sentinel value and a flag.


Lecture 6

For-Next Loops, Nested Loops

Fixed-count loops (For-Next Loop)

Problem 1: Calculating PI by approximation of the circle area (Monte Carlo method)

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X, Y As Double
        Dim I, N, M As Long
        N = InputBox("How many iterations?")
        M = 0
        For I = 1 To N
            X = Rnd(1)
            Y = Rnd(1)
            If X * X + Y * Y < 1 Then M = M + 1
        Next I
        MsgBox("PI = " & 4 * M / N)
    End Sub
End Class

Nested Loops

Problem 2: Print a table of approximation of PI

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X, Y As Double
        Dim I, N, M, Max As Long
        Max = InputBox("Max number of iterations?")
        lstOutput.Items.Add("Iterations" & Chr(9) & "PI")
        N = 1
        Do
            M = 0
            For I = 1 To N
                X = Rnd(1)
                Y = Rnd(1)
                If X * X + Y * Y < 1 Then M = M + 1
            Next I
            lstOutput.Items.Add(N & Chr(9) & 4 * M / N)
            N = N * 2
        Loop Until N >= Max
    End Sub
End Class

Problem 3: . Print the proper factors of a number (the divisors except the number itself). If the number of proper factors is 1, then this is a prime number. Count the prime numbers less than a given number.

'Print the proper factors of a number
'and count the number of primes less than 20
Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim N, F, Fcount, P As Integer, Line As String
        P = 0
        For N = 1 To 20
            Line = CStr(N) & "  "
            Fcount = 0
            For F = 1 To N / 2
                If N Mod F = 0 Then
                    Line = Line & F & " "
                    Fcount = Fcount + 1
                End If
            Next F
            If Fcount = 1 Then P = P + 1
            lstOutput.Items.Add(Line)
        Next N
        lstOutput.Items.Add("Number of primes = " & P)
    End Sub
End Class

Problem 4: Tabulate Pi(N) using the "Brute force" approach. Pi(N) is  the number of prime numbers less than or equal to N. For more information about prime numbers see this link.

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim N, F, Fcount, P As Integer
        P = 0
        lstOutput.Items.Add("N" & Chr(9) & "Pi(N)")
        For N = 1 To 1000
            Fcount = 0
            For F = 1 To N / 2
                If N Mod F = 0 Then Fcount = Fcount + 1
            Next F
            If Fcount = 1 Then P = P + 1
            If N Mod 100 = 0 Then lstOutput.Items.Add(N & Chr(9) & P)
        Next N
    End Sub
End Class


Lecture 7

General Sub Procedures, Parameters, Class-level (global) variables

1. Print the GCD of two numbers (no sub procedure)

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim A, B As Integer
        Dim X, Y, T As Integer
        A = Val(txtVal1.Text)
        B = Val(txtVal2.Text)
        X = A
        Y = B
        Do While Y > 0
            T = X Mod Y
            X = Y
            Y = T
        Loop
        txtOutput.Text = "The GCD of " & CStr(A) & " and " & CStr(B) & " is " & CStr(X)
    End Sub
End Class

2. Print the GCD of two numbers. Use a Sub procedure to print the GCD

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim A, B As Integer
        A = Val(InputBox("Enter first number"))
        B = Val(InputBox("Enter second number"))
        txtOutput.Text = "The GCD of " & CStr(A) & " and " & CStr(B) & " is "
        Call GCD(A, B)
    End Sub
    Private Sub GCD(ByVal X As Integer, ByVal Y As Integer)
        Dim T As Integer
        Do While Y > 0
            T = X Mod Y
            X = Y
            Y = T
        Loop
        txtOutput.Text = txtOutput.Text & CStr(X)
    End Sub
End Class

3. Print the GCD of two numbers. Use a Sub procedure to calculate the GCD and a class-level variable to return the result.

Public Class Form1
    Dim F As Integer ' Class-level (global) variable
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim A, B As Integer
        A = Val(InputBox("Enter first number"))
        B = Val(InputBox("Enter second number"))
        Call GCD(A, B)
        txtOutput.Text = "The GCD of " & CStr(A) & " and " & CStr(B) & " is " & CStr(F)
    End Sub
    Private Sub GCD(ByVal X As Integer, ByVal Y As Integer)
        Dim T As Integer
        Do While Y > 0
            T = X Mod Y
            X = Y
            Y = T
        Loop
        F = X
    End Sub
End Class

4. Add two fractions and simplify the result by using GCD

5. Print the proper factors of a number by using  a general sub procedure

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim N
        For N = 1 To 20
            Call PrintFactors(N)
        Next N
    End Sub
    Private Sub PrintFactors(ByVal N As Integer)
        Dim F As Integer, Line As String
        Line = CStr(N) & "  "
        For F = 1 To N / 2
            If N Mod F = 0 Then
                Line = Line & F & " "
            End If
        Next F
        lstOutput.Items.Add(Line)
    End Sub
End Class

6. Use a form-level variable to return the number of proper factors

Public Class Form1

    Dim Fcount As Integer

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim N As Integer
        For N = 1 To 10
            Call Factors(N)
            lstOutput.Items.Add(N & Chr(9) & Fcount)
        Next N
    End Sub

    Private Sub Factors(ByVal N As Integer)
        Dim F As Integer
        Fcount = 0
        For F = 1 To N / 2
            If N Mod F = 0 Then Fcount = Fcount + 1
        Next F
    End Sub

End Class

7. Write a general sub procedure that returns the sum of the proper factors of a number. Then use it in a program to find if a number is deficient, abundant or perfect.


Lecture 8

Passing parameters, Returning values, Function Procedures

Problem: Find the maximum of three numbers

Solution 1: No sub procedures

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X, Y, Z, M, Max As Double
        X = InputBox("X = ?")
        Y = InputBox("Y = ?")
        Z = InputBox("Z = ?")
        If X > Y Then
            M = X
        Else
            M = Y
        End If     ' M is the maximum of X and Y
        If M > Z Then
            Max = M
        Else
            Max = Z
        End If     ' Max is the maximum of M and Z
        MsgBox("The maximum of " & X & ", " & Y & " and " & Z & " is  " & Max)
    End Sub
End Class

Solution 2: Using sub procedure and returning values through a global variable

Public Class Form1
    Dim Max As Double ' A global variable accessible from any procedure

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X, Y, Z As Double
        X = InputBox("X = ?")
        Y = InputBox("Y = ?")
        Z = InputBox("Z = ?")
        Call Max2(X, Y)    ' Max is the maximum of X and Y
        Call Max2(Max, Z) ' Max is the maximum of Max and Z
        MsgBox("The maximum of " & X & ", " & Y & " and " & Z & " is  " & Max)
    End Sub

    Public Sub Max2(ByVal A As Double, ByVal B As Double) ' Return maximum in global variable Max
        If A > B Then
            Max = A
        Else
            Max = B
        End If
    End Sub
End Class

Solution 3: Returning values through a parameter

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X, Y, Z, Max As Double
        X = InputBox("X = ?")
        Y = InputBox("Y = ?")
        Z = InputBox("Z = ?")
        Call Max2(X, Y, Max)    ' Max is the maximum of X and Y
        Call Max2(Max, Z, Max)  ' Max is the maximum of Max and Z
        MsgBox("The maximum of " & X & ", " & Y & " and " & Z & " is  " & Max)
    End Sub

    Public Sub Max2(ByVal A As Double, ByVal B As Double, ByRef Max As Double)
        If A > B Then
            Max = A
        Else
            Max = B
        End If
    End Sub
End Class

Solution 4: Using function procedure

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X, Y, Z, M, Max As Double
        X = InputBox("X = ?")
        Y = InputBox("Y = ?")
        Z = InputBox("Z = ?")
        M = Max2(X, Y)    ' Max is the maximum of X and Y
        Max = Max2(M, Z)  ' Max is the maximum of Max and Z
        MsgBox("The maximum of " & X & ", " & Y & " and " & Z & " is  " & Max)
    End Sub

    Public Function Max2(ByVal A As Single, ByVal B As Single) As Double ' Note that there is a type definition here
        If A > B Then
            Max2 = A
        Else
            Max2 = B
        End If
    End Function
End Class

Elaboration: Using functions as parameters (modify the code above).

  1. Max = Max2(Max2(X, Y), Z)
  2. Max = Max2(Max2(InputBox("X = ?"), InputBox("Y = ?")), InputBox("Z = ?"))
  3. Max = Max2(Max2(Max2(InputBox("A=?"), InputBox("B=?")), InputBox("C=?")), InputBox("D=?"))
  4. Max = Max2(Max2(Max2(5, 8), 3), Max2(Max2(9, Max2(Max2(12, 7), 2)), 11)) (what is the value of Max?)

Lecture 9

Scope of variables, Call by reference, Call by value

Problem 1: Find the Greatest Common Divisor (GCD) of two integers using the Euclid's algorithm.

Solution 1: Using Call by Reference. If we enter 6 for A and 8 for B, the program prints: The GCD of 2 and 0 is 2 (Why?)

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim A, B, D As Integer
        A = InputBox("A = ?")
        B = InputBox("B = ?")
        D = GCD(A, B)
        MsgBox("The GCD of " & A & " and " & B & " is " & D)
    End Sub

    Public Function GCD(ByRef X As Integer, ByRef Y As Integer) As Integer
        Dim R As Integer
        Do While Y > 0
            R = X Mod Y
            X = Y
            Y = R
        Loop
        GCD = X
    End Function
End Class

Solution 2: Using Call by Value. Modify the function formal parameters as shown below. Then if we enter 6 for A and 8 for B, the program prints: The GCD of 6 and 8 is 2.

Public Function GCD(ByVal X As Integer, ByVal Y As Integer) As Integer
        Dim R As Integer
        Do While Y > 0
            R = X Mod Y
            X = Y
            Y = R
        Loop
        GCD = X
    End Function

Problem 2: Find and fix the bug in the following program (it always prints 0 as maximum).

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X, Y, Z, Max As Double
        X = InputBox("X = ?")
        Y = InputBox("Y = ?")
        Z = InputBox("Z = ?")
        Call Max2(X, Y, Max)
        Call Max2(Max, Z, Max)
        MsgBox("The maximum of " & X & ", " & Y & " and " & Z & " is  " & Max)
    End Sub

    Public Sub Max2(ByVal A As Double, ByVal B As Double, ByVal C As Double)
        If A > B Then
            C = A
        Else
            C = B
        End If
    End Sub
End Class

Problem 3: Add fractions and simplify the sum

' Compute A/B + C/D = Num/Den in rational numbers (fractions)
' Use GCD to simplify the sum
Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim A, B, C, D, Num, Den, F As Integer
        A = InputBox("Enter first numerator")
        B = InputBox("Enter first denominator")
        C = InputBox("Enter second numerator")
        D = InputBox("Enter second denominator")
        Num = A * D + B * C
        Den = B * D
        F = GCD(Num, Den)
        Num = Num / F
        Den = Den / F
        MsgBox(A & " / " & B & " + " & C & " / " & D & " = " & Num & "/" & Den)
    End Sub

    Public Function GCD(ByVal X As Integer, ByVal Y As Integer) As Integer
        Dim R As Integer
        Do While Y > 0
            R = X Mod Y
            X = Y
            Y = R
        Loop
        GCD = X
    End Function
End Class

Problem 4: Modify the program from Problem 3 so that the simplificaiton is done by a subprocedure.

Problem 5: Modify the program from Problem 3 by adding subprocedures to add two fractions and divide two fractions..


Lecture 10

Review of Sub Procedures and Functions: String manipulation

Problem 1: Request a person's first name and last name as input and display the corresponding initials. Use a function procedure that reads a name and returns its first letter.

Problem 2: Parsing a string of data: Given a sequence of words separated by blanks, the program prints each word on a separate line along with its type (sting or number). For example: given the string: "Name John Age 20" the program prints:

Name    string
John    string
Age     string
20      number

Review of string built-in functions needed:

Solution:

Public Class Form1

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim Line As String, W As String, N As Integer
        Line = InputBox("Type a line of text")
        N = 0
        Do
            W = Word(Line)
            If W <> "" Then
                If IsNumeric(W) Then
                    MsgBox(W & " number")
                Else
                    MsgBox(W & " string")
                End If
                N = N + 1
            End If
        Loop While W <> ""
        MsgBox(N & " words")
    End Sub

    'Returns and removes the first word from S (S is passed by reference, the function changes it).
    Public Function Word(ByRef S As String) As String
        Dim L As Integer, I As Integer
        S = LTrim(S)                        ' Trim the leading blanks (if any)
        L = Len(S)                          ' L is the length of S
        If L = 0 Then                       ' If no more charachters in S Then
            Word = ""                       ' return empty string
        Else                                ' Else (S is not empty) do the following:
            I = InStr(S, " ")               ' I = the position of the first blank
            If I > 0 Then                   ' If I>0 (there is a blank in S) Then
                Word = Mid(S, 1, I - 1)     ' return the word before the blank and
                S = Mid(S, I, L - I + 1)    ' remove it from S
            Else                            ' Else (I=0, i.e. there is no blank after the word - last word is S)
                Word = S                    ' Return the last word (i.e. S) and
                S = ""                      ' remove it from S
            End If
        End If
    End Function
End Class
 

Problem 2 elaboration: Count the number of strings and numbers and compute the average, min, and max for the numbers.

Problem 3: Write a program that reads student names and their grades (0-100) specified on one line of text. Then it prints each name and the corresponding letter grade on separate lines. Use the Word function (above) to process the text input. The following table shows the conversion between numeric and letter grades.
 
A B C D F
90-100 80-89 70-79 60-69 0-59


 Lecture 11

Recursion

Problem 1: Write a function procedure for computing the factorial function N!

Private Sub Form_Click()
  Print Fact(5)    ' This should print 120
End Sub

Solution 1: Factorial (iterative)


Public Function Fact(N As Integer) As Integer
Dim F As Integer
  F = 1
  If N > 0 Then
    Do While N > 0
       F = F * N
       N = N - 1
    Loop
  End If
  Fact = F
End Function

Solution 2: Factorial (recursive)

Public Function Fact(N As Integer) As Integer
  If N > 0 Then
    Fact = N * Fact(N - 1)
  Else
    Fact = 1
  End If
End Function

Problem 2: Recursive procedure to draw a triangle (fractals)

Solution 1: Using triangles only

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim gr As Graphics = picBox.CreateGraphics
        Call triangle(gr, 10, 10, 500)
    End Sub

    Private Sub triangle(ByVal gr As Graphics, ByVal X As Integer, ByVal Y As Integer, ByVal S As Integer)
        If S = 1 Then
            gr.DrawLine(Pens.Black, X, Y, X + 1, Y + 1)
        Else
            Call triangle(gr, X, Y, S / 2)
            Call triangle(gr, X + S / 2, Y, S / 2)
            Call triangle(gr, X, Y + S / 2, S / 2)
        End If
    End Sub

End Class

Solution 2: Using triangles and a square

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim gr As Graphics = picBox.CreateGraphics
        Call triangle(gr, 10, 10, 250)
    End Sub

    Private Sub square(ByVal gr As Graphics, ByVal X As Integer, ByVal Y As Integer, ByVal S As Integer)
        gr.DrawLine(Pens.Black, X, Y, X, Y + S)
        gr.DrawLine(Pens.Black, X, Y + S, X + S, Y + S)
        gr.DrawLine(Pens.Black, X + S, Y + S, X + S, Y)
        gr.DrawLine(Pens.Black, X + S, Y, X, Y)
    End Sub

    Private Sub triangle(ByVal gr As Graphics, ByVal X As Integer, ByVal Y As Integer, ByVal S As Integer)
        If S = 1 Then
            gr.DrawLine(Pens.Black, X, Y, X + 1, Y + 1)
        Else
            Call square(gr, X, Y, S / 2)
            Call triangle(gr, X + S / 2, Y, S / 2)
            Call triangle(gr, X, Y + S / 2, S / 2)
        End If
    End Sub

End Class

Problem 3: Write a function procedure greater(S1, S2)  for comparing strings (lexicographic order). Examples:

greater("abc", "bbc") = True
greater("bbc", "abc") = False
greater("abc", "ab") = True
greater("abc", "abb") = True


Private Sub Form_Click()
  Dim S1 As String, S2 As String
  S1 = InputBox("Enter string")
  S2 = InputBox("Enter another string")
  Print S1;" is greater than "; S2, greater(S1,S2)
End Sub

Solution 1 (non-recursive):

Public Function greater(X As String, Y As String) As Boolean
  Dim M As Integer, N As Integer, I As Integer
  M = Len(X)
  N = Len(Y)
  I = 1
  Do While I <= M And I <= N And Mid(X, I, 1) = Mid(Y, I, 1)
    I = I + 1
  Loop
  If I > M Then
    greater = False
  ElseIf I > N Then
    greater = True
  Else
    greater = Asc(Mid(X, I, 1)) > Asc(Mid(Y, I, 1))
  End If
End Function

Solution 2 (recursive):

Public Function greater(X As String, Y As String) As Boolean
  If X = "" Then
     greater = False
  ElseIf Y = "" Then
     greater = True
  ElseIf Mid(X, 1, 1) <> Mid(Y, 1, 1) Then
     greater = Asc(Mid(X, 1, 1)) > Asc(Mid(Y, 1, 1))
  Else
     X = Mid(X, 2, Len(X) - 1)
     Y = Mid(Y, 2, Len(Y) - 1)
     greater = greater(X, Y)
  End If
End Function


Lecture 12

Files and Arrays

Problem 1: Read the contents of a text file and print it in a ListBox

File (text.txt) contents:

90 John Smith
80 Al Clark
55 Sue Taylor
75 Ann Miller
Solution 1: Read and print each line as a string

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X As String
        Dim sr As IO.StreamReader = IO.File.OpenText("data.txt")
        Do While (sr.Peek <> -1)
           X = sr.ReadLine
            lstOutput.Items.Add(X)
        Loop
    End Sub
End Class

Solution 2: Read each line in two separate variables - Grade and Name.

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X As String, Grade As Integer, Name As String
        Dim sr As IO.StreamReader = IO.File.OpenText("data.txt")
        Do While (sr.Peek <> -1)
            X = sr.ReadLine
            Grade = CInt(X.Substring(0, 2))
            Name = X.Substring(3, X.Length - 3)
            lstOutput.Items.Add(Grade & " " & Name)
        Loop
    End Sub
End Class

Elaborations:

Solution 3: Read the file into an array and then print the array.

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X(10) As String, N As Integer
        Dim sr As IO.StreamReader = IO.File.OpenText("data.txt")
        N = 0
        Do While (sr.Peek <> -1)
            X(N) = sr.ReadLine
            N = N + 1
        Loop
        lstOutput.Items.Add(N & " student records read")
        For I = 0 To N - 1
            lstOutput.Items.Add(X(I))
        Next I
    End Sub
End Class

Elaborations:

Problem 2: Search a text file with student records

File contents:

90 John Smith
80 Al Clark
55 Sue Taylor
75 Ann Miller
A search for names with "A" must produce:
80 Al Clark
75 Ann Miller
Solution: Search the whole records (try searching by grade or part of it).

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X(10) As String, S As String, N As Integer
        Dim sr As IO.StreamReader = IO.File.OpenText("M:\data.txt")
        N = 0
        Do While (sr.Peek <> -1)
            X(N) = sr.ReadLine
            N = N + 1
        Loop
        S = InputBox("Enter student's record or part of it")
        lstOutput.Items.Add("Student records found:")
        For I = 0 To N-1
            If InStr(X(I), S) > 0 Then
                lstOutput.Items.Add(X(I))
           End If
        Next I
    End Sub
End Class

Elaborations: Search by grades, grade intervals or by letter grades (converted to intervals).


Lecture 13

Sorting student grades/records

1. Using Selection Sort algorithm

Public Class Form1
    Dim Grade(10) As Integer
    Dim N As Integer

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X, P As String, I As Integer
        Dim sr As IO.StreamReader = IO.File.OpenText("M:\data.txt")
        N = 0
        Do While (sr.Peek <> -1)
            X = sr.ReadLine
            lstOutput.Items.Add(X)
            Grade(N) = CInt(X.Substring(0, 2))
            N = N + 1
        Loop

        P = "Unsorted: "
        For I = 0 To N - 1
            P = P & Grade(I) & " "
        Next I
        lstOutput.Items.Add(P)

        Call SelectionSort()

        P = "Sorted: "
        For I = 0 To N - 1
            P = P & Grade(I) & " "
        Next I
        lstOutput.Items.Add(P)

    End Sub

    Public Sub SelectionSort()
        Dim I, J, T As Integer
        For I = 0 To N - 1
            J = MinIndex(I, N - 1)
            T = Grade(I)
            Grade(I) = Grade(J)
            Grade(J) = T
        Next I
    End Sub

    Public Function MinIndex(ByVal M As Integer, ByVal N As Integer) As Integer
        Dim Min, I As Integer
        Min = Grade(M)
        MinIndex = M
        For I = M To N
            If Grade(I) < Min Then
                Min = Grade(I)
                MinIndex = I
            End If
        Next I
    End Function
End Class
 

2. Using Bubble Sort algortithm

    Public Sub BubbleSort()
        Dim I, Swaps, T As Integer
        Do
            Swaps = 0
            For I = 0 To N - 2
                If Grade(I) > Grade(I + 1) Then
                    T = Grade(I)
                    Grade(I) = Grade(I + 1)
                    Grade(I + 1) = T
                    Swaps = Swaps + 1
                End If
           Next I
        Loop While Swaps > 0
    End Sub

Elaborations:


PROJECT 0 (grade not assigned, but submission required, the following projects will not be accepted otherwise)

Install VB 2008 on your computer or use it in the computer lab. Write and test the "Hello World" program from Lecture1. Then submit it through Vista as an attachment by doing the following:

PROJECT 1 (10 pts.)

Not available at this time.

PROJECT 2 (10 pts.)

Not available at this time.

PROJECT 3 (10 pts.)

Not available at this time.

PROJECT 4 (10 pts.)

Not available at this time.

PROJECT 5 (10 pts.)

Not available at this time.

Review topics and sample problems for TEST 1

Review topics

  1. Basic visual objects (form, text box, label, button, list box), accessing their properties from within the code.
  2. Input and output, strings, concatenation, combining strings and variables.
  3. Arithmetic expressions, integer arithmetic (\, mod).
  4. Variable types: Integer, Double, String, Booelan, explicit and implicit type conversions, narrowing, widening, built-in functions (Val, IsNumeric, CStr, CInt, CDbl, Substring, IndexOf).
  5. Relational expressions: arithmetic comparisons and logic operations.
  6. If-Then-Else structures
  7. If-Then-ElseIf structures

Example problems

  1. Describe the visual objects and their properties needed to run the following program. For each object include the following: type of the object, name and purpose in the program.

  2. Public Class Form1
        Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
            Dim X As Double
            X = CDbl(txtInput.Text)
            txtOutput.Text = CStr(X*X)
        End Sub
    End Class
     
  3. Let X and Y be integer variables. Write a single assignment statement that will display in the text box named txtOutput the quotient and the remainder of the integer division X divided by Y. For example if X=26 and Y=4 then the following should be snown:

  4. 26 divided by 4 is 6 and the remainder is 2
     
  5. What is displayed in text box TextBox3 assuming that text box TextBox1 contains 3.14 and text box TextBox2 contains 5? Explain your answer.

  6. Option Strict Off
    Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim X As Integer
            Dim Y As Double
            X = CDbl(TextBox1.Text)
            Y = CInt(TextBox2.Text)
            TextBox3.Text = CStr(X + Y)
        End Sub
    End Class

    What happens if X and Y are both of type Double? What happens if Option Strict is on?
     

  7. Find values for X and Y such that the following segment of code will show up the "Nice" message box.

  8. If X > Y Or X > 0 Then
       X = Y
    End If
    If X < Y Then
       MsgBox("Nice")
    End If
     
  9. Rewrite the following code using an IF-Then-Else structure

  10. If X > Y Then
      M = X
    End If
    If X <= Y Then
      M = Y
    End If
     
  11. Write a segment of code that finds the maximum of three variables X, Y and Z and assigns it to variable Max.
  12. Write an If-Then block that displays "in" in a message box, if valiable X belongs to interval [18, 65].
  13. Write an If-Then block that displays "in" in a message box, if valiable X belongs to interval [10, 20] or interval [30, 50].
  14. Write an If-Then block that displays "out" in a message box, if valiable X is outside (does not belong to) interval [18, 65].
  15. Write an If-Then-Else block that displays in a message box "even", if the value of variable X is even and "odd", if its value is odd.

Review topics and sample problems for TEST 2

Review topics

  1. Arithmetic expressions, integer arithmetic (\, mod), Variable types (integer, double, string) and assignments.
  2. If-Then-Else-ElseIf structures, Relational expressions.
  3. Do-While-Loop structures
  4. Do-Loop-While structures
  5. For-Next Loops

Example problems: writing programs from scratch

  1. Input and verify the variables and print the value of an expression.

  2. Problem: Compute the volume of a cylinder.

    Public Class Form1
        Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
            Dim R, H, V As Double
            R = InputBox("Enter Radius")
            H = InputBox("Enter Height")
            If R > 0 And H > 0 Then
                V = 3.141592 * R ^ 2 * H
                MsgBox("Volume of the cylinder = " & V)
            Else
                MsgBox("Incorrect input. Try again")
            End If
        End Sub
    End Class
     

  3. Input and verify the variables and print the result of a condition on these variables.

  4. Problem:  Verify whether a number is a perfect square (a square of another number).

    Public Class Form1
        Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
            Dim N As Integer, S As Double
            N = InputBox("Enter an integer number")
            If N > 0 Then
                S = Math.Sqrt(N)
                If S = CInt(S) Then
                    MsgBox(N & " is a perfect square")
                Else
                    MsgBox(N & " is not a perfect square")
                End If
            Else
                MsgBox("Incorrect Input. Try agian")
            End If
        End Sub
    End Class
     

  5. Verify a condition on the numbers in an interval.

  6. Problem: Print the even numbers from 10 to 30. Use For-Next loop. Use a step instead of a condition in the loop.

    Public Class Form1
        Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
            Dim I As Integer, S As Double
            For I = 10 To 30
                If I Mod 2 = 0 Then
                    lstOutput.Items.Add(I)
                End If
            Next I
        End Sub
    End Class
     

  7. Totaling and counting using a fixed count loop (For-Next Loop).

  8. Problem: Input 10 numbers using InputBox and count the even and odd numbers.

    Public Class Form1
        Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
            Dim N, I, EvenCount, OddCount As Integer
            EvenCount = 0
            OddCount = 0
            For I = 1 To 10
               N = InputBox("Enter a number")
                If N Mod 2 = 0 Then
                    EvenCount = EvenCount + 1
                Else
                    OddCount = OddCount + 1
                End If
            Next I
            lstOutput.Items.Add(EvenCount & " even numbers")
            lstOutput.Items.Add(OddCount & " odd numbers")
        End Sub
    End Class
     

  9. Iterative computation.

  10. Problem: Find the first N for which the sum of series 1+1/2+1/3+...+1/N is greater than 10.

    Public Class Form1
        Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
            Dim I As Integer, S As Single
            S = 0
            I = 0
            Do
                I = I + 1
                S = S + 1 / I
            Loop Until S > 10
            MsgBox(I)
        End Sub
    End Class

Example problems: modifying programs

Problem 1:  The following program prints the multiples of 3 in the interval [1,100]. Modify the program, so that it prints the number of muiltiples of 3 in the interval [1, 100].

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim I As Integer
        For I = 1 To 100
            If I Mod 3 = 0 Then
               lstOutput.Items.Add(I)
            End If
        Next I
    End Sub
End Class

Problem 2: Modify the program from Problem 1, so that it uses a Do-Loop-While structure.

Problem 3: Modify the following program, so that it stops when  more than 10 numbers are entered. Use the same type of loop.

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim N, EvenCount, OddCount As Integer
        EvenCount = 0
        OddCount = 0
        Do
            N = InputBox("Enter a number")
            If N Mod 2 = 0 Then
                EvenCount = EvenCount + 1
            Else
                OddCount = OddCount + 1
           End If
        Loop While N <> 0
        lstOutput.Items.Add(EvenCount & " even numbers")
        lstOutput.Items.Add(OddCount & " odd numbers")
    End Sub
End Class

Problem 4: What does the program below print? Circle the correct answer and explain it.

a)  1.5                        b)  2                        c) 3                          c) nothing (goes into infinite loop)
Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim I As Integer, S As Double
        S = 1
        I = 1
        Do
            S = S + 1 / I
            I = I + 1
        Loop While S < 2
        MsgBox(I)
    End Sub
End Class

Review topics and example problems for TEST 3

Review topics

  1. General Sub Procedures - Section 5.1.
  2. Local variables, Form-level variables, Passing parameters, Returning values -  Section 5.2.
  3. Function Procedures - Section 5.3

Example problems:

1. Write general sub procedures to complete the program below:

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
       Dim X As Integer, Y As Integer
       X = InputBox("Enter a number")
       Y = InputBox("Enter another number")
       Call PrintMin(X, Y)     ' Prints the smaller of X and Y
       Call PrintMax(X, Y)     ' Prints the bigger of X and Y
       Call PrintAverage(X, Y) ' Prints the average of X and Y
    End Sub
End Class

2. Use the follwing general sub procedure

Private Sub PrintAverage(X As Integer, Y As Integer, Z As Integer)
   Dim Average As Double
   Average = (X + Y + Z) / 3
   MsgBox("The average is :" & Average)
End Sub

a) write a program to print the average of 1, 2, and 4.
b) write a program that inputs (with InputBox) 3 integers and prints their average.
c) write a program that prints the average of 2.5, 3.14, and 7. Hint: modify PrintAverage accordingly.

3. Do problem 2, however use class-level variables to pass the numbers to PrintAverage. That is, the sub procedure should be defined without parameters as follows:

Private Sub PrintAverage()
   Dim Average As Double
   Average = (X + Y + Z) / 3
   MsgBox("The average is :" & Average)
End Sub
 

4.  What does the program below print? 1 or 2? Explain why. What happens if ByVal is replaced with ByRef in AddOne?

Public Class Form1

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X As Integer
        X = 1
        Call AddOne(X)
        MsgBox(X)
    End Sub

    Private Sub AddOne(ByVal X As Integer)
        X = X + 1
    End Sub

End Class
 

5. Write function procedures to complete the program below:

Public Class Form1

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X As Integer, Y As Integer
        X = InputBox("Enter a number")
        Y = InputBox("Enter another number")
        MsgBox(Min(X, Y))     ' Prints the smaller of X and Y
        MsgBox(Max(X, Y))     ' Prints the bigger of X and Y
        MsgBox(Average(X, Y)) ' Prints the average of X and Y
    End Sub

End Class
 

6. Use the follwing function procedure

Private Function Average(X As Integer, Y As Integer, Z As Integer) As Single
   Average = (X + Y + Z) / 3
End Function

a) write a program to print the average of 1, 2, and 4.
b) write a program that inputs (with InputBox) 3 integers and prints their average.
c) write a program that prints the average of 2.5, 3.14, and 7. Hint: modify Average accordingly.
 

7. Write a sub proceduire and a function procedure to complete the program below:

Public Class Form1

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
       Dim X As Integer, Y As Integer
       Call InputTwoNumbers(X, Y)          ' Reads two numbers from user input
       MsgBox("The sum is " & Sum(X, Y))   ' Print the sum of X and Y
    End Sub

End Class
 

8. Use the follwing sub procedure

Private Sub Average(ByVal X As Integer, ByVal Y As Integer, ByVal Z As Integer, ByRef W As Double)
   W = (X + Y + Z) / 3
End Sub

a) write a program to print the average of 1, 2, and 4.
b) write a program that inputs (with InputBox) 3 integers and prints their average.
c) write a program that prints the average of 2.5, 3.14, and 7. Hint: modify Average accordingly.


Review problems for the Final Exam

Problem 1. Fill in the blanks in lstOutput.Items.Add statements in the program below with proper arithmetic expressions and strings (do NOT include numbers), so that it prints the product the fractions (A/B)*(C/D) as a fraction (on the first line) and as a decimal value (on the second line). The output should be the following:

The product of 2/5 and 3/4 is 6/20
The product of 2/5 and 3/4 is decimal is 0.3

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
   Dim A, B, C, D As Integer
   A = 2
   B = 5
   C = 3
   D = 4
   lstOutput.Items.Add(_____________________________________)

   lstOutput.Items.Add(_____________________________________)
End Sub

Elaboration: Use TextBoxes to assign values to the variables A, B, C, and D.

Problem 2. Change the Do-While-Loop with a For-Next loop in the program below. The new program should produce exactly the same output as the original one.

Public Class Form1
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X, S, Y As Integer
        S = 0
        X = 1
        Do While X <= 100
            S = S + X
            lstOutput.Items.Add(S)
            X = X + 3
        Loop
    End Sub
End Class

Problem 3.  Rewrite the following code without ElseIF. The new code should work exactly in the same way as the original one.

If T > 90 Then
   MsgBox("Hot")
ElseIf T < 60 Then
    MsgBox("Cold")
Else
    MsgBox("Nice")
End If

Problem 4.  Assume that variable X has the value of 1.  Write next to each of the following conditions whether it is true or false.

a) X >= 1  AND  X < 1

b) X < 4  OR  X > 4

c) X = 1  AND  X >= 1  AND  X < 7

d) (X > 3  OR  X <= 7)  AND  (X < 0 OR X > 0)
 

Problem 5. Describe all visual objects, procedures and functions used in the following program.

Public Class Form1
     Private Sub btnStart_Click(...) Handles btnStart.Click
        Dim X, P As String, I As Integer
        Dim sr As IO.StreamReader = IO.File.OpenText("M:\data.txt")
        N = 0
        Do While (sr.Peek <> -1)
            X = sr.ReadLine
            lstOutput.Items.Add(X)
            Grade(N) = CInt(X.Substring(0, 2))
            N = N + 1
        Loop
        P = "Unsorted: "
        For I = 0 To N - 1
            P = P & Grade(I) & " "
        Next I
        lstOutput.Items.Add(P)
        Call BubbleSort()
        P = "Sorted: "
        For I = 0 To N - 1
            P = P & Grade(I) & " "
        Next I
        lstOutput.Items.Add(P)
     End Sub

    Public Sub BubbleSort()
        Dim I, Swaps, T As Integer
        Do
            Swaps = 0
            For I = 0 To N - 2
                If Grade(I) > Grade(I + 1) Then
                    T = Grade(I)
                    Grade(I) = Grade(I + 1)
                    Grade(I + 1) = T
                    Swaps = Swaps + 1
                End If
            Next I
        Loop While Swaps > 0
    End Sub
End Class

Problem 6. Write a program that computes the sum of the following sequence of numbers: 1,4,7,10,…, 100. Use a loop.

Problem 7. A store sells CDs at 50 cents for small orders, at 40 cents for orders of 20 to 100, and at 30 cents for orders of more than 100. Write a program that requests the number of CD ordered and prints the total cost.

Problem 8. Complete the sub procedure below so that it prints the smallest of the four numbers passed as parameters.

Public Sub Min4(ByVal A As Double, ByVal B As Double, ByVal C As Double, ByVal D As Double)

End Sub

Problem 9. Write a program that reads 10 integers from user input and prints every other one in a reverse order. Use an array.