# Check if Array is empty

Page 1 of 1

## 1 Replies - 27102 Views - Last Post: 08 August 2009 - 04:46 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=119113&amp;s=a146a3ce104f91b90a00210df4d39c9e&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 gretty

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

# Check if Array is empty

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

Reputation: 29
• 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