Unit II Practice/Learning

CS 1130 Visual Basic — Fall 2017

Overview

Unit II addresses interpreting and constructing numeric and string expressions in Visual Basic and the use of input and output involving the user. It sets the tone for what you will be doing in many of the learning activities. The focus of the learning/practice activity will be on creating and testing expressions. During that process you should gain facility with:

The assignment builds on the numerics and strings forms produced in the Unit I practice assignment. You may use the VB project you created for that assignment or download the project I created and placed in the project folder of the notes directory (its title is VB-practice_unit-II.zip). If you choose to use it, you may modify it as you please and I suggest you change its name before starting—after unzipping replace "_unit-II" in the folder name with your name/initials.

My plan is that a separate button be used for each item in the learning activity. Once you have the form you can start work on the assignment. You are to use an existing button or create a new one for each task indicated below. Then you should supply code that will accomplish the task and display the result of your code.

Note that this unit coincides with one of the competency/mastery demonstrations. That demonstration will be like an in-class quiz. (Remember that the demos are pass/fail and can be re-taken with little penalty but with time contraints.) You must "pass" the competency demo for this unit before any retakes of later units are allowed.

I encourage you to work with a partner, either using pair programming (one person types and one person watches for mistakes and swap roles every 30 minutes or so) or working side by side on separate computers. This way each person interacts with the code on each item—the only way to learn the material.

Specifications

You are to place the code for problem in the associated button for that problem. The "Numeric" exercise should be done in the "Numerics.vb" form and the "String" exercises in the "Strings.vb" form. If you need additional buttons, supply them.

If you have questions you can save and zip your project and send it to me or you can just copy your code and paste it into a mail message.

Numeric Exercises

The input for these problems can come from text boxes or input boxes. You should know how to use both. If you want to provide directions, you can use a message box in each problem to do so. Report your results with an explanation, i.e., the result and words that explain what it represents as directed, i.e., using a message box or a textbox. If the output mechanism is not supplied use whichever you wish.

Basic Numerics

  1. pay

    Calculate gross pay for a weekly pay period. You'll want to get values for pay-rate and hours-worked from the user. Use a message box to display a labeled result.

  2. time to travel

    Determine the time needed to travel an indicated distance. In addition to the desired distance, you'll want to get a value for speed from the user. Report the labelled result using a message box.

  3. hybrid savings

    Get input values for miles driven per year, MPG with current car, MPG with new hybrid, and cost of gasoline; then calculate and report the cost of fuel for each and the savings with the hybrid. Report the labeled result in a message box.

  4. your own "problem"

    Think of a problem that seems similar to these and produce code that will get appropriate input values and produce an "answer". Report the labeled result in a message box.

More Advanced Numerics

  1. pay with overtime

    Calculate gross pay for a pay period (probably a week). You'll want to get values for pay-rate and hours-worked from the user. Be sure to include time-and-a-half for overtime hours. Use the result text box to display a labeled result.

  2. Fahrenheit to Celcius

    Accept a value for a temperature on the Fahrenheit scale and produce equivalent value on the Celcius scale. Report the labeled result in the result text box.

  3. Remainder

    Accept two numbers from the user and report the old-fashioned/long division result of quotient and remainder when the first number is divided by the second. Report your result in the following format: # / # = q R r.

  4. one of the following
    • sale price

      I want to advertise a sale by indicating how much a customer has to pay. Provide code that allows me to enter the original price and a "percent off", and then tell me the sale price I can advertise. Report the labeled result in the result text box.

    • percent off

      I wish to advertise a sale item by indicating the savings percentage or "percent off" for the sale. I know the original price and I want try several different values for what I might charge. Provide code that will tell me what "percent off" I should claim in my advertising for a given pair of values for original price and sale price. Report the labeled result in the result text box.

    • original price

      A sale advertisement indicates the sale price and the savings or "percent off" figure. Report the labeled result for the original price in the result text box.

  5. average of averages

    Assume I know the averages for two exams and I want to find the overall average. Accept input for the average score and the number of scores included for each of the exams. Calculate and report the overall average of the two sets of scores.

  6. your own "problem"

    Think of a problem that seems similar to these and produce code that will get appropriate input values and produce an "answer".

Numeric Functions

Unless otherwise specified, you may use either a message box or the result text box to produce your output (report the result).

  1. total cost

    My daughter always wanted to know if she had enough money to buy something. Provide code that will accept input for price and tax-rate and then produce the total cost value. Round the result to the nearest cent and display

  2. die roll

    Use the Rnd() and Fix() functions to produce a value for a standard (1-6) die roll.

  3. craps roll

    As above but report the total when two dice are rolled.

  4. generate an addition problem

    Produce a drill & practice addition problem that asks the user to add two integers between 0 and 10 (inclusive). Use a message box to present the problem in the form of X + Y = ? where X and Y are replaced by the random numbers you generated.

  5. generate an subtraction problem

    Produce a drill & practice subtraction problem. (Hint: generate an addition problem as above, calculate the sum, and then present the problem as sum - x = ?.)

  6. peeps offspring

    Peeps are entities that live for 6 years. At age two they mate for life (magically half are male and half are female :-) At ages three and four each pair produces a single offspring. Get values for the number of 3-year and 4-year olds and report the number of peeps that will be born. (Note: there cannot be half a peep.)

  7. floor tiles

    Accept input for the length and width of a room (in inches) and for the size of floor tile to be used, e.g., 4 inches square. Determine and report the number of tiles needed. Note: tile remnants can not be used.

  8. arbitrary random integer

    Accept input for the low value and the high value for a range of random numbers. Then generate and report a random value in the range [low, ..., high] (inclusive).

  9. your own "problem"

    Think of a problem that seems similar to these and produce code that will get appropriate input values and produce an "answer".

String Exercises

As above, the input for these problems should mostly be entered in text boxes.

Basic String Actions

  1. welcome message

    Accept a value for a person's name and use a message box to welcome the person to the class, e.g., "Welcome to Visual Basic, Philip!"

  2. address

    Use the InputBox() method to get values for city, state (code), and zip; then, combine the values as in an address (i.e., City, ST  zip) and display the results in the output text box.

  3. increment

    Accept a value for a number in a text box, add one to the value, and report the result back in the same text box. What happens if you click the button again?

  4. your own "problem"

    Think of a problem that seems similar to these and produce code that will get appropriate input values and produce an "answer".

String Functions

  1. password length

    Accept a value representing a password and indicate how many characters it contains. Try clicking the button without typing anything.

  2. first character

    Use a message box to report the first character of the value entered via the text box.

  3. last character

    Use a message box to report the last character of the value entered via the text box.

  4. location of @

    Use a message box to report the first location of an at sign (@) in the value entered via the text box. Be sure to include a test value that does not include the at sign.

  5. location of comma

    Use a message box to report the first location of a comma in the value entered via the text box. Be sure to include a test value that does not include a comma.

  6. first word length

    Use a message box to report the length of the first word of the value entered via the text box. Be sure to enter more than one word. (Words are separated by spaces.)

  7. first word

    Use a message box to show a copy of the first word of the value entered via the text box. Be sure to enter more than one word. (Words are separated by spaces.)

  8. second word

    Use a message box to show a copy of the second word of the value entered via the text box. Be sure to enter more than one word. (Words are separated by spaces.) Note that the Substring() function can work with a single argument, e.g., ("This string").sub

        ("This string").Substring(4)
    

    produces " string", i.e., it starts in position 4 and copies the rest of the string.

  9. mail server

    Use a message box to report the mail server name entered via the text box. The mail server is the value between the at sign (@) and the dot (.) in an e-mail address.

  10. city, state, zip

    Accept a value from a text box that represents the City, ST  zip and report the values on separate lines in a message box. Note: vbNewLine can be used (via concatenation) to place a return character in a string.

  11. your own "problem"

    Think of a problem that seems similar to these and produce code that will get appropriate input values and produce an "answer".

In Closing

As you work, remember that the purpose is familiarization with variables, different data types, functions, form element/control properties and expressions. If you have questions, ask. If you are confident you know how to do one of the activities skip it if you want. Be aware that the competency demo questions will likely be similar to what you see here.

Extra Credit

Extra credit will be available to those who produce code to do the tasks noted above and add a report-to-file capability to their program. Perhaps the easiest way to do so is to append each answer to a file when you report it to the screen. I suggest you produce a string that is your "answer" to each problem and report it to the screen and then append it to the file. You will need to include the following code at the top of the Start class (just below Public Class Start

    Public report As IO.StreamWriter

And, insert the following code in the Start form's "load" procedure (double click on the start form and you should be taken to the correct place in the code/.VB file).

    report = IO.File.AppendText("unit-II_report.txt")
    report.WriteLine(DateAndTime.DateString())

And, insert the following code in the btnExit button's (of the Start form) click handler (double click on the and you should be taken to the correct place in the code/.VB file). Be sure to place it before Me.Close()

    report.Close()

Then in the "numerics" and "strings" forms, declare a string to store your answer, use it to report to the screen, then write it to the file, e.g.,

     Dim result as String
     
     '...  declare variables and do whatever is need to get the answer ready

     result = '... set the value of what you plan to report to the screen
     
     '... show your result using   MessageBox.Show(result)  or  txtResult.Text = Result
     
     start.report.WriteLine(result)     'write your result to the file

For example, my solution to #20 might look like

    Dim result as String
    '...  code for previous problems
    
    '. . . . . #20 arbitrary random integer
    Dim lo, hi, randVal As Integer
    lo = Val(txtInput1.Text)
    hi = Val(txtInput2.Text)
    randVal = Fix(Rnd() * (hi - lo + 1)) + lo
     
    result = "#20: A random number in [" & lo.ToString & " ... " & hi.ToString _
             & "] is " & randVal.ToString
    txtResult.Text = result
    
    start.report.WriteLine(result)

To submit your work for extra credit evaluation prepare your program. When done, run it testing each of the problems with 2-3 of values. The file should save the results each time you run it. You can view the file by looking in the projects bin/Debug folder. If you want to start over, just delete it. When done, zip the project (& change its name) and send me an e-mail message:

Final Suggestions

To maximize the learning experience with these examples consider how you might change them to make them "better", functionally or aesthetically. And, devise a VB form for some application or problem from your discipline (or that is of personal interest) that you would like to see implemented. If this activity were graded, some results here would be required for an A.

Remember, have fun! Feel free to embellish what you see. The goal is to familiarize yourself with the form objects and their properties (such as font, size, color etc.).

Process Reminders

Don't forget to use Save All. And, use it early and at least after completing each new task.

If you have problems and want me to examine what is going on

Or, copy your code for the whole form and paste it into the e-mail message.