CS213 - Applications of Computer Programming

Fall-2003

Classes: TR 5:15 pm - 6:30 pm, Nicolaus Copernicus Hall 22404
Instructor: Dr. Zdravko Markov, MS 203, (860)-832-2711, http://www.cs.ccsu.edu/~markov/, e-mail: markovz@ccsu.edu
Office hours:  TR 8:00pm-9:00pm, MW 5:00pm-6:45pm, or by appointment

Catalog description: Prereq.: MATH 121 or 125 or placement test. This course focuses on the use of programming techniques to solve problems encountered in the areas of mathematics, life science, physical science, engineering, education and social science. Topics include programming, languages with emphasis on FORTRAN and either BASIC or PASCAL, the use of time-shared and batch-oriented computers, and applications of the computer. No credit given to students with credit for CS 151. [c] Mode 2

Prerequisites:  MATH 121 or 125 or placement test.

General description and objectives

This course focuses on the use of programming techniques to solve problems encountered in the areas of mathematics, life science, physical science, engineering, education and social science. The primary programming language taught in CS 213 is Visual Basic .NET.  Students learn to develop graphical user interfaces (GUI’s) for basic types of programs. The main language features taught are the following:

Students will also learn some basic structures of FORTRAN. This will allow them to understand the very idea of programming and to distinct it from the programming language used. Furthermore FORTRAN is a language generally used in many engineering fields.

Finally there will be a class devoted to creating a simple applet in Java.  This will be an example of using a free-form  language (such as Pascal and C) and will illustrate its difference from line-oriented languages such as Basic and FORTRAN.  As the material is presented on an elementary level, no particular textbook is recommended for FORTRAN and Java.

Required textbook: David Schneider, An Introduction to Programming Using Visual Basic .NET, Fifth Edition, Prentice Hall, 2003.

Grading: 40% of the total grade depends on test grades and 60% depends on project grades. The letter grades 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

Honesty policy: It is expected that all students will conduct themselves in an honest manner (see the CCSU Student handbook), 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.

Tentative schedule of classes and assignments (will be updated regularly: classes shown in bold face are already updated)

  1. Introduction to programming by examples in Visual Basic and FORTRAN.
  2. Problem solving by programming.
  3. Visual Basic Programming Environment: Objects (Controls), Events, Event Procedures
  4. Variables, Assignment, Arithmetic Expressions, Built-in Functions, Input, Output.
  5. Data type Double, Data Type conversions (casting), Math functions, String manipulation, More Input and Output (Input box, Message Box).
  6. Relational Expressions, If-Then-Else, ElseIf.
  7. Multiple ElseIf, Select Case.
  8. PROJECT 1 due 9/30, 10 pts.
  9. Do-While/Until-Loops (pre-test loops)
  10. Do-Loop-While/Until (post-test loops)
  11. Counters, Accumulators, Sentinel loops.
  12. TEST 1, 10 pts.
  13. October 16: For-Next Loops, Nested Loops
  14. October 21: PROJECT 2 due, 10 pts. General Sub Procedures, Parameters, Class-level variables
  15. Passing Parameters (ByVal, ByRef), Returning values, Function Procedures.
  16. Scope of variables, Call by reference
  17. PROJECT 3 due, 10 pts. Review of Sub Procedures and Functions: String manipulation
  18. TEST 2, 10 pts.
  19. Recursion. Recursion is not in tests or projects.
  20. FORTRAN: Fortran programming cycle, Read, Assignment, Expressions, Print.
  21. FORTRAN: If-Else-ElseIf, Logical variables.
  22. FORTRAN: Indexed Do loops, Goto, One-line If.
  23. Review of Fortran
  24. 11/25/03: Test 3 (FORTRAN), 10 pts. PROJECT 4 due, 10 pts.
  25. Back to VB: One-Dimensional Arrays.
  26. Sequential Files
  27. Searching Files and Arrays
  28. Sorting - this is not in tests or programs.
  29. Java Applet
  30. TEST 4,  10 pts., PROJECT 5 due, 20 pts

CS213 - Lecture 1

Introduction to Programming by Examples in Visual Basic and FORTRAN

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).
FORTRAN:
1     7
      program Simple
      print*, 5*(31-32)/9
      end

VB:
Private Sub Form_Click()
Print 5*(31-32)/9
End Sub

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

FORTRAN:
1    7                                                          72
     program Tranfroms_Fahrenheit_to_Celcius                    Program header
C Reads the temperature in F and prints the result in C         Comment
* VARIABLES                                                     Comment
     integer F                                                  Declares variable F
     integer C                                                  Declares variable C
     print*, ’Enter the temperature in Fahrenheit’              Prints ’Enter the ...
     read*, F                                                   Typed in value goes in F
     C = 5*(F-32)/9                                             Value of the expression assigned to C
     print*, ’The Celsius temperature is ’, C                   Prints the result
     end                                                        End of program

Sample run:
Enter the temperature in Fahrenheit
0
The Celsius temperature is –17

VB:

Private Sub Form_Click()
  Dim F As Integer
  Dim C As Integer
  F = InputBox("Enter the temperature in Fahrenheit", "Input dialog")
  C = 5*(F-32)/9
  Print C
End Sub

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

0   –17
20  –6
40  4
60  15
...
300 148

FORTRAN:

1    7
     program Fahrenheit_to_Celcius_Table
     integer F
     integer C
     F = 0
     do while (F.le.300)
        C = 5*(F-32)/9
        print*, F,’    ’,C
     end do
     end

VB:

Private Sub Form_Click()
   Dim F As Integer
   Dim C As Integer
   F = 0
   Do While F <= 300
     C = 5*(F-32)/9
     Print F ; ”    ” ; C
   Loop
End Sub


CS213 - Lecture 2

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 FORTRAN)

  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 (e.g. by using the read command) and get the results on the screen (e.g. by the print command).

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. Place a text box on the form. Using the property window set its name to "txtForm1".
  3. Bring up the code window and you'll see the following:

  4.  

     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     

    Public Class Form1

      Inherits System.Windows.Forms.Form

    Windows Form Designer generated code

    Private Sub txtForm1_TextChanged(...) Handles txtForm1.TextChanged

    End Sub
     

  5. Write the following statement before End Sub:

  6.  
      Me.Text = "Hello! This is my first program"
  7. Run the program

CS213 - Lecture 3

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 Text Box to add a Text Box to your form
  2. Activate the Properties window
  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. Examples:

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. Double click on the object to open the Code window.
  4. Click on the Procedure box to find the event
  5. Write the code for that event.

Accessing the object properties

  1. ObjectName.Property accesses Property of ObjectName.
  2. ObjectName.Procedure executes the Procedure associated with Object Name. Example: lstOutput.Items.Add("Hello") will add a line to list box lstOutput.

Example: Using Basic Controls


CS213 - Lecture 4

Variables, Assignment, Arithmetic Expressions, Built-in Functions, Input, Output

Problem: Calculation of age (years and months lived) based on month and year of birth (Current month is 9, year - 2003, MOB is 10, 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 a button and using a list box for output.

Private Sub btnCompute_Click(...) Handles btnCompute.Click
  lstOutput.Items.Add("Years = " & (9 + 2003 * 12 - 10 - 1956 * 12) \ 12)
  lstOutput.Items.Add("Months = " & (9 + 2003 * 12 - 10 - 1956 * 12) mod 12)
End Sub

Solution 2: Using variables and inital values.

Private Sub btnCompute_Click(...) Handles btnCompute.Click
  Dim MOB, YOB, Months, Years, MonthsLived As Integer
  Dim CurrentMonth As Integer = 9
  Dim CurrentYear As Integer = 2003
  MonthsLived = CurrentMonth + CurrentYear * 12 - 10 - 1956 * 12
  Months = MonthsLived Mod 12  ' Remainder from integer division
  Years = MonthsLived \ 12     ' Integer division
  lstOutput.Items.Add("Years = " & Years)
  lstOutput.Items.Add("Months = " & Months)
End Sub

Solution 3: Elaborating the interface - text boxes for input. Converting a string into a number (CInt fuction).

Private Sub btnCompute_Click(...) Handles btnCompute.Click
  Dim MOB, YOB, Months, Years, MonthsLived As Integer
  Dim CurrentMonth As Integer = 9
  Dim CurrentYear As Integer = 2003
  MOB = CInt(txtMonth.Text)      ' Convert string to number
  YOB = CInt(txtYear.Text)
  lstOutput.Items.Clear()        ' Clear output list box
  MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
  Months = MonthsLived Mod 12   ' Remainder from integer division
  Years = MonthsLived \ 12      ' Integer division
  lstOutput.Items.Add("Years = " & Years)
  lstOutput.Items.Add("Months = " & Months)
End Sub

Solution 4: Using labels to explain input and output. Using text boxes for output. Converting integer to string (CStr function)

Private Sub btnCompute_Click(...) Handles btnCompute.Click
  Dim MOB, YOB, Months, Years, MonthsLived As Integer
  Dim CurrentMonth As Integer = 9
  Dim CurrentYear As Integer = 2003
  MOB = CInt(txtMonth.Text)      ' Convert string to number
  YOB = CInt(txtYear.Text)
  txtYears.Text = ""             ' Clear list box Years
  txtMonths.Text = ""            ' Clear list box Months
  MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
  Months = MonthsLived Mod 12   ' Remainder from integer division
  Years = MonthsLived \ 12      ' Integer division
  txtYears.Text = CStr(Years)
  txtMonths.Text = CStr(Months)
End Sub


CS213 - Lecture 5

Data type Double, Type conversions (Casting), Math functions, String manipulation, Input box, Message Box

More solutions to the problem of calculation of age based on month and year of birth (Lecture 4).

Solution 1: Using floating point arithmetic (type double).

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
    Dim MOB, YOB, Months, Years As Integer
    Dim Age As Double
    Dim CurrentMonth As Integer = 9
    Dim CurrentYear As Integer = 2003
    MOB = CInt(txtMonth.Text)           ' Convert string to number
    YOB = CInt(txtYear.Text)
    lstOutput.Items.Clear()             ' Clear output list box
    Age = (CurrentMonth + CurrentYear * 12 - MOB - YOB * 12) / 12
    Years = Int(Age)                   ' Get the integer part
    Months = Int((Age - Years) * 12)   ' Convert monts from fraction to integer
    lstOutput.Items.Add("Years = " & Years)
    lstOutput.Items.Add("Months =" & Months)
End Sub

Solution 2: Using string variable for the output. String concatenation (&)

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
    Dim MOB, YOB, Months, Years, MonthsLived As Integer
    Dim CurrentMonth As Integer = 9
    Dim CurrentYear As Integer = 2003
    Dim Output As String
    MOB = CInt(txtMonth.Text)
    YOB = CInt(txtYear.Text)
    MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
    Months = MonthsLived Mod 12  ' Remainder from integer division
    Years = MonthsLived \ 12     ' Integer division
    Output = "You are " & Years & " years and " & Months & " months old"
    lstOutput.Items.Clear()
    lstOutput.Items.Add(Output)
End Sub

Solution 3: Using interactive Input/Output: Input box, Message box.

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
    Dim MOB, YOB, Months, Years, MonthsLived As Integer
    Dim CurrentMonth As Integer = 9
    Dim CurrentYear As Integer = 2003
    Dim Output As String
    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
    Output = "You are " & Years & " years and " & Months & " months old"
    MsgBox(Output)
End Sub

Math and string built-in functions. String manipulation

Problem 1: Generate random numbers between 1 and 5 and print them as words (one, two, three, four, five)

Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn.Click
    Dim S As String = "one  two  threefour five "
    Dim Pos As Integer
    Pos = (Int(Rnd() * 5)) * 5
    MsgBox(S.Substring(Pos, 5))
End Sub
 

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

Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn.Click
    Dim S As String = "one  two  threefour five "
    Dim Pos, Num As Integer
    Pos = S.IndexOf(InputBox("type a number word"))
    Num = Pos / 5 + 1
    MsgBox(Num)
End Sub

Elaboration 1: Allow both upper and lower case input

Elaboration 2: Extend the input to 9 (nine).


CS213 - Lecture 6

Relational Expressions, If-Then-Else, ElseIf

Problem 1: Calculation of age based on month and year of birth (Lecture 4)

Solution 1:  No input data validation

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
    Dim MOB, YOB, Months, Years, MonthsLived As Integer
    Dim CurrentMonth As Integer = 9
    Dim CurrentYear As Integer = 2003
    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
    MsgBox("You are " & Years & " years and " & Months & " months old")
End Sub

Solution 2:  Data validation: using one If block  (Exercise: invert the condition and exchange the Then and Else clauses)

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
    Dim MOB, YOB, Months, Years, MonthsLived As Integer
    Dim CurrentMonth As Integer = 9
    Dim CurrentYear As Integer = 2003
    MOB = CInt(InputBox("Enter Month of Birth"))
    YOB = CInt(InputBox("Enter Year of Birth"))
    If (MOB>0) And (MOB<13) And (YOB<2003) Then
       MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
       Months = MonthsLived Mod 12  ' Remainder from integer division
       Years = MonthsLived \ 12     ' Integer division
       MsgBox("You are " & Years & " years and " & Months & " months old")
    Else
       MsgBox("Wrong input! Try again.")
    End If
End Sub
 

Solution 3:  More detailed data validation (which is wrong - month or year): Using ElseIf clause.

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
    Dim MOB, YOB, Months, Years, MonthsLived As Integer
    Dim CurrentMonth As Integer = 9
    Dim CurrentYear As Integer = 2003
    MOB = CInt(InputBox("Enter Month of Birth"))
    YOB = CInt(InputBox("Enter Year of Birth"))
    If (MOB<0) Or (MOB>12) Then
       MsgBox("Wrong MOB! Try again.")
    ElseIf YOB > 2003 Then
       MsgBox("Wrong YOB! Try again.")
    Else
       MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
       Months = MonthsLived Mod 12  ' Remainder from integer division
       Years = MonthsLived \ 12     ' Integer division
       MsgBox("You are " & Years & " years and " & Months & " months old")
    End If
End Sub

Problem 2: Read and validate the type of a numeric input. (try: "5", "3.14", "123E-1", "xyz", "").

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
    Dim S As String, N As Integer, X As Double
    S = txtInput.Text
    N = CInt(S)
    X = CDbl(S)
    MsgBox("Integer value = " & N & ", Double value = " & X)
End Sub

Solution 1: Avoid the system interrupt: check the first character in the input string (partial solution, try "1xy").

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
    Dim S As String, N As Integer, X As Double
    X = txtInput.Text
    If S = "" Then
        MsgBox("Empty String")
    ElseIf Asc(S) < Asc("0") Or Asc(S) > Asc("9") Then
        MsgBox("Non-numeric input")
    Else
        N = CInt(S)
        X = CDbl(S)
        MsgBox("Integer value = " & N & ", Double value = " & X)
    End If
End Sub

Solution 2: Use the IsNumeric built-in function.

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
    Dim S As String, N As Integer, X As Double
    S = txtInput.Text
    If IsNumeric(S) Then
        N = CInt(S)
        X = CDbl(S)
        MsgBox("Integer value = " & N & ", Double value = " & X)
    Else
        MsgBox("Non-numeric input")
    End If
End Sub

Exercise: Extend the age computation program (Solution 3 to Problem 1, this Lecture) with input type validation.


CS213 - Lecture 7

Multiple ElseIf, Select Case

Problem: Implement a simple calculator using the following VB objects:
  1. For Input: Text Boxes: txtOperand1, txtOperand2, txtOperation;
  2. Button: btnCalculate (Text: Calculate);
  3. For Output: txtResult
Operand1 and Operand1 are numeric values (of type Double) and Operation (of type String) is one of following: "+", "-", "*", "/", "\", "mod". When you press the btnCalculate button the result of computing the expression <Operand1> <Operation> <Operand2> must be displayed in txtResult. If incorrect data are entered the program should print a message on a Message Box.

Solution 1: Using If block with multiple ElseIf clause

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
        Dim X, Y, R As Double
        Dim Op As String
        X = CDbl(txtOperand1.Text)
        Y = CDbl(txtOperand2.Text)
        Op = txtOperation.Text

        If Op = "+" Then
            txtResult.Text = X + Y
        ElseIf Op = "-" Then
            txtResult.Text = X - Y
        ElseIf Op = "*" Then
            txtResult.Text = X * Y
        ElseIf Op = "/" Then
            If Y <> 0 Then
                txtResult.Text = X / Y
            Else
                MsgBox("Division by 0")
            End If
        ElseIf Op = "\" Then
            If Y <> 0 Then
                txtResult.Text = X \ Y
            Else
                MsgBox("Division by 0")
            End If
        ElseIf Op = "mod" Then
            txtResult.Text = X Mod Y
        Else
            MsgBox("Incorrect operation")
        End If
End Sub

Elaboration: Use the IsNumeric function to validate the numeric input.

Solution 2: Using Select Case structure

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
        Dim X, Y, R As Double
        Dim Op As String
        X = CDbl(txtOperand1.Text)
        Y = CDbl(txtOperand2.Text)
        Op = txtOperation.Text

        Select Case Op
            Case "+"
                txtResult.Text = X + Y
            Case "-"
                txtResult.Text = X - Y
            Case "*"
                txtResult.Text = X * Y
            Case "/"
                If Y <> 0 Then
                    txtResult.Text = X / Y
                Else
                    MsgBox("Division by 0")
                End If
            Case "\"
                If Y <> 0 Then
                    txtResult.Text = X \ Y
                Else
                    MsgBox("Division by 0")
                End If
            Case "mod"
                txtResult.Text = X Mod Y
            Case Else
                MsgBox("Incorrect operation")
        End Select
End Sub


CS213 - Lecture 8

Do-While/Until-Loops (pre-test loop)

Fixed-count loop - the number of repetitions is known in advance

Problem 1: Print Fahrenheit to Celsius conversion table for 0, 10, 20, ..., 90, 100.

Solution:

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

Scientific Computation

Problem 2: Sum of series (investigating limits). Compute the sum of the series 1+1/2+1/4+...+1/N, for different N's. Is there an upper bound for the sum? What about the series 1/(N^2) ?

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
    Dim N As Integer, Sum As Double = 0
    Dim I As Integer = 1
    N = InputBox("Number of iterations?")
    lstOutput.Items.Clear()
    Do While I < N
        Sum = Sum + 1 / I
        lstOutput.Items.Add(I & "   " & Sum)
        I = I + 1
    Loop
End Sub

Elaboration 1: Print the sum in increments. Enclose lstOutput.Items.Add(I & "   " & Sum) in an If block:

    If I Mod 100 = 0 Then
        lstOutput.Items.Add(I & "   " & Sum)
    End If

Elaboration 2: Use an input parameter for the printing increment.
 

Problem 3: Calculating the base of the natural logarithm – the number e. For a discussion of e see http://mathworld.wolfram.com/e.html.

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
    Dim N As Integer, Eu As Double = 1.0
    Dim I As Integer = 1
    N = InputBox("Number of iterations?")
    Do While I < N
        Eu = Eu * (1 + 1 / N)
        I = I + 1
    Loop
    MsgBox("Eu = " & Eu)
End Sub
 

Variable-condition loop - the number of repetitions is NOT known in advance

Problem 4: 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.

Solution 1: (Change Do While with Do Until, See comment 2 on page 249)

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
    Dim X, Y, T As Integer
    X = CInt(InputBox("Enter First Integer"))
    Y = CInt(InputBox("Enter Second Integer"))
    Do While Y > 0   'Do Until Y = 0
        T = X Mod Y
        X = Y
        Y = T
    Loop
    MsgBox("The GCD is " & X)
End Sub

Solution 2: Preserving the input values

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
    Dim A, B As Integer
    Dim X, Y, T As Integer
    A = CInt(InputBox("Enter First Integer"))
    B = CInt(InputBox("Enter Second Integer"))
    X = A
    Y = B
    Do While Y > 0
        T = X Mod Y
        X = Y
        Y = T
    Loop
    MsgBox("The GCD of " & A & " and " & B & " is " & X)
End Sub

Problem 5 (Exercises 6.1: 25). Assume that the world population is growing 1.2 percent each year. When will the population exceed 10 bilion (now it is 6.2 bilion)?

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
    Dim P As Double = 6.2
    Dim N As Integer = 0
    Do Until P > 10
        N = N + 1
        P = P + P * 0.012
    Loop
    MsgBox("The population will reach 10 bilion in " & N & " years")
End Sub


CS213 - Lecture 9

Do-Loop-While/Until (post-test loop)

Repetition structures:  post-test loops (Do Loop Until/While)

Problem 1: Print a sequence of random numbers (are they really random?). Try Second(Now()) instead of Rnd().

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim S As String
        S = ""
        Do
            S = S & Rnd() & ", "
        Loop Until S.Length > 60
        lstOutput.Items.Add(S)
End Sub

Problem 2: Implement a guessing game

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

Problem 3: Implement the version of the Euclid's algorithm based on subtraction. The basic idea is the following: to find the GCD of two numbers by this algorithm,  repeatedly replace the larger by subtracting the smaller from it until the two numbers are equal. For example: 132, 168 -> 132, 36 -> 96, 36 -> 60, 36 -> 24, 36 -> 24, 12 -> 12, 12 so the GCD of 132 and 168 is 12. This implementation of GCD is based on the fact that gcd(a, b) = gcd(a-b, b).

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 = CInt(InputBox("Enter First Integer"))
        B = CInt(InputBox("Enter Second Integer"))
        X = A
        Y = B
        Do
            If X < Y Then
                Y = Y - X
            ElseIf Y < X Then
                X = X - Y
            Else
            End If
        Loop Until X = Y
        MsgBox("The GCD of " & A & " and " & B & " is " & X)
End Sub


CS213 - Lecture 10

Counters, Accumulators, Sentinel loops

Problem 1: Counting, totaling, averaging a sequence of numbers

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim Number, Average As Double
        Dim Total As Double = 0
        Dim Count As Integer = 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

Problem 2: Computing the distribution of a series of random numbers.

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim X As Double, N As Integer
        Dim C1 As Integer = 0
        Dim C2 As Integer = 0
        Dim C3 As Integer = 0
        Dim C4 As Integer = 0
        N = CInt(InputBox("How many random numbers?"))
        Do While C1 + C2 + C3 + C4 < N
            X = Rnd()
            Select Case X
                Case 0.0 To 0.25
                    C1 = C1 + 1
                Case 0.25 To 0.5
                    C2 = C2 + 1
                Case 0.5 To 0.75
                    C3 = C3 + 1
                Case Else
                    C4 = C4 + 1
            End Select
        Loop
        lstOutput.Items.Clear()
        lstOutput.Items.Add("[0.00, 0.25]:" & C1 * 100 / N)
        lstOutput.Items.Add("[0.25, 0.50]:" & C2 * 100 / N)
        lstOutput.Items.Add("[0.50, 0.75]:" & C3 * 100 / N)
        lstOutput.Items.Add("[0.75, 1.00]:" & C4 * 100 / N)
    End Sub

Elaboration: Plot the distribution as a bar diagram. Use a string variable to plot the bars. Add S to Dim as String and replace the output to the list box with the following code.

        C1 = C1 * 100 / N
        S = ""
        Do While C1 > 0
            S = S & "|"
            C1 = C1 - 1
        Loop
        lstOutput.Items.Add("[0.00, 0.25]:" & S)
        C2 = C2 * 100 / N
        S = ""
        Do While C2 > 0
            S = S & "|"
            C2 = C2 - 1
        Loop
        lstOutput.Items.Add("[0.25, 0.50]:" & S)
        C3 = C3 * 100 / N
        S = ""
        Do While C3 > 0
            S = S & "|"
            C3 = C3 - 1
        Loop
        lstOutput.Items.Add("[0.50, 0.75]:" & S)
        C4 = C4 * 100 / N
        S = ""
        Do While C4 > 0
            S = S & "|"
            C4 = C4 - 1
        Loop
        lstOutput.Items.Add("[0.75, 1.00]:" & S)
 


CS213 - Lecture 11

For-Next Loops, Nested Loops

Fixed-count loops (For-Next Loop)

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

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 Integer
        N = InputBox("How many iterations?")
        M = 0
        For I = 1 To N
            X = Rnd()
            Y = Rnd()
            If X * X + Y * Y < 1 Then M = M + 1
        Next I
        MsgBox(4 * M / N)
    End Sub

Nested Loops

Problem 2: Print a table of approximation of PI

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, Delta, Max As Integer
        Max = InputBox("Max number of iterations?")
        Delta = InputBox("Interval beteen approximations?")
        lstOutput.Items.Clear()
        For N = Delta To Max Step Delta
            M = 0
            For I = 1 To N
                X = Rnd()
                Y = Rnd()
                If X * X + Y * Y < 1 Then M = M + 1
            Next I
            lstOutput.Items.Add(N & Chr(9) & 4 * M / N)
        Next N
End Sub

Elaboration 2: Use one For-Next loop and print the approximations of Pi in intervals using the Mod operation (see elaboration 1, Lecture 8).

Problem 3: 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.

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim N, I, Limit, Delta, Pi As Integer
        Dim Prime As Boolean
        Limit = InputBox("Enter the limit")
        Delta = InputBox("Enter the step")
        lstOutput.Items.Clear()
        lstOutput.Items.Add("N" & Chr(9) & Chr(9) & "Pi(N)")
        Pi = 0
        For N = 2 To Limit
            Prime = True
            I = 2
            Do While (I <= N / 2) And Prime
                If (N Mod I = 0) Then Prime = False
                I = I + 1
            Loop
            If Prime Then Pi = Pi + 1
            If N Mod Delta = 0 Then
                lstOutput.Items.Add(N & Chr(9) & Chr(9) & Pi)
            End If
        Next N
    End Sub


CS213 - Lecture 12

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

Problem 1: Avoid repeating the code for plotting the distribution as a bar diagram in the Elaboration of Lecture 10.

    Sub Plot(ByVal C As Integer, ByVal N As Integer)
        Dim S As String
        C = C * 100 / N
        S = ""
        Do While C > 0
            S = S & "|"
            C = C - 1
        Loop
        lstOutput.Items.Add(S)
    End Sub

Elaboration: Use a class-level variable for N

Problem 2: Calculation of the monthly payment for a loan with validation of the input.

Solution 1: No sub procedures used

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim Amount As Double    ' Amount of loan in Dollars
        Dim Time As Double      ' Length of loan in Years
        Dim Rate As Double      ' Annual percentage rate in %
        Dim Payment As Double

        REM Reading the input
        Amount = CDbl(txtAmount.Text)
        Time = CDbl(txtTime.Text)
        Rate = CDbl(txtRate.Text)

        REM Input data validation
        If Amount < 1000 Or Amount > 50000 Then
            MsgBox("Wrong Amount (must be between 1000 and 50000)")
        ElseIf Time < 1 Or Time > 10 Then
            MsgBox("Wrong Length (must be between 1 and 10)")
        ElseIf Rate < 1 Or Rate > 25 Then
            MsgBox("Wrong Rate (must be between 0 and 25)")
        Else

            REM Data are OK -> compute Payment
            Time = Time * 12
            Rate = Rate / 1200
            If Rate = 0 Then
                Payment = Amount / Time
            Else
                Payment = (Amount * Rate) / (1 - (1 + Rate) ^ -Time)
            End If

            MsgBox(" The monthly payment is: " & Payment)
    End If

Solution 2: Using a Sub procedure for input data validation and printing a message in the event of wrong input

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim Amount As Double    ' Amount of loan in Dollars
        Dim Time As Double      ' Length of loan in Years
        Dim Rate As Double      ' Annual percentage rate in %
        Dim Payment As Double

        REM Reading the input
        Amount = CDbl(txtAmount.Text)
        Time = CDbl(txtTime.Text)
        Rate = CDbl(txtRate.Text)

        REM Input data validation
        Check("Amount", Amount, 1000, 50000)
        Check("Length", Time, 1, 10)
        Check("Annual rate", Rate, 0, 25)

        Time = Time * 12
        Rate = Rate / 1200
        If Rate = 0 Then
            Payment = Amount / Time
        Else
            Payment = (Amount * Rate) / (1 - (1 + Rate) ^ -Time)
        End If

        MsgBox(" The monthly payment is: " & Payment)

    End Sub

    Sub Check(ByVal Name As String, ByVal Val As Single, ByVal A As Single, ByVal B As Single)
        If Val < A Or Val > B Then
            MsgBox("Wrong " & Name & " (must be between " & A & " and " & B & ")")
        End If
    End Sub

Solution 3: Using a Sub procedure for input data validation and a global variable for signaling input data error

    Dim InputOK As Boolean   ' Class-level (Global) variable for signaling input data error

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim Amount As Double    ' Amount of loan in Dollars
        Dim Time As Double      ' Length of loan in Years
        Dim Rate As Double      ' Annual percentage rate in %
        Dim Payment As Double

        REM Reading the input
        Amount = CDbl(txtAmount.Text)
        Time = CDbl(txtTime.Text)
        Rate = CDbl(txtRate.Text)

        REM Input data validation
        InputOK = True
        Check("Amount", Amount, 1000, 50000)
        Check("Length", Time, 1, 10)
        Check("Annual rate", Rate, 0, 25)

        If InputOK Then
            Time = Time * 12
            Rate = Rate / 1200
            If Rate = 0 Then
                Payment = Amount / Time
            Else
                Payment = (Amount * Rate) / (1 - (1 + Rate) ^ -Time)
            End If
            MsgBox(" The monthly payment is: " & Payment)
        End If

    End Sub

    Sub Check(ByVal Name As String, ByVal Val As Single, ByVal A As Single, ByVal B As Single)
        If Val < A Or Val > B Then
            InputOK = False
            MsgBox("Wrong " & Name & " (must be between " & A & " and " & B & ")")
        End If
    End Sub

Elaboration 1:
Problem: What happens if the input for Rate is non-numeric, e.g. Text3?
Solution: Pass the input string to the Check procedure and check whether it is numeric using the IsNumeric built-in function.

Elaboration 1: Use a general procedure to calculate the payment


CS213 - Lecture 13

Passing parameters, Returning values, Function Procedures

Problem: Find the maximum of three numbers

Solution 1: No sub procedures

    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 is: " & Max)
    End Sub

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

    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 = ?")
        Max2(X, Y)    ' Max is the maximum of X and Y
        Max2(Max, Z)  ' Max is the maximum of Max and Z
        MsgBox("The maximum is: " & Max)
    End Sub
    Sub Max2(ByVal A As Single, ByVal B As Single) ' Return maximum in global variable Max
        If A > B Then
            Max = A
        Else
            Max = B
        End If
    End Sub

Solution 3: Returning values through a parameter. Why do we need ByRef? (Try first with ByVal C As Double.)

    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 = ?")
        Max2(X, Y, Max)    ' Max is the maximum of X and Y
        Max2(Max, Z, Max)  ' Max is the maximum of Max and Z
        MsgBox("The maximum is: " & Max)
    End Sub
    Sub Max2(ByVal A As Double, ByVal B Double, ByRef C As Double) ' Return maximum in parameter C
        If A > B Then
            C = A
        Else
            C = B
        End If
    End Sub

Solution 4: Using function procedure

    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 = ?")
        Max = Max2(X, Y)   ' Max is the maximum of X and Y
        Max = Max2(Max, Z) ' Max is the maximum of Max and Z
        MsgBox("The maximum is: " & Max)
    End Sub
    Function Max2(ByVal A As Double, ByVal B As Double) As Double ' Note that there is a type definition here
        If A > B Then
            Return A   ' Alternative syntax is Max2 = A
        Else
            Return B   ' Alternative syntax is Max2 = B
        End If
    End Function

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?)

CS213 - Lecture 14

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

Solution: Using Call by Value

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim A As Integer, B As Integer, D As Integer
        A = InputBox("A = ?")
        B = InputBox("B = ?")
        D = GCD(A, B)
        MsgBox("The GCD of " & A & " and " & B & " is " & D)
    End Sub
    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
        Return X
    End Function

Question: Use 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?)

Problem 2: Compute (A/B)+(C/D)=(Num/Den) in rational numbers (fractions). Simplify the result by using GCD, i.e. Num=Num/GCD(Num,Den); Den=Den/GCD(Num,Den).

Solution: Find and fix the bugs in the following program.

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim A, B, C, D, Num, Den As Integer
        A = InputBox("Enter first numerator")
        B = InputBox("Enter first denominator")
        C = InputBox("Enter second numerator")
        D = InputBox("Enter second denominator")
        Call AddFractions(A, B, C, D, Num, Den)
        MsgBox(A & "/" & B & " + " & C & "/" & D & " = " & Num & "/" & Den)
    End Sub
    ' U/V + W/X = Y/Z
    Sub AddFractions(ByVal U As Integer, ByVal V As Integer, ByVal W As Integer, ByVal X As Integer, ByVal Y As Integer, ByVal Z As Integer)
        Y = U * X + W * V
        Z = V * X
        Y = Y / GCD(Y, Z)
        Z = Z / GCD(Y, Z)
   End Sub

    Function GCD(ByVal N As Integer, ByVal M As Integer) As Integer
        Dim R As Integer
        Do While M > 0
            R = N Mod M
            N = M
            M = R
        Loop
        Return N
    End Function


CS213 - Lecture 15

Review of Sub Procedures and Functions: String manipulation

Problem 1: 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:

        Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
    Dim Line, W As String, N As Integer
        Line = txtInput.Text
        lstOutput.Items.Clear()
        N = 0
        Do
            W = Word(Line)
            If W <> "" Then
                If IsNumeric(W) Then
                    lstOutput.Items.Add(W & Chr(9) & "number")
                Else
                    lstOutput.Items.Add(W & Chr(9) & "string")
                End If
                N = N + 1
            End If
        Loop While W <> ""
        lstOutput.Items.Add("__________________")
        lstOutput.Items.Add(N & " words")
    End Sub

    'Returns and removes the first word from S (S is passed by reference, the function changes it).
    Function Word(ByRef S As String) As String
        Dim L As Integer, I As Integer
        S = S.Trim()                ' Trim the leading blanks (if any)
        L = S.Length                ' L is the length of S
        If L = 0 Then               ' If no more charachters in S Then
            Return ""               ' return empty string
        Else                        ' Else (S is not empty) do the following:
            I = S.IndexOf(" ")               ' I = the position of the first blank
            If I >= 0 Then                   ' If I>=0 (there is a blank in S) Then
                Word = S.Substring(0, I)        ' return the word before the blank and
                S = S.Substring(I, L - I)       ' 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


CS213 - Lecture 16

Recursion

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

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
   MsgBox(Fact(5))    ' This should print 120
End Sub

Solution 1: Factorial (iterative)

Function Fact(ByVal 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
  Retrun F
End Function

Solution 2: Factorial (recursive)

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

Problem 2: 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 btnstart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnstart.Click
  Dim S1 As String, S2 As String
  S1 = InputBox("Enter string")
  S2 = InputBox("Enter another string")
  MsgBox(S1 & " is greater than " & S2 & " is " & greater(S1,S2))
End Sub

Solution 1 (non-recursive):

Public Function greater(ByVal X As String, ByVal 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
    Return False
  ElseIf I > N Then
    Return True
  Else
    Return 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
     Return False
  ElseIf Y = "" Then
     Return True
  ElseIf Mid(X, 1, 1) <> Mid(Y, 1, 1) Then
     Return 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)
     Return greater(X, Y)
  End If
End Function


CS213 - Lecture 27

Searching Files and Arrays

Problem 1: Implement a line-oriented text editor with three commands: list, line #n (edit line #n) and quit.

    Private Sub Button1_Click(...) Handles Button1.Click
        Dim Filename As String
        Dim sw As IO.StreamWriter
        Dim sr As IO.StreamReader
        Dim Line(100) As String
        Dim Opt As String
        Dim I, N As Integer

        Filename = InputBox("Enter the file name")

        ' Read the file into the array, N holds the number of lines
        sr = IO.File.OpenText(Filename)
        N = 0
        Do While sr.Peek <> -1
            N = N + 1
            Line(N) = sr.ReadLine
        Loop
        sr.Close()

        Do
            Opt = InputBox("Enter an option (list, line#, quit)")
            lstOutput.Items.Clear()
            Select Case Opt
                Case "list"
                    For I = 1 To N
                        lstOutput.Items.Add(Line(I))
                    Next I
                Case "quit"
                    MsgBox("Good Bye")
                Case 1 To N
                    Line(Opt) = InputBox("Type the new contents of line " & Opt & ": " & Line(Opt))
                Case Else
                    MsgBox("Unknown option")
            End Select
        Loop Until Opt = "quit"

        ' Write the array into the file
        sw = IO.File.CreateText(Filename)
        For I = 1 To N
            sw.WriteLine(Line(I))
        Next I
        sw.Close()

    End Sub
 

Problem 2: Search a text file with grades and student names. Given a name or a part of it the program must print all matching students and their grades.

Example of a file contents:

90 John Smith
80 Al Clark
55 Sue Taylor
75 Ann Miller
A search for names with "A" must produce:
Al Clark      80
Ann Miller    75


Solution 1: Using the file directly (Questions: what about searching an empty string? What if name is first, grade next?)

    Private Sub Button1_Click(...) Handles Button1.Click
        Dim Filename, Line As String
        Dim sr As IO.StreamReader
        Dim Search As String
        Dim Name As String
        Dim Grade As Integer

        Filename = InputBox("Enter the file name")
        Search = InputBox("Enter name to search")

        sr = IO.File.OpenText(Filename)
        lstOutput.Items.Clear()
        Do While sr.Peek <> -1
            Line = sr.ReadLine
            Grade = CInt(Line.Substring(0, 2))
            Name = Line.Substring(2)
            If Name.IndexOf(Search) >= 0 Then lstOutput.Items.Add(Name & "  " & Grade)
        Loop
        sr.Close()

    End Sub
 

Solution 2: Reading the file into two arrays and performing the search in the arrays.

    Private Sub Button1_Click(...) Handles Button1.Click
        Dim Filename, Line As String
        Dim sr As IO.StreamReader
        Dim Search As String
        Dim Name(100) As String
        Dim Grade(100) As Integer
        Dim I, N As Integer

        Filename = InputBox("Enter the file name")

        sr = IO.File.OpenText(Filename)
        N = 0
        Do While sr.Peek <> -1
            N = N + 1
            Line = sr.ReadLine
            Grade(N) = CInt(Line.Substring(0, 2))
            Name(N) = Line.Substring(2)
        Loop
        sr.Close()

        Do
            Search = InputBox("Enter name to search (quit to exit the program)")
            lstOutput.Items.Clear()
            For I = 1 To N
                If Name(I).IndexOf(Search) >= 0 Then lstOutput.Items.Add(Name(I) & "  " & Grade(I))
            Next
        Loop Until Search = "quit"

    End Sub
 

Elaboration: Searching by grades.


CS213 - Lecture 28

Sorting student grades/records by selection sort

Using a text file with grades

    Dim Grade(100) As Integer
    Dim N As Integer

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim Filename As String
        Dim sr As IO.StreamReader
        Dim I As Integer

        Filename = InputBox("Enter the file name")

        sr = IO.File.OpenText(Filename)
        N = 0
        Do While sr.Peek <> -1
            N = N + 1
            Grade(N) = CInt(sr.ReadLine)
        Loop
        sr.Close()
        lstOutput.Items.Clear()
        lstOutput.Items.Add("Input: ")
        For I = 1 To N
            lstOutput.Items.Add(Grade(I))
        Next

        Sort()

        lstOutput.Items.Add("Sorted: ")

        For I = 1 To N
            lstOutput.Items.Add(Grade(I))
        Next
    End Sub

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

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

Elaboration 1: Use a text file with student records - grade and name.

Elaboration 2: Sorting files - write back the sorted records on the file.


PROJECT 1 (10 pts., due 9/30)

Description: The program asks the user for the month and year of his/her birth (by using two separate Text Boxes or Input Boxes).  Then it compares these with the current month and year (variables initialized in the program).  The program then prints "You are a senior" if over age 65, "You are a kid" if under age 18, and "You are an adult" otherwise. Exception: If the birth month is the current month, then the program just prints the words of the Happy Birthday song (4 lines). Use a Message Box or List Box for the output. The program should also validate the input if it's numeric (use the IsNumeric function) and if it's within the allowed range for months and years, and prompt the user in case of invalid input (use a Message Box).

To implement the program use either If Blocks with ElseIf clause or Select Case structure.

Documentation and submission: Compile and run your project and if it works as described above print just the code (copy/paste the contents of the code window into a text editor, as MS Word, and print it) and hand it in class. You may also e-mail the code (only) as a text file attachment. Do not forget to add your name in the beginning of the code as a comment (with Rem or '). Add also comments to explain how the code works. Note that comments and the way you format your program (follow the program format used in the book) will be graded too.


PROJECT 2 (10 pts., due 10/21)

Description: The program asks the user how many test grades will be entered.  The program then asks the user for a sequence of that many integers, each a test grade (use an Input Box to enter each one).  The program then tells how many test grades were Excellent (more than 89) and what their total and average are.  It also tells the same two answers for the Failure  grades (under 60) and the Okay grades (those in-between).

EXAMPLE: Your output should look like the one below when the inputs are 3 followed by 90, 45, 93:

There were 2 excellent grades, totaling 183, average 91.5
There were 0 okay grades, totaling 0, average 0
There were 1 failure grades, totaling 45, average 45

RESTRICTIONS HEREAFTER: Use Input Box for entering data, List Box for the output, and DO-LOOP-WHILE  for reading and processing grades. Use descriptive variable names.  Put a comment at the top of the program giving your name, the date done, and a 2 to 4 line description of the program. Include other comment in the code.

DOCUMENTATION AND SUBMISSION: Compile and run your project and if it works as described above print just the code (copy/paste the contents of the code window into a text editor, as MS Word, and print it) and hand it in class. You may also e-mail the code (only) as a text file attachment. Do not forget to add your name in the beginning of the code as a comment (with Rem or '). Add also comments to explain how the code works. Note that comments and the way you format your program (follow the program format used in the book) will be graded too.


PROJECT 3 (10 pts., due class #17)

Description: Find the sum A/B=1+1/2+1/3+...+1/N as a rational number (fraction). The program must first input N (by using an Input Box) and then print A and B separated by a slash in a Message Box. For example, if we enter 5 for N the program should print 137/60.

RESTRICTIONS HEREAFTER:

  1. Use a FOR-NEXT loop.
  2. Define and use a general sub procedure AddFractions to find the sum of two fractions (see Lecture 14).
  3. Define and use a function procedure GCD to compute the greatest common divisor of two numbers (see Lecture 14).
Extra credit (5pts.): Implement a version of the Euclid's algorithm to find the Greatest Common Divisor (GCD) of two integers based on subtraction (the version from Lecture 8 uses the "mod" operation). The basic idea is the following: to find the GCD of two numbers repeatedly replace the larger by subtracting the smaller from it until the two numbers become equal. For example: Given 132 and 168, first replace 168 (the maximum of the two) by 36 (168-132), then continue with 132 and 36. Repeat the same and get  96 and 36, 60 and 36, 24 and 36, 24 and 12, 12 and 12, stop at this point because the two numbers are equal. So, the GCD of 132 and 168 is 12. Use the new version of GCD in the program for computing the rational sum of 1+1/2+...+1/N.

DOCUMENTATION AND SUBMISSION: Compile and run your project and if it works as described above print just the code (copy/paste the contents of the code window into a text editor, as MS Word, and print it) and hand it in class. You may also e-mail the code (only) as a text file attachment. Do not forget to add your name in the beginning of the code as a comment (with Rem or '). Add also comments to explain how the code works. Note that comments and the way you format your program (follow the program format used in the book) will be graded too.


PROJECT 4 (10 pts., due class #24)

Description: Do Project 2 however in FORTRAN. Follow all requirements of Project 2 and: Extra credit (5pts.): Implement a second version of the same program where the loop is implemented by using GOTO statements, i.e. without a DO statement.

Documentation and submission: Compile and run your project using the FORTRAN Applet and if it works as required print the source code and hand it in class. You can also e-mail this as a text file attachment. To get the extra credit both versions of the program (with and without a DO statement) must be submitted.


PROJECT 5 (20 pts., due class #30)

Write a program in Visual Basic to read a text file containing grades (integer numbers between 0 and 100) and student names (see the example in Problem 2, Lecture 27). The number of records (lines) in this file is not given in advance (the program must use the peek method to detect the end of the file). The program first asks for the file name (using an InputBox), then opens it and reads its content into two arrays - one for student names and another for grades.

After reading the file the program offers a menu with 8 options and waits for the user to enter an option number (using an InputBox). Depending on the number entered the program performs the required operation. If a non-existing option is entered the program issues a proper message and returns to the list of options. The options are:

1. Print all student records (name and grade)
2. Print the records with excellent grades
3. Print the records with ok grades
4. Print the records with failure grades
5. Print the record with maximal grade
6. Print the record with minimal grade
7. Find the records with a given student name (full name must be specified)
8. Find the records with a given grade
9. Exit

If there are no records meeting the search criterion, then the program prints "No records found".

Testing and documentation: The program must be tested by supplying a text file with student records and by checking each one of the 9 options. Submit both the code of the program with comments describing its logic and the file with student records used for testing.

Hints: Use the following model programs:

Extra credit (maximum 5 pts.): Extend the program with the following features:

TEST 1 (10 pts.)

Review topics

  1. Basic visual objects (text box, button, list box, input box, message box), accessing their properties from within the code.
  2. Event procedures: associating code to visual objects.
  3. Input/Output using text boxes, list boxes, message boxes. See Lecture 3.
  4. Arithmetic expressions, integer arithmetic (\, mod). See Lecture 4.
  5. Variable types: Integer, Double, String, type conversion on assignment, using conversion functions (CInt, CDbl). See Lecture 5.
  6. String concatenation (&), strings functions (Substring, IndexOf). See Lecture 5.
  7. Relational expressions: arithmetic comparisons and logic operations.
  8. If Blocks, If-Then-Else structures
  9. If-Then-ElseIf structures
  10. Multiple ElseIf and Select Case structures

Example problems

1. Let X and Y be integer variables and X=26 and Y=4. What should be included in the parentheses of  ListBox1.Items.Add()  in order to get the following in the List box:

  The integer result of dividing 26 by 4 is 6 and the remainder is 2

Note that the parameter of the Add() function should include the X and Y variables, but not any constant (such as 26, 4, 6 and 2).
 

2. What would the code below print in ListBox1 assuming that Text1 and Text2 contain 3.14 and 10.5 respectively? Explain your answer.

  Dim X As Integer, Y As Double
  X = CInt(Text1.Text)
  Y = CInt(Text2.Text)
  ListBox1.Items.Add(X + Y)

3. Are there values for X and Y such that the following code prints "OK" in the message box?

    If X > Y Or X > 0 Then
      X = Y
  End If
  If X < Y Then
     MsgBox("OK")
  End If

4. Rewrite the following code using an IF-Then-Else structure. What is the purpose of this code?

     If X > Y Then
        M = X
     End If
     If X < Y Then
        M = Y
     End If
     If X = Y Then
        M = X
     End If
 

5. Rewrite the following code using IF-Then structures only (without ElseIf)

     If X >= Y And X >= Z Then
        V = X
     ElseIf X >= Y Then
        V = Z
     ElseIf Y >= Z Then
        V = Y
     Else
        V = Z
     End If

6. Rewrite the following code using logical operators in the conditions to avoid the nested If's.

     If X > Y Then
        If X > Z Then
           V = X
        End If
        If Z > X Then
           V = Z
        End If
        V = Y
     End If


TEST 2 (10 pts.)

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.

    Private Sub btnStart_Click(...) 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("Radius = " & R)
          MsgBox("Height = " & H)
          MsgBox("Volume of the cylinder = " & V)
       Else
          MsgBox("Incorrect input. Try again")
       End If
    End Sub
     

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

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

    Private Sub btnStart_Click(...) 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 = Int(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
     

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

  6. Problem: Print the exact squares between 10 and 100. Use For-Next loop.

    Private Sub btnStart_Click(...) Handles btnStart.Click
       Dim I As Integer, S As Double
       For I = 10 To 100
         S = Math.Sqrt(I)
         If S = Int(S) Then
            lstBox.Items(I & " = " & S & "^ 2")
       Next I
    End Sub
     

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

  8. Problem: Input 10 words using InputBox and count the strings and numbers.

    Private Sub btnStart_Click(...) Handles btnStart.Click
       Dim W As String
       Dim I, StrCount, NumCount As Integer
       StrCount = 0
       NumCount = 0
       For I = 1 To 10
         W = InputBox("Enter a word")
         If IsNumeric(W) Then
            NumCount = NumCount + 1
         Else
            StrCount = StrCount + 1
         End If
       Next I
       MsgBox(StrCount & " strings")
       MsgBox(NumCount & " numbers")
    End Sub
     

  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.

    Private Sub btnStart_Click(...) 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

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].

Private Sub btnStart_Click(...) Handles btnStart.Click
   Dim I As Integer, S As Double
   For I = 1 To 100
     S = I/3
     If S = Int(S) Then
       lstOutput.Items.Add(I)
     End If
   Next I
End Sub

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 words are entered. Use the same type of loop.

Private Sub btnStart_Click(...) Handles btnStart.Click
   Dim W As String
   Dim StrCount, NumCount As Integer
   StrCount = 0
   NumCount = 0
   Do
     W = InputBox("Enter a word")
     If IsNumeric(W) Then
        NumCount = NumCount + 1
     Else
        StrCount = StrCount + 1
     End If
   Loop While W <> "end"
   MsgBox(StrCount & " strings")
   MsgBox(NumCount & " numbers")
End Sub

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

a)  1.5                        b)  2                        c) 3                          c) nothing (goes into infinite loop)
Private Sub btnStart_Click(...) 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


TEST 3 (10 pts.)

Review topics

  1. Arithmetic expressions, integer arithmetic (mod), Variable types and assignment.
  2. If-Then-Else-ElseIf structures, Relational expressions.
  3. Using Goto to implement loops
  4. Indexed Do loop

Example problems

Problem 1: Compute the volume of a cylinder.

        program cylinder
        real R, H, V
        print*, 'Enter Radius'
        read*,R
        print*, 'Enter Height'
        read*,H
        V = 3.141592 * R * R * H
        print*, 'Radius = ', R
        print*, 'Height = ', H
        print*, 'Volume of the cylinder = ', V
        end

Problem 2:  Same as problem 1 plus input verification.

        program cylinder
        real R, H, V
1       print*, 'Enter Radius'
        read*,R
        if (R.LE.0) then
            print*, 'Wrong input: a positive number needed'
            goto 1
        end if
2       print*, 'Enter Height'
        read*,H
        if (H.LE.0) then
            print*, 'Wrong input: a positive number needed'
            goto 2
        end if
        V = 3.141592 * R * R * H
        print*, 'Radius = ', R
        print*, 'Height = ', H
        print*, 'Volume of the cylinder = ', V
        end

Problem 3: Print partial sums of the 1/N series.

       program series
       integer N, I, Step
       real Sum
       print*, 'Enter the number of terms and a step'
       read*, N, Step
       Sum = 0
       do I = 1, N
          Sum = Sum + 1/I
          if (mod(I,Step).EQ.0) print*, I, '      ', Sum
       end do
       end

Problem 4: Input 10 numbers and count how many of them fall in the interval [5,10].

a) Using a Do loop

        program numbers
        integer i, count
        real x
        print*, 'Enter 10 numbers - one at a time'
        count=0
        do i=1,10
           read*, x
           if (x.LE.10.AND.x.GE.5) then
              count=count+1
           end if
        end do
        print*, 'You entered ',count,' numbers in [5,10]'
        end

b) Using a Goto statement

        program numbers
        integer i, count
        real x
        print*, 'Enter 10 numbers - one at a time'
        count=0
        i=1
1       read*, x
        i=i+1
        if (x.LE.10.AND.x.GE.5) then
            count=count+1
        end if
        if (i.LE.10) Goto 1
        print*, 'You entered ',count,' numbers in [5,10]'
        end

Problem 5: Input numbers and add them together until a number greater that 10 is entered. Print the total excluding the last number. Use Goto statements.

a) Post-condition control

        program add numbers
        real x, sum
        print*, 'Enter numbers - one at a time'
        sum=0
1       read*, x
        sum=sum+x
        if (x.LE.10) print*, x
        if (x.LE.10) goto 1
        print*, '------'
        print*, sum-x
        end
 

b) Exit from within the loop (stopping condition in the body of the loop)

        program add numbers
        real x, sum
        print*, 'Enter numbers - one at a time'
        sum=0
1       read*, x
        if (x.GT.10) goto 2
        sum=sum+x
        print*, x
        goto 1
2       print*, '------'
        print*, sum
        end
 

Problem 6: Input and add together numbers until the number entered is less than the previous number. Use Goto statements.

        program add numbers
        real x, y, sum
        print*, 'Enter numbers - one at a time'
        read*, y
        print*, y
        sum=y
1       read*, x
        if (x.LT.y) goto 2
        sum=sum+x
        print*, x
        y=x
        goto 1
2       print*, '------'
        print*, sum
        end


TEST 4 (10 pts.)

Review Topics and Example Problems

FOR-loops and IF structures
  1. Write a program to read 10 integer numbers and add together all positives and all negatives in separate totals.
  2. Write a program to read 10 integer numbers and count the perfect squares among them.
FOR-loops and Arrays
  1. Write a program to read 10 integer numbers into an array. Then using the array the program finds the maximal number and its index into the array.
  2. Write a program to read 10 integer numbers into two arrays of 5 elements each. Then the program must print the sums of the corresponding elements of the two arrays. For example, if the arrays contain 11,44,51,50,30 and 10,44,54,52,30 the program must print 21,88,105,103,60.
  3. Write a program to read 10 student records from the keyboard (using InputBox) into two arrays. Each record contains an ID (Integer) and a name (String) separated by a blank. The ID's go in the first array and the names - in the second one. Then the program asks for an ID (using InputBox) and prints the name of the students with the specified ID.
Do-Loop-While and Arrays
  1. Write a program to read integer numbers into an array until the number –99 is entered. Then using the array the program must print the numbers in a reverse order (excluding the number –99).