c# - Use an array to display a unique set of values -
i'm doing homework problem need write application inputs 5 numbers, each of between 10 , 100, inclusive. each number read, display if not duplicate of number read. provide worst case, in 5 numbers different. use smallest array possible in order solve problem , display complete set of unique values after user inputs each new value.
what have far works correctly. only, keep getting unhandled error once program runs if 5 numbers unique. tells me index goes out of bounds of array. i'm not sure why , can't see errors in loop.
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; namespace ten_seven_thirteen { class program { static void main(string[] args) { const int size = 5; int[] nums = new int[size]; int a; int b; int c = 0; //c amount of numbers entered int number; console.writeline("input 5 numbers between 10 , 100 (inclusive): \n"); (int count = 0; count < size; count++) { number = convert.toint32(console.readline()); if (number >= 10 && number <= 100) //verify whether or not number meets criteria { (a = 0; < c; a++) { // following if condition checks duplicate entrees. if (number == nums[a]) { console.writeline("duplicate number.\n"); break; //breaking loop prevents duplicate number entering array } } // end // if number not duplicate, enter in array if (number != nums[a]) { nums[c++] = number; } // end if - not duplicate console.writeline("the non-duplicate values are:\n"); //display array of unique numbers (b = 0; nums[b] != 0 && b < size; b++) { console.writeline(nums[b]); } // end loop , display array } // end if - validate , test else console.writeline("invalid number."); console.writeline("\n"); } // end - 5 numbers } } }// end ten_seven_thirteen
that's because of code..
for (b = 0; nums[b] != 0 && b < size; b++) { console.writeline(nums[b]); }
you can't check nums[b] there. need figure out better way cut off (i'll leave since it's homework, or can ask in comments). b go size , check nums[size] , last index in nums size - 1, index out of range exception..
also, code won't work because prompts 5 times, regardless of whether or not unique. try different type of loop.
also... off topic, since you're learning: name variables meaningful. a, b, c make cryptic , hard read. won't know you're doing after sleeping. better naming means need less comments because code documents itself. there aren't many comments in professional code, though high school teachers tell there are.
Comments
Post a Comment