In: Computer Science
C# Arrays & methods
I'm having trouble implementing the GetIntArrayFromUser method in the following problem:
Create a method AverageIntArray that takes an array of integers
and calculates and returns the average of all values in the array
as a double Write a program that uses GetIntArrayFromUser method to
get an array of 7 numbers, then calls the AverageIntArray method to
get the average then prints all values in the array that are
greater than the average.
Sample run:
Enter next whole number: 3
Enter next whole number: 8
Enter next whole number: 4
Enter next whole number: 12
Enter next whole number: 13
Enter next whole number: 6
Enter next whole number: 9
Average: 7.85714285714286
8
12
13
9
here is GetIntArrayFromUser:
public void GetIntArrayFromUser()
{
Console.WriteLine("Enter number of list items");
int size = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[size];
for (int i = 0; i < size; i++)
{
Console.WriteLine("Enter next whole number");
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Items in the list: ");
foreach (int item in arr)
{
Console.WriteLine(item);
}
}
Below is your complete code: -
using System;
public class Program
{
public static void Main()
{
int[] arr = GetIntArrayFromUser();
double average = AverageIntArray(arr);
Console.WriteLine("Average: {0}",average);
for(int i = 0; i < arr.Length; i++) {
if(arr[i] > average) {
Console.WriteLine(arr[i]);
}
}
}
public static int[] GetIntArrayFromUser()
{
int count = 0;
int[] arr = new int[7];
while ( count < 7) {
Console.Write("Enter next whole number: ");
arr[count++] = Convert.ToInt32(Console.ReadLine());
}
return arr;
}
public static double AverageIntArray(int[] arr) {
double sum = 0;
for(int i = 0; i < arr.Length; i++) {
sum = sum + arr[i];
}
return sum/(double) arr.Length;
}
}
Output: -
Enter next whole number: 3
Enter next whole number: 8
Enter next whole number: 4
Enter next whole number: 12
Enter next whole number: 13
Enter next whole number: 6
Enter next whole number: 9
Average: 7.85714285714286
8
12
13
9