Find High / Low Value in Array (Definitive Series)

Welcome to another kick ass entry of the Programming Underground. On today’s entry we explore a basic way to find the high and low values in an array as part of our Definitive Series. For those of you who are not familiar with my Definitive Series, it is the exploration of a concept and examples provided for 5 major languages (C++/C#/VB.NET/Java/PHP). Doing a search on my blog will also uncover other entries I have made under this series. Think of it as a mutating cytoplasmic organism entry that is destined to take over the world and can morph between languages! Or something like that. This entry is targeting the newbies out there looking for a quick explanation and examples they can use. It has been a popular question as of late on the boards, so I thought I would give you the 411 on this nice little problem. So strap on the battle helmet and jump in the X-Wing fighter, we are going into Programming Underground!

So you have an array full of numbers, maybe grade percentages, and you want to find your top student or the student who is flunking the class in a major way. You could probably walk up to these students and either congratulate them or scold them to do better. Of course that is assuming the flunking student isn’t bigger than you. How do we find the values? The process is pretty straight forward once you know where to start.

The concept starts with creating two variables. One to hold our high value and one to hold the low value. At the end of our program these two values will of course hold the highest value in the array and the lowest value respectively. Most newbies I have encountered want to set these two values to some arbitrary number like 0 or even leave it blank. The trick is, set them both to the first value of your array. If the first value of the array is the lowest or highest, then that variable will never be changed and you already have your answer. However, the chances are that the lowest or highest values are not always going to be the first value.

Once we have these two values setup to the first value of the array, we are already half way there. Loop through the entire array and compare each value in the array to see if it is lower than the lowest value variable and if it is higher than the highest value variable. In the examples that follow, I broke this mechanism into two separate functions so that people who want to rip off the code (oh yeah I know it happens) can actually rip out the low value or high value detection separately. Plus it makes it simple to demonstrate the mechanism for both finding the high and low values of the array. But you can certainly merge the two to find them simultaneously in one function and iterate the array once for performance sake. It will be up to you how you want to do it.

If we come across a value in the array that is lower than our lowest value variable, we will then set the lowest value variable to that new value. Same the high value variable. If the value is higher than the recorded highest value variable, we will set it to the new high value.

At the end of the loop, the highest value will be in the highest value variable and the lowest will be in the lowest value variable.

Simple enough huh? Lets show how this is done in C++…

#include <iostream>
using namespace std;

// Declarations
int findHighScore(int [], int);
int findLowScore(int [], int);

// Main function
int main() {

	// Declare array and fill it with values.
	int scores[10];

	scores[0] = 21;
	scores[1] = 1;
	scores[2] = 5;
	scores[3] = 24;
	scores[4] = 7;
	scores[5] = 3;
	scores[6] = 4;
	scores[7] = 11;
	scores[8] = 2;
	scores[9] = 9;

	// Call our functions to find high score and low score
	int high = findHighScore(scores,10);
	int low = findLowScore(scores,10);

	// Print out the high and low scores.
	cout << "High score is: " << high << " and low score is: " << low << endl;


	return 0;
}

// findHighScore() loops through the array and records the highest value found and returns it.
int findHighScore(int scores[], int size) {
	int highscore = scores[0];
	for (int i = 0; i < size; i++) {

		// If the current score is higher than our last recorded score, record it as the new high score.
		if (scores[i] > highscore) {
			highscore = scores[i];
		}
	}

	return highscore;
}

// findLowScore() loops through the array and records the lowest value found and returns it.
int findLowScore(int scores[], int size) {
	int lowscore = scores[0];
	for (int i = 0; i < size; i++) {

		// If the current score is lower than our last recorded score, record it as the new low score.
		if (scores[i] < lowscore) {
			lowscore = scores[i];
		}
	}

	return lowscore;
}

You can see the steps in this program by reading through the in-code comments. The comments will be virtually the same for all of these examples and you will see that the code similarities between languages is very subtle. So even if you don’t know one of the other languages, you can still read the differences and know where things are going.

Here is the program in C# console application….

static void Main(string[] args)
{
			// Declare array and fill it with values.
			int[] scores = new int[10];

			scores[0] = 21;
			scores[1] = 1;
			scores[2] = 5;
			scores[3] = 24;
			scores[4] = 7;
			scores[5] = 3;
			scores[6] = 4;
			scores[7] = 11;
			scores[8] = 2;
			scores[9] = 9;

			// Call our functions to find high score and low score
			int high = findHighScore(scores);
			int low = findLowScore(scores);

			// Print out the high and low scores.
			System.Console.WriteLine("High score is: " + high + " and low score is: " + low);
			
}

// findHighScore() loops through the array and records the highest value found and returns it.
static int findHighScore(int[] scores) {
			int highscore = scores[0];
			for (int i = 0; i < scores.Length; i++) {

				// If the current score is higher than our last recorded score, record it as the new high score.
				if (scores[i] > highscore) {
					highscore = scores[i];
				}
			}

			return highscore;
}

// findLowScore() loops through the array and records the lowest value found and returns it.
static int findLowScore(int[] scores) {
			int lowscore = scores[0];
			for (int i = 0; i < scores.Length; i++) {

				// If the current score is lower than our last recorded score, record it as the new low score.
				if (scores[i] < lowscore) {
					lowscore = scores[i];
				}
			}

			return lowscore;
}

As you can see from the C# example, all the pieces are pretty much the same except for defining these functions without needing to pass in a size for the array. The reason is that we can get the size of the array using the length property of the array passed to the function. Other than that and defining the functions as static (so they can be used from static main) they are virtually identical.

Again here is the program in Java…

public class findhighlow {
	public static void main(String args[]) {
		// Declare array and fill it with values.
		int[] scores = new int[10];

		scores[0] = 21;
		scores[1] = 1;
		scores[2] = 5;
		scores[3] = 24;
		scores[4] = 7;
		scores[5] = 3;
		scores[6] = 4;
		scores[7] = 11;
		scores[8] = 2;
		scores[9] = 9;

		// Call our functions to find high score and low score
		int high = findHighScore(scores);
		int low = findLowScore(scores);

		// Print out the high and low scores.
		System.out.println("High score is: " + high + " and low score is: " + low);


	}

	// findHighScore() loops through the array and records the highest value found and returns it.
	private static int findHighScore(int scores[]) {
		int highscore = scores[0];
		for (int i = 0; i < scores.length; i++) {

			// If the current score is higher than our last recorded score, record it as the new high score.
			if (scores[i] > highscore) {
				highscore = scores[i];
			}
		}

		return highscore;
	}

	// findLowScore() loops through the array and records the lowest value found and returns it.
	private static int findLowScore(int scores[]) {
		int lowscore = scores[0];
		for (int i = 0; i < scores.length; i++) {
	
			// If the current score is lower than our last recorded score, record it as the new low score.
			if (scores[i] < lowscore) {
				lowscore = scores[i];
			}
		}

		return lowscore;
	}

}

Again the Java is very similar to both the C++ and C# in that it has its roots in the C++ world. These are defined in a static context as well since we are calling them from static main and they too do not need to have the size of the array passed to the functions because of using the length property like in C#.

Here is the program in VB.NET….

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		' Declare array and fill it with values.
		Dim scores(9) As Integer

		scores(0) = 21
		scores(1) = 1
		scores(2) = 5
		scores(3) = 24
		scores(4) = 7
		scores(5) = 3
		scores(6) = 4
		scores(7) = 11
		scores(8) = 2
		scores(9) = 9

		' Call our functions to find high score and low score
		Dim high As Integer = findHighScore(scores)
		Dim low As Integer = findLowScore(scores)

		' Print out the high and low scores.
		Label1.Text = "High score is: " & high & " and low score is: " & low
End Sub


' findHighScore() loops through the array and records the highest value found and returns it.
Private Function findHighScore(ByVal scores() As Integer) As Integer
		Dim highscore As Integer = scores(0)
		Dim i As Integer

		For i = 0 To scores.Length - 1

			' If the current score is higher than our last recorded score, record it as the new high score.
			If scores(i) > highscore Then
				highscore = scores(i)
			End If
		Next

		Return highscore
End Function

' findLowScore() loops through the array and records the lowest value found and returns it.
Private Function findLowScore(ByVal scores() As Integer) As Integer
		Dim lowscore As Integer = scores(0)
		Dim i As Integer

		For i = 0 To scores.Length - 1

			' If the current score is higher than our last recorded score, record it as the new high score.
			If scores(i) < lowscore Then
				lowscore = scores(i)
			End If
		Next

		Return lowscore
End Function

Here the two functions look quite a bit different in that VB syntax is a little more wordy and drawn out. So follow the in code comments and you will see where things are the same and different. We are also calling this from a button click event and printing the output to a simple label called “Label1”. This is one way you can incorporate this functionality into a more GUI style application. You could have done the same thing back in the C# example.

Lastly the PHP example for all you web techs out there…

<?php

function findhighlow() {

	// Declare array and fill it with values.
	$scores = array(21, 1, 5, 24, 7, 3, 4, 11, 2, 9);


	// Call our functions to find high score and low score
	$high = findHighScore($scores);
	$low = findLowScore($scores);

	// Print out the high and low scores.
	echo "High score is: $high and low scores is: $low";
}

// findHighScore() loops through the array and records the highest value found and returns it.
function findHighScore($scores) {
	$highscore = $scores[0];
	for ($i = 0; $i < count($scores); $i++) {

		// If the current score is higher than our last recorded score, record it as the new high score.
		if ($scores[$i] > $highscore) {
			$highscore = $scores[$i];
		}
	}

	return $highscore;
}

// findLowScore() loops through the array and records the lowest value found and returns it.
function findLowScore($scores) {
	$lowscore = $scores[0];
	for ($i = 0; $i < count($scores); $i++) {

		// If the current score is lower than our last recorded score, record it as the new low score.
		if ($scores[$i] < $lowscore) {
			$lowscore = $scores[$i];
		}
	}

	return $lowscore;
}



// Now we simply call our functions to find the output

findhighlow();

?>

We created a main findhighlow() main function which calls our other two functions. The variables are the same as the other programs, but that we change around the signature of the functions a little and get rid of all the datatyping (since PHP of course juggles types). To handle the size of the array, we call the count() function and with that we can loop through the array. Here we could have also done a foreach through the array, but to stay in line with the other programs I have kept the for loop counting structure.

So there you go, finding the high and low values of an array doesn’t have to be a chore. Being in an array actually simplifies the project because we can use various loop styles to move through the array and compare values. Just remember that you compare each value in the array to some variables outside the loop. If you accidentally put this variable inside the loop, you will get unexpected results like it saying the last value of the array is always the highest/lowest even if it isn’t.

Take this knowledge to a party, wow the ladies, setup some cheetos on the table and compare them to one another to find the biggest or smallest. Maybe you will get lucky and one of them will want to take you home to do some more action packed sorting of emotional issues! If you know what I mean.

Thanks for reading! 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.