Im working on an assignment in which I have to find the highest value in an array using a for loop, and without sorting it. I feel like what I have so far is close to being correct but not quite there. Below is an example of the code I have so far.
NSArray *unsortedArray = @[ @2, @44, @11, @99, @35 ];
for (int i = 0; i < 4 ; i++) {
id number = [unsortedArray objectAtIndex:i];
id largestNumber = 0;
if (largestNumber < number) {
largestNumber = number;
NSLog(@"%@ is the largest number", largestNumber );
return 0;
}
}
Now this is only returning the first value in the area then the loop is stopping, am I assigning the wrong values to largestNumber and number? Very new to code, so I would appreciate and feedback and examples.
Thanks!
To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.
The max() method of java. util. Collections class is used to return the maximum element of the given collection, according to the natural ordering of its elements.
Key-Value-Coding solution, no loop
NSArray *unsortedArray = @[ @2, @44, @11, @99, @35 ];
NSNumber *maxNumber = [unsortedArray valueForKeyPath:@"@max.self"];
NSLog(@"%@", maxNumber); // 99
See this interesting article by Mattt Thompson: KVC Collection Operators
KVC answer is best, but if you want to do it with a loop..
NSArray *unsortedArray = @[ @2, @44, @11, @99, @35 ];
NSNumber *l = [unsortedArray objectAtIndex:0];
for (int i = 1; i < 5; i++) {
l = ([[unsortedArray objectAtIndex:i]integerValue] > [l integerValue] ? [unsortedArray objectAtIndex:i]:l);
}
NSLog(@"Largest = %@\n",l);
Also, given you have five objects in the array, your loop invariant must test for i < 5
, not i < 4
. That will stop at index 3, when you should stop after index 4. Finally, this compares integer values only as it stands, if you want to compare floating point or other numeric types. You should remember to specify the appropriate property. You can see them all here.
Edit: (Downvotes for what? This answer is correct..)
To clarify since you're new, an if
statement can also be written as follows:
a = (b > c ? (return this if true):(return this if false)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With