424,986 Members | 2,042 Online
Need help? Post your question and get tips & solutions from a community of 424,986 IT Pros & Developers. It's quick & easy.

# Finding smallest number from user input(array) ?

 P: 2 Okay, so I am making a program that accepts user input of integers. As you can see I am using an array and i need to get the greatest number, and smallest, range, mean, etc. But I successfully did this for the greatest and figured not much would need to be changed but everything I've tried has given me errors of like -8732113 as the smallest. If needed i can post the code with the greatest included, I took it out so i could just focus on this. Expand|Select|Wrap|Line Numbers #include  #include    using namespace std;     void main() {     int nums[50];     int howmany=0;     int largest;     int smallest;     int x;       while(cin >> x)     {         nums[howmany] = x;         howmany++;     }           smallest = nums[0];       for (int s=50; s >= howmany; s--)     {         if(nums[s] <= smallest)             smallest = nums[s];     }             cout << howmany << "\n\n";     cout << smallest << "\n\n";       getche(); } Dec 20 '10 #1
5 Replies

 P: 1 Try initializing smallest and largest with 0. Dec 20 '10 #2

 P: 2 well for the largest on my original code its largest = nums[0] which seemed fine so you're suggesting i use smallest=0 instead of nums[0]?? Dec 20 '10 #3

 P: 5 There is two question in you program, I think. First, the array nums[50] should be initialized. Second, I think there will be a dead loop in lines 15-19. and if you don't want to initialize the array, you can define it as global variables, and the compilier will defautly initialized it with 0; Dec 20 '10 #4

 Expert 100+ P: 2,396 What happens in the user enters more than 50 values? You would write past the end of the array. That would be bad. The first location accessed in your find-minimum loop is nums[50]. This is one slot past the end of the array. It is not good to access past the end of the array. The find-minimum loop examines those locations in the nums array that were not filled with user input; so you're finding the smallest randomly uninitialized value in the unused locations at the end of the array rather than the smallest value entered by the user. You were right to initialize smallest (and largest) to nums[0]. Do not follow the advice of initializing it to zero. What if the smallest user value were 10? You would erroneously report a smallest value of 0. Dec 20 '10 #5

 100+ P: 542 Yes.....a bad suggestion to initialize with 0 Dec 21 '10 #6