Java Notes
Practise core Java array logic by finding a largest value, calculating a total, and locating a second-largest distinct value with readable loop-based solutions.
Array problems are mainly loop problems. Before coding, decide what each variable must remember as the loop moves through the array.
Find the largest value
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Start with the first real element rather than 0, because arrays may contain negative values. largest always holds the best value seen so far. When the loop ends, it is the maximum.
Calculate sum and average
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The enhanced for loop is useful when you only need each value, not its index. Cast total to double before division; otherwise integer division would discard the decimal part.
Find the second-largest distinct value
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
largest and secondLargest track two answers during one pass. The value != largest condition keeps a duplicate maximum from being called second-largest. Test an array with one element, all equal values, and negative values.
Practice next
- Reverse an array by swapping values from both ends.
- Count how many times a target value appears.
- Find the smallest value and its index.
- Copy only even values into a second array while counting how many positions are used.
Continue the lesson path