Finding Largest and smallest number in a file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Finding Largest and smallest number in a file

Trying to find the easiest way to find the largest and smallest number in a file using ifstream. Say I have 5 digits in the input file, what’s an easy way to grab those 5 integers, and display the smallest and largest ones? I tried using an empty array size and then just do a for loop that reads the line and assigns it to arr[x] but idk what to do from there. When I try and display the individual values assigned to each array index, it’ll show normal number for the first 4-5 index’s, then it just displays large numbers like 8669278

12th Nov 2019, 5:46 AM
Caleb Nielsen
Caleb Nielsen - avatar
2 Answers
+ 5
Caleb Nielsen please show your attempt. Link the code in your question. How can someone tell you what's wrong without watching your code? also explain how digits are stored in file. are there spaces between digits or not? or are they in a sequence on after another like 1234.... or they are on different lines.? #How to link code https://www.sololearn.com/post/75089/?ref=app
12th Nov 2019, 6:44 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 3
An empty array size won't work. The reason is that the size of an array must be known at compile time. If no size is provided, it is determined by the number of elements in the initializer list. Since you don't initialize the array, its size is effectively 0. Two ways around this: 1. Use vectors. Unlike arrays, their size is not required to be known at compile time, and they can grow and shrink. Here is some info regarding vectors: https://en.cppreference.com/w/cpp/container/vector Once you have all the numbers, applying minmax is easy enough: https://en.cppreference.com/w/cpp/algorithm/minmax_element 2. No need for a container. Instead, two variables are sufficient, one for the smallest and one for the largest value. Initialize the one for the smallest element to the biggest value possible and vice versa, and update them whenever you grab a new number and it is smaller/ bigger than the respective variable. For further questions, seeing your code would be helpful, as mentioned before.
12th Nov 2019, 7:19 AM
Shadow
Shadow - avatar