1 Replies - 16466 Views - Last Post: 08 August 2009 - 04:46 AM Rate Topic: -----

#1 gretty  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 123
  • Joined: 25-May 09

Check if Array is empty

Post icon  Posted 08 August 2009 - 04:01 AM

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 how I can check if the array is empty.

Quote

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
}


This post has been edited by gretty: 08 August 2009 - 04:02 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Check if Array is empty

#2 rs4  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 29
  • View blog
  • Posts: 153
  • Joined: 01-February 09

Re: Check if Array is empty

Posted 08 August 2009 - 04:46 AM

if (n >= 0) {				// does this check if the array is empty??



Yes your along the right track, n gives you the number of ints in the array. If n is 0 the array is empty, but should use if(n > 0) so you don't include 0.

Otherwise everything else seems fine.

Good luck

Edit: forgot to add this, you are asked to find the largest intager, it doesn't specify that it has to be positive. Currently if the array is full of numbers under 0 it will return 0. So you might want to be on the safe side and set;
int max = INT_MIN;

This post has been edited by rs4: 08 August 2009 - 04:52 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1