user9374267
user9374267

Reputation:

Storing values in an array and outputting the highest,lowest,average. Output flaw

This was a small problem the teacher gave us at school. We were asked to make a program which keeps asking the user to input test scores until he inputs -99 to stop the program. The values are stored in an array and the highest, lowest and average scores are displayed.

The problem I have with my code is that whenever I run it it always gives me a value of 0 for lowest scores even though there are no zeros in the input. Can anyone please point out the mistake in my code?

Code:

static void Main(string[] args)
    {
        int[] za = new int[100];
        scores(za, 0);
    }

 public static void scores(int[] ar, int x)
    {

        Console.Write("Please enter homework score [0 to 100] (-99 to exit): ");
        int a = Convert.ToInt16(Console.ReadLine());
        if (a != -99)
        {
            ar[x] = a;
            x++;
            scores(ar, x);
        }
        else
        {
            Console.Clear();
            Console.WriteLine("Homework App");

            int[] arr = new int[x];
            foreach (int l in arr)
            {
                arr[l] = ar[l];
            }

            int lowest = arr[0];
            for (int i = 1; i < arr.Length; i++)
            {
                if (lowest > arr[i]) { lowest = arr[i]; }
            }

            int highest = arr[0];
            for (int j = 1; j < arr.Length; j++)
            {
                if (highest < arr[j]) { highest = arr[j]; }
            }

            double sum = 0;
            double nums = 0;
            for (int k = 0; k < arr.Length; k++)
            {
                sum = sum + arr[k];
                nums++;
            }
            double average = sum / nums;

            Console.WriteLine("Highest Score: {0}", highest);
            Console.WriteLine("Lowest Score: {0}", lowest);
            Console.WriteLine("Average Score: {0}", average);

            Console.ReadLine();
        }
    }

Upvotes: 0

Views: 61

Answers (1)

Rufus L
Rufus L

Reputation: 37020

When you're copying items, don't use a foreach loop and then the element stored in the array as the index that you're inserting to. Instead, use a for loop with a counter variable.

You should change this:

int[] arr = new int[x];
foreach (int l in arr)
{
    // You're using the wrong value for the index here.
    // l represents the value of the item stored in `arr`, which is `0`
    arr[l] = ar[l]; 
}

To this:

int[] arr = new int[x];
for (var counter = 0; counter < x; counter++)
{
    arr[counter] = ar[counter];
}

Upvotes: 1

Related Questions