Table of Contents

## 1. Detailed Question

Open the Calories **Solution.sln** file contained in the VB2017\Chap08\Calories Solution folder. Open the Code Editor window and locate the **btnDisplay_Click** procedure. The procedure declares and initializes a one-dimensional array named **intCalories**. The array stores the numbers of daily calories consumed. The procedure should calculate and display the average number of calories consumed; use the **Math.Round** method to round the average to an integer. (You learned about the **Math.Round** method in Chapter 6.) The procedure should also display the number of days in which the daily calories were greater than the average, the number of days in which the daily calories were the same as the average, and the number of days in which the daily calories were less than the average. Code the procedure. Save the solution and then start and test the application.

## 2. Problem

Calculate

- Average of Array
- Number of Above Average Elements
- The Number of Below Average Elements
- Number of Average Elements

an Array of VB .Net in Visual Studio Desktop Forms Application.

## 3. Solution Code

Dim intCalories() As Integer = {2, 1, 5, 4, 9, 13, 16} Dim Average As Double = Math.Round(intCalories.Average()) Dim avgBelow As Integer = 0 Dim avgAbove As Integer = 0 Dim avgEqual As Integer = 0 Dim Total As Integer = intCalories.Count() For i As Integer = 0 To Total - 1 If intCalories(i) < Average Then avgBelow += 1 ElseIf intCalories(i) > Average Then avgAbove += 1 Else avgEqual += 1 End If Next lblAvg.Text = average.ToString() lblAboveAvg.Text = avgAbove.ToString() lblAtAvg.Text = avgEqual.ToString() lblBelowAvg.Text = avgBelow.ToString()

## 4. Algorithm of Solution

##### Step 1

Calculate the average of Array using **Average()** function and applied **Round.Math() **to get round off.

Dim Average As Double = Math.Round(intCalories.Average())

##### Step 2

Declared and initialized 3 variables **avgBelow avgAbove avgEqual** equal to zero.

Dim avgBelow As Integer = 0 Dim avgAbove As Integer = 0 Dim avgEqual As Integer = 0

##### Step 3

Count the elements of Array using **.Count()** function.

Dim Total As Integer = intCalories.Count()

##### Step 4

Applied For Loop with IF condition to check each index of array either its equal, above or bellow the average.

For i As Integer = 0 To Total - 1 If intCalories(i) Is Average Then avgBelow += 1 ElseIf intCalories(i) > Average Then avgAbove += 1 Else avgEqual += 1 End If Next

##### Step 5

Set values of **avgBelow, avgAbove, and avgEqual **to the respective textboxes.

lblAvg.Text = average.ToString() lblAboveAvg.Text = avgAbove.ToString() lblAtAvg.Text = avgEqual.ToString() lblBelowAvg.Text = avgBelow.ToString()

## Share Your Comments an Feedback!