- 1
How do I find a smallest/biggest int element in an array
Question
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.
+ 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.
+ 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"
+ 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.
+ 2
Green mod about wrote all the code you need.
What other help would you like.
+ 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.
+ 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!
+ 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
0
William Owens,
Can u just demonstrate??.. please!!