C# Keeping sentinel value out of my array -
this code works when enter 10 values. if enter less sentinel value added. i'd stop, being able manipulate array length don't many 0's left when entering less 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); (int x = 0; x < numbers.length; ++x) write("{0, 4}", numbers[x]); writeline(); writeline("the array has {0} values", arraycount); writeline("the highest value {0}", high); writeline("the lowest value {0}", low); writeline("the sum of array {0}", sum); writeline("the average {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 number or 999 exit: "); enternum = readline(); while (!int.tryparse(enternum, out numbers[count])) { writeline("error"); write("enter number or 999 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(); low = numbers.min(); sum = numbers.sum(); avg = numbers.average(); return arraycount; } }
}
first, let's fix code, because simple: rather using numbers.length
in main
, use arraycount
. have, , stop main
showing zeros @ end.
i'd [...] manipulate array length
although .net provides way resize array, not should doing in general, because code becomes hard read.
a better solution problem return sized array fillarray
. however, best solution switch using list<t>
, allowed grow , shrink needed.
Comments
Post a Comment