How do I find a smallest/biggest int element in an array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

How do I find a smallest/biggest int element in an array

Question

25th Apr 2022, 12:44 PM
FENG LI
FENG LI - avatar
9 Answers
+ 2
I provided the code ,in order to study it and ask something that you don't understand. I think in your case, that some lines of easy code like this helps. However, its not something that I do in every question. I don't provide solutions , but in this case I think providing the solution would help you. Also Note that the code is commented, to understand what every command in every line does.
26th Apr 2022, 12:04 AM
Black Winter
+ 2
Create array, min, and max variables Traverse array First number I array is both min and max Next number is compared against max and swapped if larger & compared against min and swapped if smaller.
25th Apr 2022, 12:49 PM
William Owens
William Owens - avatar
+ 2
There'll be no learning if you don't try yourself, so I'll give an algorithm. Set variable "minnum" and "maxnum" to the first number in the array For every element in the array, if the number is smaller than "minnum", replace minnum with that number. Same goes if a number is bigger than "maxnum". After iterating through the array, print the value of "minnum" and "maxnum"
25th Apr 2022, 12:58 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
Create first an array: int array[5]={-1,0,9,4,3}; Set max and min values equal to the first array element: int max=-1;//the first element of the array int min=-1;//the first element of the array Traverse the array and if an element is higher (for max) or lower(for min) than the current max/min element then update max and min values: for(int i=0;i<5;i++) { if(array[i]>max) { max=array[i];//update max value } if(array[i]<min) { min=array[i];//update min value } } Print the max and the min elements: cout<<"max element="<<max<<"\n"; cout<<"min element="<<min<<"\n"; } That's all.
25th Apr 2022, 12:58 PM
Black Winter
+ 2
Green mod about wrote all the code you need. What other help would you like.
25th Apr 2022, 3:11 PM
William Owens
William Owens - avatar
+ 2
ㅤㅤㅤ Avoid giving finished code as an answer. This defeats SoloLearn purpose, which is to learn to code. Instead, prefer giving hints for people to find the solution.
25th Apr 2022, 3:32 PM
Emerson Prado
Emerson Prado - avatar
+ 1
What if there are two numbers lesser/bigger (in both cases) than the first element in an array, will the compiler choose automatically?.. GUYS!
25th Apr 2022, 3:32 PM
FENG LI
FENG LI - avatar
+ 1
No let's say {5, 8, 9, 1} On first pass Min=5 Max=5 Next iteration Min=5 Max=8 Next iteration Min=5 Max=9 Next iteration Min=1 Max=9
25th Apr 2022, 5:03 PM
William Owens
William Owens - avatar
0
William Owens, Can u just demonstrate??.. please!!
25th Apr 2022, 12:55 PM
FENG LI
FENG LI - avatar