burokkori February 2016

C# Keeping sentinel value out of my array

This code works when I enter 10 values. If I enter less my sentinel value is added. I'd like that to stop, as well as being able to manipulate my array length so I don't get however many 0's left when entering less than 10.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace IntegerStatistics
{
class Program
{
    static void Main(string[] args)
    {
        int[] numbers = new int[10];
        int arrayCount, high, low, sum;
        double avg;

        arrayCount = FillArray(numbers);


        Statistics(numbers, arrayCount, out high, out low, out sum, out avg);

        for (int x = 0; x < numbers.Length; ++x)
            Write("{0, 4}", numbers[x]);
        WriteLine();
        WriteLine("The array has {0} values", arrayCount);
        WriteLine("The highest value is {0}", high);
        WriteLine("The lowest value is {0}", low);
        WriteLine("The sum of the array is {0}", sum);
        WriteLine("The average is {0}", avg);

    }

    private static int FillArray(int[] numbers)
    {
         const int QUIT = 999;
        string enterNum;
        int stop;
        int count = 0;
        int addNum = 0;
        stop = numbers.Length - 1;
        while((addNum != QUIT) && (count <= stop))
        {
            Write("Enter a number or 999 to exit: ");
            enterNum = ReadLine();
            while (!int.TryParse(enterNum, out numbers[count]))
                {
                WriteLine("Error");
                Write("Enter a number or 999 to exit: ");
                enterNum = ReadLine();
            }


            numbers[count] = Convert.ToInt32(enterNum);
            addNum = numbers[count];
            ++count;



        }
        return count;


    }

    private static int Statistics(int[] numbers, int arrayCount, out int high, out int low, out int sum, out double avg)
    {
        high = numbers.Max();
         

Answers


dasblinkenlight February 2016

First, let's fix your code, because it is very simple: rather than using numbers.Length in the Main, use arrayCount. This is something that you already have, and it will stop Main from showing zeros at the end.

I'd like [...] to manipulate my array length

Although .NET provides a way to resize an array, this is not something you should be doing in general, because your code quickly becomes hard to read.

A better solution to this problem would be to return a properly sized array from FillArray. However, the best solution is to switch to using List<T>, which are allowed to grow and shrink as needed.


Dave February 2016

I have modified your original program to use a List<int> (good practice) instead of an array of integers which is dynamically re-sized (no so good practice, in general).

class Program
{
    static void Main(string[] args)
    {
        // Use a collection instead of an array, as length is as of yet unknown:
        List<int> numbers;

        int high, low, sum;
        double avg;

        numbers = FillArray();

        Statistics(numbers, out high, out low, out sum, out avg);

        foreach (var number in numbers)
        {
            Console.Write("{0, 4}", number);
        }
        Console.WriteLine();
        Console.WriteLine("The array has {0} values", numbers.Count);
        Console.WriteLine("The highest value is {0}", high);
        Console.WriteLine("The lowest value is {0}", low);
        Console.WriteLine("The sum of the array is {0}", sum);
        Console.WriteLine("The average is {0}", avg);

        Console.ReadKey();

    }

    private static List<int> FillArray(int maximum = 10)
    {
        const int QUIT = 999;
        int count = 0;
        int addNum = 0;
        var list = new List<int>();
        while (count <= maximum)
        {
            Console.Write("Enter a number or 999 to exit: ");
            if (!int.TryParse(Console.ReadLine(), out addNum))
            {
                Console.WriteLine("Error");
                continue;
            }
            if (addNum == QUIT)
            {
                break;
            }
            list.Add(addNum);
            count++;
        }
        return list;
    }

    private static void Statistics(List<int> numbers, out int high, out int low, out int sum, out double avg)
    {
        high = numbers.Max();
        low = numbers.Min();
        sum = numbers.Sum();
        avg = numbers.Average();
    }
}

I also noticed you were including your "escape" value of 999 with your collection o


S. Brentson February 2016

Similar to @Dave. Allows for a value of 999. There's no exception handling, tho...

class Program
    {
        private static string _STOP = "STOP";
        private static int _MAX_SIZE = 10;

        static void Main(string[] args)
        {
            List<int>numbers = FillList();

            foreach(int number in numbers)
                Console.Write("{0, 4}", number);

            Console.WriteLine();
            Console.WriteLine("The list has {0} values", numbers.Count);
            Console.WriteLine("The highest value is {0}", numbers.Max());
            Console.WriteLine("The lowest value is {0}", numbers.Min());
            Console.WriteLine("The sum of the array is {0}", numbers.Sum());
            Console.WriteLine("The average is {0}", numbers.Average());
            Console.ReadKey();

        }

        private static List<int> FillList()
        {
            List<int> numbers = new List<int>();
            int value;
            int count = 0;
            do
            {
                Console.Write("Enter a number or {0} to exit: ", _STOP);
                string line = Console.ReadLine();
                if (line == _STOP)
                    break;

                if (int.TryParse(line, out value))
                {
                    numbers.Add(value);
                    count++;
                }
                else
                {
                    Console.WriteLine("Error reading number.");
                }
            } while (count < _MAX_SIZE);

            return numbers;
        }
    }

Post Status

Asked in February 2016
Viewed 2,217 times
Voted 6
Answered 3 times

Search




Leave an answer