# Find the First Negative Number of an Array

• 02-20-2011, 03:56 AM
Cod
Find the First Negative Number of an Array
The code I came up with works if there is only one negative number. If there is more than one negative number, I get a throw exception. Which portion of the code should I be focusing on? Or is there another loop statement needed?

Code:

```      for (int i = 0; i < a.length; i++) {       if (a[i] < 0)         negativeNumbers ++;       }           int j = a.length - 1;           while (j >= 0) {       if (a[j - negativeNumbers] < 0) {         a[j] = 0;         a[j - 1] = a[j - negativeNumbers];         negativeNumbers--;         j--;         }       else         a[j] = a[j - negativeNumbers];         j--;       }```
Any guidance is greatly appreciated.
• 02-20-2011, 04:14 AM
pbrockway2
Quote:

If there is more than one negative number, I get a throw exception. Which portion of the code should I be focusing on?

The bit that's wrong!

To try and isolate which bit that might be, construct a small runnable program that shows this behaviour. Post both the code and the runtime exception (the entire stack trace).

-------------------

Also it will help if you could clarify: are you trying to find something in the array (as the thread title states), or change the array as the code is doing?
• 02-20-2011, 04:19 AM
gcalvin
It's not clear what you're trying to do, but this looks like trouble:
Code:

```    for (int i = 0; i < a.length; i++) {         if (a[i] < 0)             negativeNumbers ++;     }         int j = a.length - 1;         while (j >= 0) {         if (a[j - negativeNumbers] < 0) {             a[j] = 0;             a[j - 1] = a[j - negativeNumbers];             negativeNumbers--;             [COLOR="Blue"]j--;[/COLOR]         }         else             a[j] = a[j - negativeNumbers];         [COLOR="Blue"]j--;[/COLOR]     }```
I've cleaned up your indentation. Note that within your while loop, if the if condition is true you end up decrementing j twice.

-Gary-
• 02-20-2011, 04:34 AM
Cod
Quote:

Originally Posted by pbrockway2
The bit that's wrong!
Also it will help if you could clarify: are you trying to find something in the array (as the thread title states), or change the array as the code is doing?

The goal is to find out if an array has a negative integer. If it does, the program is meant to place a 0 (zero) in the index right after the first negative number and shift subsequent elements to the right, dropping the last element. If there is no negative number, the program should return the original array.

So, to answer your question, the code is trying to find and change.
• 02-20-2011, 04:43 AM
pbrockway2
THanks.

Since you are only finding the first negative value and altering the array from that point on it makes no sense at all to be counting the number of negative values as you do in the first loop.

You should remove this loop and any other code involving this variable.

Quote:

the program is meant to place a 0 (zero) in the index right after the first negative number and shift subsequent elements to the right, dropping the last element

As stated this doesn't make sense. I think you mean shift all elements after the negative one to the right, not those subsequent to the one that was set to zero (because that would leave the slot to the right of the zero without a value.)

Think about how you would try to do this and express your plan in plain English before writing code.
• 02-20-2011, 05:28 AM
Cod
Starting from scratch again...

I have the following code to place a zero after a negative number.
Code:

```    for (int i = 0; i < a.length; i++) {       if (a[i] < 0)         a[i + 1] = 0;     }```
The problem is, it puts a zero behind all negative numbers and takes the place of the element that was directly after the negative number (if it existed).

I cannot figure out / understand how to tell the program to stop going through the motions once it finds the first negative number. Also, I cannot figure out how to shift all the elements after the negative one to the right.

Any further guidance is greatly appreciated.
• 02-20-2011, 05:39 AM
pbrockway2
Code:

```for (int i = 0; i < a.length; i++) {     if (a[i] < 0) {         //a[i + 1] = 0;                 // put code here to work down the array from         // i+1 to the end changing the values.     } }```

The code you use will probably involve another for loop since you are walking down the rest of the array. It may also involve another variable since you have to remember each value you replace so you can use that the next time around the loop.

Again: a precise and clearly expressed plan of attack will help you. Try doing the task yourself with a strip of paper, a pencil and an eraser. You erase a number and write zero, and then what? You need the number you just erased so it can be put in the next slot.
• 02-20-2011, 06:34 AM
Cod
It's safe to say, now I'm lost. I thought I had it with my first go around (counting the negatives, etc.), but obviously that didn't work for multiple negatives. I've been working in my spiral notebook for 45-mins now and can't come up with anything except for this...

Code:

```        int j = 0;         for (int i = 0; i < a.length; i++) {       if (a[i] < 0) {         j = a[i + 1];         a[i + 1] = 0; }     }```

After testing the method, temp gives me the correct numbers which zero takes place of; however, I still don't know how to shift the numbers following the zero to the right without copying the array (which isn't allowed). Also, I still haven't figured out how to keep the zero behind the first negative number only.

Thanks for all the help pbrockway2, but I just don't think I'm going to grasp this method anytime soon.
• 02-20-2011, 07:25 AM
pbrockway2
You need a second for loop inside the if block, not a couple of statements.

The outer for loop takes you to the negative number, the inner one will walk along changing the array values.

Code:

```j=0 a  b  c  -1  d  e  f           * first loop stops here at i=3```

What happens if we swap d and j?

Code:

```j=d  a  b  c  -1  0  e  f             *```

And then swap e and j?

Code:

```j=e a  b  c  -1  0  d  f                 *```
And finally swap f and j?

Code:

```j=f a  b  c  -1  0  d  e                   *```

In short we have to walk down the array swapping the array items with the value of j

Code:

```int j = 0;     for (int i = 0; i < a.length; i++) {     if (a[i] < 0) {         for(int i2 = ???; i2 < ???; i2++) {             // swap the values of a[i2] and j             // this may involve a second variable         }         break; // we've finished!             } }```
• 02-20-2011, 05:10 PM
Cod
The concept I understand, its the implementation giving me an issue. I know exactly how to say it in plain language, but coding language is another story. I'll keep working at it and see where I can get.

Thanks again for the guidance.
• 02-20-2011, 06:30 PM
gcalvin
I would not do two loops. I would do one simple for loop, with an int lastVal variable initialized to 0 and a boolean negFound variable initialized to false -- both initializations outside the loop, of course. My thinking is that you have to do something at every position of the array -- either check if it's negative or shift it right. Storing the initial 0 is simply a special case of shifting right, and is easily handled with the lastVal variable initialized to 0. If you do it this way, you will need another int tmp variable within the loop.

If you do go with two loops instead of one, you may find it easier to start the second loop from the end of the array, heading toward the index where you need to place the 0.

-Gary-
• 02-20-2011, 06:52 PM
Cod
I'm looking at my first try again and trying to figure out how to manipulate the loop to only add a zero after the first negative number...not all.

I've been looking at pbrockway2's loop all morning and still drawing a blank.
• 02-20-2011, 06:59 PM
al_Marshy_1981
Quote:

Originally Posted by Cod
The goal is to find out if an array has a negative integer. If it does, the program is meant to place a 0 (zero) in the index right after the first negative number and shift subsequent elements to the right, dropping the last element. If there is no negative number, the program should return the original array.

So, to answer your question, the code is trying to find and change.

What happens if the negative number is the very last element in the array?