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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
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.

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

##### Step 2

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

1 2 3 |
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.

1 |
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.

1 2 3 4 5 6 7 8 9 |
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.

1 2 3 4 |
lblAvg.Text = average.ToString() lblAboveAvg.Text = avgAbove.ToString() lblAtAvg.Text = avgEqual.ToString() lblBelowAvg.Text = avgBelow.ToString() |

## Share Your Comments an Feedback!