I have this task below & I need someone to tell me if I have done it correctly. The part where I am not sure is if I am correctly checking if the array is empty.

Write a function to find the maximum value in an array of ints a.

int findMax(int a[], int n)
// precondition : a[0..n-1] is an array of ints
// postcondition : returns the maximum value in array or
// INT_MIN if array is empty

Recall that INT_MIN is a predefined constant indicating the minimum value of an integer.

int findMax(int a[], int n) {
	/// Homework 2 ///

	int max = 0;

	if (n >= 0) {                // does this check if the array is empty??
		for (int i=0; i<n; i++) {
			if (a[i] > max) { max = a[i]; }
		return max;
		return INT_MIN;          // array is empty so return INT_MIN
7 Years
Discussion Span
Last Post by Akill10

Consider what happens if all the numbers in the array are negative. Then the if(a[i]>max) will never return true. There are two ways you can do this. Either set max to INT_MIN or set max to a[0] and loop from 1 to n then.

Beaten :)

one third divided by three fiths equal two forths

Aug 8th, 2009
Is my homework Correct :P

Please READ the original posts date before reviving old threads!!!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.