Block of Code

Practical Examples for Programmers

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

Nutrition

The American Heart Association suggests that at most 30% of the calories in our diet come from fat.  Although food labels give the number of calories and amount of fat per serving, they often do not give the percentage of calories from fat.  This percentage can be calculated by multiplying the number of grams of fat in one serving by 9 and dividing that number by the total number of calories per serving.  Write a program that requests the name, number of calories per serving, and the grams of fat per serving as input, and tells whether the food meets the American Heart Association recommendation.  A sample run is shown in the figure below.

Nutrition

Suggested Control Names and Attributes:

Name Property Text Property ReadOnly Property Control Type Notes
 frmNutrition Nutrition N/A Form Holds Controls
 txtFood N/A N/A TextBox Captures name of food
 txtCalories N/A N/A TextBox Captures # of calories
 txtFat N/A N/A TextBox Captures # of fat grams
 btnCompute Compute % Calories from Fat N/A  Button Performs calculations and outputs results
 lstOutput N/A N/A ListBox Displays output

Write the Code:

' Project: Nutrition
' Description:  Determines if a food is approved by AHA standards
'     User inputs the food, calories and grams of fat
'     Fat content and AHA approval is determined and output

Public Class frmNutrition

    Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click
        ' declare local variables
        Dim food As String = " "
        Dim calories As Double = 0
        Dim gramsOfFat As Double = 0
        Dim percentOfCalories As Double = 0

        ' collect data from user and store in variables
        food = txtFood.Text
        calories = CDbl(txtCalories.Text)
        gramsOfFat = CDbl(txtFat.Text)

        ' calculate fat content
        percentOfCalories = ((gramsOfFat * 9) / calories) * 100

        'output results
        lstOutput.Items.Clear()
        lstOutput.Items.Add(food & " contains " & percentOfCalories & "% calories from fat,")
        If (percentOfCalories > 30) Then
            lstOutput.Items.Add("which exceeds AHA recommendation")
        Else
            lstOutput.Items.Add("which meets AHA recommendation.")
        End If

    End Sub
End Class

Secondary Sidebar

This is the secondary sidebar

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