Hello

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;
	}
	else
		return INT_MIN;          // array is empty so return INT_MIN
}

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.

commented: Beaten :) +36

The check is fine.

The code is broke, if all the elements of the array are negative though.

Another option is set max to a[0] .

one third divided by three fifths equa two forths_

one third divided by three fiths equal two forths

commented: reviving old thread +0

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!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.