Project 5 is due in Vista on May 12

Final Exam (20%) will be held on Monday, May 12, 2-4pm. See review topics for Tests 1, 2 and 3.

CS 113 - Introduction to Computers

Spring-2008

Classes: MW 2:00 pm - 3:15 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 9:30am - 12:00pm,  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 and objectives: 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 6.0.  Students learn to develop graphical user interfaces (GUI’s) and use basic programming language structures to develop algorithms for solving various kinds of problems.

Required textbook: David Schneider, An Introduction to Programming Using Visual Basic 6.0, Fourth (Update) Edition, Prentice Hall, 2004.

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 (CentralPipeline>Student>Vista Courses>CS-113-03). Some tests may also be taken through Vista.

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

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, assignments, projects and tests (by week)

Note: Dates will be placed for all projects due days and tests. Check the schedule regularly for updates!
  1. January 22 - 31: Introduction to programming by example. Problem solving by programming.
  2. February 4 - 8: Visual Basic Programming Environment and basic programming structures.
  3. February 11, 13, 20: Input Box, Built-in Functions, String manipulation, Relational Expressions, If-Then-Else.
  4. February 27: Test 1 (10%). Review topics and example problems for TEST 1
  5. March 3: ElseIf, Select Case.
  6. March 5-10: Do-While/Until-Loops, Interactive Input, Do-Loop-While/Until, Counters, Accumulators.
  7. March: 24 - 26: For-Next Loops, Nested Loops
  8. April 2: Test 2 (10%). Review topics and example problems for TEST 2
  9. April 7-9: General Sub Procedures, Parameters, Form-level variables
  10. Passing Parameters, Returning values, Function Procedures.
  11. Scope of variables, Call by reference, Call by value
  12. April 23: Test 3 (10%). Review topics and example problems for TEST 3
  13. Review of Sub Procedures and Functions: String manipulation
  14. Recursion. Recursion is not in tests or projects.
  15. Sequential Files, One-Dimensional Arrays.
  16. Sorting. Sorting is not in tests or projects..
  17. May 12, 2-4pm: Final test (20%). See review topics for Tests 1, 2 and 3.

Lecture 1

A little history

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

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

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
     F = F + 20
   Loop
End Sub


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 and select "Form" in the object identification box (upper left) and "Click" in the procedure identification box (upper right). You get automatically the code template in the code window:
    1. Private Sub Form_click()

      End Sub

  4. Write the code into the template. For example:
    1. Private Sub Form_click()
          Print "Hello! This is my first program"
      End Sub
  5. 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. Command Buttons
  4. Picture Boxes

Creating a Text Box

  1. Double-click on Text Box 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. 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. Form is the default object. Example: Print "Hello" will print on the form.
  2. ObjectName.Property accesses Property of ObjectName.
  3. ObjectName.Procedure executes the Procedure associated with Object Name. Example: picOutput.Print will print on picture box picOutput.

Example: Basic Controls


Variables, Assignment, Intrinsic Functions, Input, Formatted Output, Named Constants

Example 1: Concatenation and addition. Convert string into number - the Val function.

Private Sub cmdAdd_Click()
  Print Val(txtInput1.Text) + Val(txtInput2.Text)
End Sub

Private Sub cmdConcatenate_Click()
  Print txtInput1.Text + txtInput2.Text
End Sub

Problem: Calculation of age (years and months lived) based on month and year of birth (Current month is 2, year - 2008, 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 Form_Click()
  Print "Years = " ; (2 + 2008 * 12 - 3 - 1956 * 12) \ 12
  Print "Months = " ; (2 + 2008 * 12 - 3 - 1956 * 12) mod 12
End Sub

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

Private Sub Form_Click()
  Dim MOB As Integer, YOB As Integer, Months As Integer, Years As Integer, MonthsLived As Integer
  Const CurrentMonth As Integer = 2
  Const CurrentYear As Integer = 2008
  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
  Print "Years = " ; Years
  Print "Months = " ; Months
End Sub

Solution 3: Using input boxes to enter data.

Private Sub Form_Click()
  Dim MOB As Integer, YOB As Integer, Months As Integer, Years As Integer, MonthsLived As Integer
  Const CurrentMonth As Integer = 2
  Const CurrentYear As Integer = 2008
  MOB = InputBox("Enter Month of Birth")
  YOB = 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
  Cls
  Print " You are "; Years; "years and "; Months; " months old"
End Sub

Solution 4: Elaborating the interface - text boxes for input, a picture box for output and a command button to run the program. Converting a string to a number.

Private Sub cmdCalc_Click()
  Dim MOB As Integer, YOB As Integer, Months As Integer, Years As Integer, MonthsLived As Integer
  Const CurrentMonth As Integer = 2
  Const CurrentYear As Integer = 2008
  MOB = Val(txtMonth.Text)      ' Convert string to number
  YOB = Val(txtYear.Text)
  MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
  Months = MonthsLived Mod 12   ' Remainder from integer division
  Years = MonthsLived \ 12      ' Integer division
  picShow.Cls                           ' Clear picture box
  picShow.Print "Years = " ; Years      ' Print Years
  picShow.Print "Months = " ; Months    ' print Months
End Sub


Lecture 3

Built-in Functions, String manipulation, If-Then-Else block

Example: Variable types and conversions (the Val function). Run the following program with inputs: "Text1", "3.14" and "  3.14" and explain the output

Private Sub Form_Click()

Dim N As Integer, X As Single, S As String

  U = txtInput.Text
  Print "Varaint", U
  S = txtInput.Text
  Print "String", S
  N = Val(txtInput.Text)
  Print "Integer", N
  X = Val(txtInput.Text)
  Print "Single", X

End Sub

Implicit end explicit variable declarations: try the above program with Option Explicit before the event procedure.
 

Check the input type - The IsNumeric function

Private Sub Form_Click()

  Print txtInput.Text, IsNumeric(txtInput.Text)

End Sub

Problem 1: Add or concatenate inputs depending on their type. Use If-Then block.

Private Sub Form_Click()

  If IsNumeric(txtInput.Text) = True Then
     Print Val(txtInput.Text) + Val(txtInput.Text)
  End If

  If IsNumeric(txtInput.Text) = False Then
     Print txtInput.Text + txtInput.Text
  End If

End Sub

Or use If-Then-Else block:

Private Sub Form_Click()

  If IsNumeric(txtInput.Text) = True Then
     Print Val(txtInput.Text) + Val(txtInput.Text)
  Else
     Print txtInput.Text + txtInput.Text
  End If

End Sub
 

Relational Expressions, If-Then-Else block

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

Solution 1:  No input data validation

Private Sub Form_Click()
  Dim MOB As Integer, YOB As Integer, Months As Integer, Years As Integer, MonthsLived As Integer
  Const CurrentMonth As Integer = 2
  Const CurrentYear As Integer = 2008
  MOB = InputBox("Enter Month of Birth")
  YOB = 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
  Cls
  Print " You are "; Years; "years and "; Months; " months old"
End Sub

Solution 2:  Data validation

Private Sub Form_Click()
  Dim MOB As Integer, YOB As Integer, Months As Integer, Years As Integer, MonthsLived As Integer
  Const CurrentMonth As Integer = 2
  Const CurrentYear As Integer = 2008
  MOB = InputBox("Enter Month of Birth")
  YOB = InputBox("Enter Year of Birth")
  If YOB > 2008 Or YOB < 1900 Then         ' Check if YOB is out of the interval [1900,2008]
    Print YOB, "Wrong year"
  Else
    MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
    Months = MonthsLived Mod 12  ' Remainder from integer division
    Years = MonthsLived \ 12     ' Integer division
    Cls
    Print " You are "; Years; "years and "; Months; " months old"
  End If
End Sub

Solution 3: More elaborated verification - ElseIf clause.

Private Sub Form_Click()
  Dim MOB As Integer, YOB As Integer, Months As Integer, Years As Integer, MonthsLived As Integer
  Const CurrentMonth As Integer = 2
  Const CurrentYear As Integer = 2008
  MOB = InputBox("Enter Month of Birth")
  YOB = InputBox("Enter Year of Birth")
  If YOB > 2008 Or YOB < 1900 Then
    Print YOB, "Wrong year"
  ElseIf MOB > 12 Or MOB < 1 Then
    Print MOB, "Wrong month"
  Else
    MonthsLived = CurrentMonth + CurrentYear * 12 - MOB - YOB * 12
    Months = MonthsLived Mod 12  ' Remainder from integer division
    Years = MonthsLived \ 12     ' Integer division
    Form1.Cls
    Print " You are "; Years; "years and "; Months; " months old"
  End If
End Sub

Elaboration: Use the Isnumeric fucntion to check if the input is numeric.
 

More Numeric and String functions

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

Private Sub cmdPrint_Click()
  Const S = "one  two  threefour five "
  Pos = (Int(Rnd * 5)) * 5 + 1
  picShow.Cls
  picShow.Print Mid(S, Pos, 5)
End Sub

Problem 4: 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 cmdPrint_Click()
  Const S = "one  two  threefour five "
  Dim Pos, Num As Integer
  Pos = InStr(S, txtInput.Text)
  Num = (Pos / 5) + 1
  picShow.Cls
  picShow.Print Num
End Sub


Lecture 4

ElseIf, Select Case

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

Solution 1: Using If-Then-ElseIf structures

Private Sub cmdCalc_Click()
  Dim X, Y, R As Single
  Dim Op As String
  X = Val(txtOperand1.Text)
  Y = Val(txtOperand2.Text)
  Op = txtOperation.Text
  picShow.Cls

  If Op = "+" Then
    picShow.Print X + Y
  ElseIf Op = "-" Then
    picShow.Print X - Y
  ElseIf Op = "*" Then
    picShow.Print X * Y
  ElseIf Op = "/" Then
    If Y <> 0 Then
      picShow.Print X / Y
    Else
      picShow.Print "Division by 0"
    End If
  ElseIf Op = "\" Then
    If Y <> 0 Then
      picShow.Print X \ Y
    Else
      picShow.Print "Division by 0"
    End If
  ElseIf Op = "mod" Then
    picShow.Print X Mod Y
  Else
    picShow.Print "Incorrect operation"
  End If
End Sub

Solution 2: Using Select Case structures

Private Sub cmdCalc_Click()
  Dim X, Y, R As Single
  Dim Op As String
  X = Val(txtOperand1.Text)
  Y = Val(txtOperand2.Text)
  Op = txtOperation.Text
  picShow.Cls
  Select Case Op
  Case "+"
    picShow.Print X + Y
  Case "-"
    picShow.Print X - Y
  Case "*"
    picShow.Print X * Y
  Case "/"
    If Y <> 0 Then
      picShow.Print X / Y
    Else
      picShow.Print "Division by 0"
    End If
  Case "\"
    If Y <> 0 Then
      picShow.Print X \ Y
    Else
      picShow.Print "Division by 0"
    End If
  Case "mod"
    picShow.Print X Mod Y
  Case Else
    picShow.Print "Incorrect operation"
  End Select
End Sub


Lecture 5

Do-While/Until-Loops

Problem 1: Find the total and the average of a seqence of numbers.

Rem Counting, totaling, averaging a fixed-length sequence of numbers
Private Sub Form_Click()
  Dim X, Total, Average As Single
  Dim N, Count As Integer
  N = InputBox("How many numbers?")
  Count = 0
  Total = 0
  Do While Count < N
    X = InputBox("Enter a number")
    Count = Count + 1
    Total = Total + X
  Loop
  Average = Total / Count
  Cls
  Print "You entered "; Count; " numbers totaling "; Total
  Print "The average of these numbers is "; Average
End Sub

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

Solution: Using a Fixed-count loop - the number of repetitions is known in advance.

Private Sub Form_Click()
  Const F0 As Integer = 0
  Const F1 As Integer = 100
  Const Step As Integer = 10
  Dim F, C As Integer
  F = F0
  Form1.Cls
  Form1.Print "Fahrenheit", "Celsius"
  Do While F <= F1
    C = (F - 32) * 5 / 9
    Form1.Print F, C
    F = F + Step
  Loop
End Sub

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

Solution: Using a Variable-condition loop - the number of repetitions is NOT known in advance.

Private Sub cmdGCD_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   'Do Until Y = 0
    T = X Mod Y
    X = Y
    Y = T
  Loop
  picResult.Cls
  picResult.Print "The GCD of "; A; " and "; B; " is "; X
End Sub


Interactive Input, Do-Loop-While/Until

Input boxes - Warning: The input (and text) box is always of string type.
Examples: Illustrating also the use of one-line If-Then structures
  1. Version 1

  2. X=5
    Y=InputBox("Number? ")      ' Enter 5
    If X=Y Then Print "OK"      ' No print
  3. Version 2

  4. X=5
    Y=Val(InputBox("Number? ")) ' Enter 5
    If X=Y Then Print "OK"      ' Prints OK
  5. Version 3

  6. Dim Y as Integer
    X=5
    Y=InputBox("Number?")       ' Enter 5
    If X=Y Then Print "OK"      ' Prints OK
Repetition structures:  posttest loops (Do Loop Until/While)

Rem Counting the tries to guess a number
Private Sub Form_Click()
  Dim Number As Integer, Guess As Integer, 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
    Cls
    If Guess > Number Then Print "It's smaller"
    If Guess < Number Then Print "It's bigger"
    If Guess = Number Then Print "OK, the number is "; Number
  Loop While Guess <> Number        ' Until Guess = Number
  Print Count; " tries"
End Sub


Sentinel loop, counters, accumulators

Rem Counting, totaling, averaging a sequence of numbers
Private Sub Form_Click()
  Dim Number, Total, Average As Single
  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
  Cls
  Print "You entered "; Count; " numbers totaling "; Total
  Print "The average of these numbers is "; Average
End Sub

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)

Private Sub Form_Click()
  Dim X As Single, Y As Single
  Dim I As Single, N As Single, M As Single
  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
  Print 4 * M / N
End Sub

Nested Loops

Problem 2: Print a table of approximation of PI

Private Sub Form_Click()
 Dim X As Single, Y As Single
 Dim I As Single, N As Single, M As Single
 Dim Max As Single
 Max = InputBox("Max number of iterations?")
 Cls
 Print "Iterations", "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
    Print N, 4 * M / N
    N = N * 2
 Loop Until N >= Max
 Print "End"
End Sub

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
Private Sub Form_Click()
  Dim N, F, Fcount, P As Integer
  P = 0
  For N = 1 To 20
    Print N,
    Fcount = 0
    For F = 1 To N / 2
      If N Mod F = 0 Then
        Print F;
        Fcount = Fcount + 1
      End If
    Next F
    If Fcount = 1 Then P = P + 1
    Print
  Next N
  Print "Number of primes ="; P
End Sub

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.

Private Sub Form_Click()
  Dim N, F, Fcount, P As Integer
  P = 0
  Print " N", "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 Print N, P
  Next N
End Sub


Lecture 7

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

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

Private Sub Form_Click()
  Dim N As Integer
  For N = 1 To 10
    Print N,
    Call PrintFactors(N)
  Next N
End Sub

Private Sub PrintFactors(N As Integer)
  Dim F As Integer
  For F = 1 To N / 2
      If N Mod F = 0 Then Print F;
  Next F
  Print
End Sub

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

Dim Fcount As Integer

Private Sub Form_Click()
  Dim N As Integer
  For N = 1 To 10
    Call Factors(N)
    Print N, Fcount
  Next N
End Sub

Private Sub Factors(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

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

Private Sub Form_Click()  ' Find the maximum of three numbers
  Dim X As Single, Y As Single, Z As Single, M As Single, Max As Single
  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
  Print "The maximum is: "; Max
End Sub

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

Dim Max As Single ' A global variable accessible from any procedure

Private Sub Form_Click()
Dim X As Single, Y As Single, Z As Single
  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
  Print "The maximum is: "; Max
End Sub

Public Sub Max2(A As Single, 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

Private Sub Form_Click()
Dim X As Single, Y As Single, Z As Single, Max As Single
  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
  Print "The maximum is: "; Max
End Sub

Public Sub Max2(A As Single, B As Single, C As Single) ' 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 Form_Click()
Dim X As Single, Y As Single, Z As Single, Max As Single
  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
  Print "The maximum is: "; Max
End Sub

Public Function Max2(A As Single, B As Single) As Single ' Note that there is a type definition here
  If A > B Then
     Max2 = A
  Else
     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?)

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

Private Sub Form_Click()
  Dim A As Integer, B As Integer, D As Integer
  A = InputBox("A = ?")
  B = InputBox("B = ?")
  D = GCD(A, B)
  Print "The GCD of "; A; " and "; B; " is "; D
End Sub

Public Function GCD(X As Integer, 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

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

Private Sub Form_Click()
Dim X As Single, Y As Single, Z As Single, Max As Single
  X = InputBox("X = ?")
  Y = InputBox("Y = ?")
  Z = InputBox("Z = ?")
  Call Max2(X, Y, Max)
  Call Max2(Max, Z, Max)
  Print "The maximum is: "; Max
End Sub

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

Problem 3: Add fractions and simplify the sum
' Compute A/B + C/D = E/F in rational numbers (fractions)
' Use GCD to simplify the sum

Private Sub Form_Click()
Dim A As Integer
  Dim B As Integer
  Dim C As Integer
  Dim D As Integer

  A = InputBox("Enter first numerator")
  B = InputBox("Enter first denominator")
  C = InputBox("Enter second numerator")
  D = InputBox("Enter second denominator")
  E = A * D + B * C
  F = B * D
  S = GCD(E, F)
  E = E / S
  F = F / S
  Print A; " / "; B; " + "; C; " / "; D; " = "; E; "/"; F
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


Lecture 10

Review of Sub Procedures and Functions: String manipulation

Problem 1 (Problem 27, page 179): 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:

Private Sub Form_Click()
Dim Line As String, W As String, N As Integer
Line = Text1.Text
Picture1.Cls
N = 0
Do
  W = Word(Line)
  If W <> "" Then
    If IsNumeric(W) Then
      Picture1.Print W, "number"
    Else
      Picture1.Print W, "string"
    End If
    N = N + 1
  End If
Loop While W <> ""
Picture1.Print "__________________"
Picture1.Print N; " words"
End Sub

'Returns and removes the first word from S (S is passed by reference, the function changes it).
Public Function Word(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

Problem 2 elaboration:Count the number of string 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

Private Sub Form_Click()
   Call triangle(1000, 1000, 5000)
End Sub

Private Sub triangle(X As Integer, Y As Integer, S As Integer)
  If S = 1 Then
    Line (X, Y)-(X + 1, Y + 1)
  Else
    Call triangle(X, Y, S / 2)
    Call triangle(X + S / 2, Y, S / 2)
    Call triangle(X, Y + S / 2, S / 2)
  End If
End Sub

Solution 2: Using triangles and a square

Private Sub Form_Click()
   Call triangle(1000, 1000, 5000)
End Sub

Private Sub square(X As Integer, Y As Integer, S As Integer)
  Line (X, Y)-(X, Y + S)
  Line (X, Y + S)-(X + S, Y + S)
  Line (X + S, Y + S)-(X + S, Y)
  Line (X + S, Y)-(X, Y)
End Sub

Private Sub triangle(X As Integer, Y As Integer, S As Integer)
  If S = 1 Then
    Line (X, Y)-(X + 1, Y + 1)
  Else
    Call square(X, Y, S / 2)
    Call triangle(X + S / 2, Y, S / 2)
    Call triangle(X, Y + S / 2, S / 2)
  End If
End Sub

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 on the form

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

Private Sub Form_Click()

Dim Filename As String
Dim X As String

Filename = InputBox("Enter the file name")

Open Filename For Input As #1

Do While Not EOF(1)
  Input #1, X
  Print X
Loop
Close #1

End Sub

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

Private Sub Form_Click()

Dim Filename As String
Dim Grade As Integer
Dim Name As String

Filename = InputBox("Enter the file name")

Open Filename For Input As #1

Do While Not EOF(1)
  Input #1, Grade, Name
  Print Grade, Name
Loop
Close #1

End Sub

Elaborations: Print only grades or names, or print first the name and then the grade.

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

Private Sub Form_Click()

Dim Filename As String
Dim X(1 To 10) As String ' This is an array of 10 elements
Dim I As Integer, N As Integer

Filename = InputBox("Enter the file name")

Open Filename For Input As #1

N = 0

Do While Not EOF(1)  ' Read the file in the array X
  N = N + 1
  Input #1, X(N)
Loop
Close #1

Print N; " student records read"
Print "------------------------"

For I = 1 To N       ' Print the array
   Print X(I)
Next I

End Sub

Elaboration: Print the student records in reverse order.

Solution 4: Read the file in two separate arrays - Grade and Name and print from the arrays.

Private Sub Form_Click()

Dim Filename As String
Dim Grade(1 To 10) As Integer
Dim Name(1 To 10) As String
Dim I As Integer, N As Integer

Filename = InputBox("Enter the file name")

Open Filename For Input As #1

N = 0

Do While Not EOF(1)
  N = N + 1
  Input #1, Grade(N), Name(N)
Loop
Close #1

Print "All student grades"
For I = 1 To N
   Print Name(I), Grade(I)
Next I

Print
Print "Students with excellent grades"

For I = 1 To N
   If Grade(I) >= 90 Then
      Print Name(I), Grade(I)
   End If
Next I

End Sub

Elaboration: Print student records with letter grades (check grade intervals)
 

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:
Al Clark      80
Ann Miller    75


Solution 1: Search names
Private Sub Form_Click()

Dim Filename As String
Dim Grade(1 To 10) As Integer
Dim Name(1 To 10) As String
Dim I As Integer, N As Integer
Dim S As String

Filename = InputBox("Enter the file name")
S = InputBox("Enter student name or a part of it")

Open Filename For Input As #1

N = 0

Do While Not EOF(1)
  N = N + 1
  Input #1, Grade(N), Name(N)
Loop
Close #1

Print "Student names that contain "; S
Print "--------------------------------"

For I = 1 To N
   If InStr(Name(I), S) > 0 Then
      Print Name(I), Grade(I)
   End If
Next I

End Sub

Solution 2:
Search by grades

Private Sub Form_Click()

Dim Filename As String
Dim Grade(1 To 10) As Integer
Dim Name(1 To 10) As String
Dim I As Integer, N As Integer
Dim S As Integer

Filename = InputBox("Enter the file name")
S = InputBox("Enter grade")

Open Filename For Input As #1

N = 0

Do While Not EOF(1)
  N = N + 1
  Input #1, Grade(N), Name(N)
Loop
Close #1

Print "Students with grade "; S
Print "------------------------"

For I = 1 To N
   If Grade(I) = S Then
      Print Name(I), Grade(I)
   End If
Next I

End Sub

Elaboration: Search by grades in intervals or by letter grades (converted to intervals).


Lecture 13

Sorting student grades/records by selection sort

Using a text file with grades

Dim Grade(1 To 10) As Integer
Dim N As Integer

Private Sub Form_Click()

  Open InputBox("Enter File Name") For Input As #1
  N = 0
  Do While Not EOF(1)
    N = N + 1
    Input #1, Grade(N)
    Print Grade(N)
  Loop
  Close #1

  Call Sort

  Print "Sorted:"

  For I = 1 To N
    Print 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(M As Integer, N As Integer) As Integer
Dim Min As Integer, 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
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 0 (grade not assigned, but submission required)

Install VB6.0 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.)

Write a program in Visual Basic 6.0 according to the following specifications:

Description

Implementation

Use two separate Text Boxes or Input Boxes for input and print on a Picture Box. Hints: For computing the age use code from Lecture 3, Problem 2. Then include If-Then or If-Then-Else blocks that check for the range of variable Years. Add also an If block that compares MOB with CurrentMonth and prints the birthday message.

Documentation

Run your program and make sure it works as described above. Then 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.

Submission


PROJECT 2 (10 pts.)

Write a program in Visual Basic 6.0 according to the following specifications:

Description:

Implementation: Use input boxes for all input and print the output on a picture box. Use a Do-While-Loop structure for reading and processing the sequence of grades. See the program
for Problem 1 from Lecture 5.

Example: Your output should look like the one below when the input is 5 followed by 90, 45, 93, 75, 85:

     2 excellent grades with average 91.5
     2 okay grades with average 80
     1 failure grades with average 45

Documentation: Run your program and make sure it works as described above. Then 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.

Submission:


PROJECT 3 (10 pts.)

Write a program in Visual Basic 6.0 according to the following specifications:

Description:

Implementation: Documentation: Run your program and make sure it works as described above. Then 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.

Submission:

Extra Credit (maximum 3 points): Extend the program so that it also prints the prime numbers in the same interval. For example:

Abundant numbers: 12 18 20 24
Deficient numbers: 1 2 3 4 5 7 8 9 10 11 13 14 15 16 17 19 21 22 23 25 26 27 29
Perfect numbers: 6 28
Prime numbers: 2 3 5 7 11 13 17 19 23 29


PROJECT 4 (10 pts.)

Description: Implementation and restrictions: Documentation: Run your program and make sure it works and prints exactly as described above. Then 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.

Submission:

Extra Credit (maximum 5 points): The program sums a number of fractions specified by the user.

PROJECT 5 (10 pts.)

Write a program in Visual Basic 6.0 according to the following specifications:

Description:

4 student records read.

Studentts with excellent grades:
John Smith    90

Students with ok grades
Al Clark      80
Ann Miller    75

Students with failure grades:
Sue Taylor    55

Documentation: Run your program and make sure it is designed  and works exactly as described above. Then 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.

Submission:

Extra Credit (maximum 5 points): After printing the student records as explained above the program should print statistics about the number of excellent, ok, and falure grades with their averages (see Project 2). For example, with the text file from Lecture 12, the program prints
1 excellent grades with average 90
2 okay grades with average 77.5
1 failure grades with average 55

Review topics and sample problems for TEST 1

Review topics

  1. Basic visual objects (form, text box, command button, picture box), accessing their properties from within the code.
  2. Print statement: printing to the form and to a picture box, printing strings and variables.
  3. Arithmetic expressions, integer arithmetic (\, mod).
  4. Variable types: Integer, Single, String, type conversion on assignment, using the Val function, string concatenation vs. arithmetic addition.
  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. Private Sub cmdSquare_Click()
      Dim X As Single
      X = Val(txtValue.Text)
      picShow.Print X*X
    End Sub
     
  3. Let X and Y be integer variables. Write a single Print statement to print the result and the remainder of the integer division X divided by Y. For example if X=26 and Y=4 then the following should be printed:

  4. The integer result of dividing 26 by 4 is 6 and the remainder is 2
     
  5. What does the program below print assuming that text box Text1 contains 3.14 and text box Text2 containg ABC? Explain your answer.

  6. Private Sub Form_Click()
      Dim X As Integer, Y As Integer
      X = Val(Text1.Text)
      Y = Val(Text2.Text)
      Print X + Y
    End Sub

    What does it print if X and Y are both of type Single?
     

  7. Find values for X and Y such that the following segment of code will print "OK"

  8. If X > Y Or X > 0 Then
       X = Y
    End If
    If X < Y Then
      Print "OK"
    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 prints "in" if valiable X belongs to interval [18, 65].
  13. Write an If-Then block that prints "in" if valiable X belongs to interval [10, 20] or interval [30, 50].
  14. Write an If-Then block that prints "out" if valiable X is outside (does not belong to) interval [18, 65].
  15. Write an If-Then-Else block that prints "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.

    Private Sub Form_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
          Print "Radius = " & R
          Print "Height = " & H
          Print "Volume of the cylinder = " & V
       Else
          Print "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 a perfect square (a square of another number).

    Private Sub Form_Click()
       Dim N As Integer, S As Double
       N = InputBox("Enter an integer number")
       If N > 0 Then
         S = Sqr(N)
         If S = Int(S) Then
            Print N & " is a perfect square"
         Else
            Print N & " is not a perfect square"
         End If
       Else
         Print "Incorrect Input. Try agian"
       End If
    End Sub
     

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

  6. Problem: Print the even numbers from 10 to 30. Use For-Next loop.

    Private Sub Form_Click()
       Dim I As Integer, S As Double
       For I = 10 To 30
          If I Mod 2 = 0 Then
            Print I
          End If
       Next I
    End Sub
     

  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.

    Private Sub Form_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
       Print EvenCount & " even numbers"
       Print OddCount & " odd 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 Form_Click()
      Dim I As Integer, S As Single
      S = 0
      I = 0
      Do
        I = I + 1
        S = S + 1 / I
      Loop Until S > 10
      Print 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 Form_Click()
   Dim I As Integer
   For I = 1 To 100
     If I Mod 3 = 0 Then
       Print 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 numbers are entered. Use the same type of loop.

Private Sub Form_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
   Print EvenCount & " even numbers"
   Print OddCount & " odd numbers"
End Sub

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)
Private Sub Form_Click()
   Dim I As Integer, S As Double
   S = 1
   I = 1
   Do
      S = S + 1 / I
      I = I + 1
   Loop While S < 2
   Print I
End Sub

Review topics and example problems for TEST 3

Review topics

  1. General Sub Procedures - Section 4.1.
  2. Local variables, Form-level variables, Passing parameters, Returning values -  Section 4.2.
  3. Function Procedures - Section 4.3

Example problems:

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

Private Sub Form_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
 

2. Use the follwing general sub procedure

Private Sub PrintAverage(X As Integer, Y As Integer, Z As Integer)
   Dim Average As Single
   Average = (X + Y + Z) / 3
   Print "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 form-level variables to pass the numbers to PrintAverage. That is, the sub procedure should be defined without parameters as

Private Sub PrintAverage()
   Dim Average As Single
   Average = (X + Y + Z) / 3
   Print "The average is :"; Average
End Sub

4.  What does the program below print? 1 or 2? Explain why. What happens if ByVal is removed?

Private Sub Form_Click()
Dim X As Integer
  X = 1
  Call AddOne(X)
  Print X
End Sub

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

5. Write function procedures to complete the program below:

Private Sub Form_Click()
   Dim X As Integer, Y As Integer
   X = InputBox("Enter a number")
   Y = InputBox("Enter another number")
   Print Min(X, Y)     ' Prints the smaller of X and Y
   Print Max(X, Y)     ' Prints the bigger of X and Y
   Print Average(X, Y) ' Prints the average of X and Y
End Sub
 

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:

Private Sub Form_Click()
   Dim X As Integer, Y As Integer
   Call InputTwoNumbers(X, Y)      ' Reads two numbers from user input
   Print "The sum is "; Sum(X, Y)  ' Print the sum of X and Y
End Sub

8. Use the follwing sub procedure

Private Sub Average(ByVal X As Integer, ByVal Y As Integer, ByVal Z As Integer, ByRef W As Single)
   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.