Here are some Visual Basic answers to the programming problems from the quiz.
Option Explicit
Private Sub cmdDisplay_Click() Rem Calculate population densities of states Rem This subroutine copied exactly from the text book picDensity.Cls Call CalculateDensity("Hawaii", 1134750, 6471) Call CalculateDensity("Alaska", 570345, 591000) End Sub
Private Sub CalculateDensity( _ state As String, _ pop As Single, _ area As Single _ ) Rem Calculates and prints population density Rem This subroutine modified from one given in the text
Dim rawDensity As Single ' floating-point density Dim denrounded As Integer ' rounded density
Let rawDensity = CalculateRawDensity(pop, area) Let denrounded = CalculateWholeNumber(rawDensity)
Rem Format the floating-point number using 2 decimal places picDensity.Print _ "The density of "; state; " is "; denrounded; _ " ("; Format(rawDensity, "Standard"); ")"; _ " people per square mile." End Sub
Private Function CalculateRawDensity( _ pop As Single, _ area As Single _ ) As Single ' RET: floating-point density Rem Calculates the density of the population
CalculateRawDensity = pop / area End Function
Private Function CalculateWholeNumber( _ inum As Single _ ) As Integer ' RET: rounded number Rem Round a number inum to its nearest integer
CalculateWholeNumber = Int(inum + 0.5) End Function
Option Explicit
Private Sub cmdDo_Click() Rem Get a full name and generate an Algonquin e-mail address
Dim nom As String
Let nom = txtName.Text picId.Cls picId.Print GetLast(nom); GetInitial(nom); picId.Print "@algonquincollege.com" End Sub
Private Function GetInitial( _ str As String _ ) As String ' RET: lower-case first initial from name Rem Extracts the first initial from the str
Let GetInitial = LCase(Left(str, 1)) End Function
Private Function GetLast( _ str As String _ ) As String ' RET: last name Rem Extracts 6 characters of the last name from the string
Dim n As Integer ' position of first blank Dim last As String ' last name (after blank)
Let n = Len(str) - InStr(str, " ") Let last = Right(str, n) Let GetLast = LCase(Left(last, 6)) End Function
Alternate version of GetLast using no unnecessary variables:
Private Function GetLast( _ str As String _ ) As String ' RET: last name Rem Extracts 6 characters of the last name from the string Let GetLast = LCase(Left(Right(str,Len(str)-InStr(str," ")),6)) End Function