954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Is my homework Correct :P

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
}
gretty
Junior Poster
158 posts since Apr 2009
Reputation Points: 10
Solved Threads: 7
 

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.

twomers
Posting Virtuoso
1,877 posts since May 2007
Reputation Points: 453
Solved Threads: 57
 

The check is fine.

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

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

Another option is set max to a[0] .

ithelp
Nearly a Posting Maven
Banned
2,230 posts since May 2006
Reputation Points: 769
Solved Threads: 128
 

one third divided by three fifths equa two forths_

hello2
Newbie Poster
2 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

one third divided by three fiths equal two forths

hello2
Newbie Poster
2 posts since Oct 2010
Reputation Points: 10
Solved Threads: 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!!!

Akill10
Posting Pro
575 posts since Sep 2010
Reputation Points: 115
Solved Threads: 80
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You