Simple, Quality, Awesome Software

Totaling and Averaging Revisited

Below is the complete code for the Totaling and Averaging Revisited Try It Out! problem.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TotalingAndAveragingRevisited
{
    class Program
    {
        static void Main(string[] args)
        {
            // Set up the array.
            int[] array = new int[] { 4, 51, -7, 13, -99, 15, -8, 45, 90 };

            // Determine the minimum.
            int currentMinimum = Int32.MaxValue;
            foreach (int number in array)
            {
                if (number < currentMinimum) { currentMinimum = number; }
            }
            Console.WriteLine("Minimum: " + currentMinimum);

            // Determine the average value of the array.
            int total = 0;
            foreach (int number in array)
            {
                total += number;
            }
            float average = (float)total / array.Length;
            Console.WriteLine("Average: " + average);

            // Failed attempt to copy the contents of one array to another.
            int[] copy = new int[array.Length];
            foreach (int number in array)
            {
                // We have no clue where to actually stick this.
                //copy[???] = number;
            }

            Console.ReadKey();
        }
    }
}

We are unable to use a foreach loop to copy the contents of one array to another, simply because with a foreach loop, the index variable is gone. This is convenient in many cases, but it’s a problem here, because we don’t know where to place it in the copy array. In a few chapters, we’ll look at the List class. Because we can simply add things to the end of a List, this won’t be a problem there.