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:
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)
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
Public Class Form1
Inherits System.Windows.Forms.Form
Windows Form Designer generated code
Private Sub txtForm1_TextChanged(...) Handles txtForm1.TextChanged
End Sub
Private Sub btnClearOutput_Click(...) Handles btnClearOutput.Click
lstOutput.Items.Clear()
End Sub
Private Sub btnPrint_Click(...) Handles btnPrint.Click
lstOutput.Items.Add(txtInput.Text)
End Sub
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
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).
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.
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
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
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
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)
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
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
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).
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
Name string
John string
Age string
20 number
Review of string built-in functions needed:
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
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)
Solution 2: Factorial (recursive)
Problem 2: Write a function procedure greater(S1, S2) for comparing strings (lexicographic order). Examples:
greater("abc", "bbc") = TruePrivate Sub btnstart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnstart.Click
greater("bbc", "abc") = False
greater("abc", "ab") = True
greater("abc", "abb") = True
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
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 SmithA search for names with "A" must produce:
80 Al Clark
55 Sue Taylor
75 Ann Miller
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.
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.
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.
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.
RESTRICTIONS HEREAFTER:
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.
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.
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:
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
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
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
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
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
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
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
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