Block of Code

Practical Examples for Programmers

  • Home
  • C++
  • Java
  • Visual Basic
  • Discrete Math
  • Ask a Question

Tipping

Write a program to compute tips for services rendered.  The program should request the person’s occupation, the amount of the bill, and the percentage tip as input and pass this information to a Sub procedure to display the person and the tip.  A sample run is shown in the figure below.

Tipping

Suggested Control Names and Attributes:

Name Property Text Property Control Type Notes
 frmTipping Gratuities Form Holds Controls
 txtOccupation TextBox Captures occupation
 txtBillAmount TextBox Captures total amount of bill
 txtPercentage TextBox Captures percentage of tip
 btnCompute  Compute Tip Button Triggers event to display results
 txtOutput TextBox Displays output.  Read only property set to true.

Hints:

  • Create a function to receive and validate input
  • Create a sub procedure to calculate and display the results.

Write the Code:

' Project: Tipping
' Description: Receives input from user and calculates the tip.

Public Class Tipping
    ' Declare public variables
    Dim occupation As String
    Dim billAmount As Double
    Dim percentage As Double
    Dim tipAmount As Double

    Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click
        If InputIsValid() = True Then
            CalculateValue()
        Else
            MessageBox.Show("Missing or invalid input. Please try again.")
        End If
    End Sub

    Function InputIsValid() As Boolean
        Dim valid As Boolean = True
        occupation = txtOccupation.Text
        If (occupation = "") Then
            MessageBox.Show("Occupation cannot be blank.")
            valid = False
        End If
        If IsNumeric(txtBillAmount.Text) Then
            billAmount = CDbl(txtBillAmount.Text)
            If (billAmount < 0) Then
                MessageBox.Show("Bill amount cannot be negative.")
                valid = False
            End If
        Else
            MessageBox.Show("Bill amount must be numeric.")
            valid = False
        End If
        If IsNumeric(txtPercentage.Text) Then
            percentage = CDbl(txtPercentage.Text)
            If (percentage < 0) Then
                MessageBox.Show("Percentage cannot be negative.")
                valid = False
            End If
        Else
            MessageBox.Show("Percentage must be numeric.")
            valid = False
        End If
        Return valid
    End Function

    Sub CalculateValue()
        tipAmount = billAmount * (percentage / 100)
        txtOutput.Text = ("Tip the " & occupation & " " & tipAmount.ToString("C"))
    End Sub
End Class

Secondary Sidebar

This is the secondary sidebar

Copyright © 2025 · Metro Pro Theme on Genesis Framework · WordPress · Log in