anansharm
anansharm

Reputation: 193

Remove Negative numbers from array in C

I am trying to remove the negative numbers from array with the following code. Unfortunately, not getting the results. It just prints the first element over and over. Can someone please let me know where am I going wrong?

#include <stdio.h>
void removenegative(int a[],int *p, int *q);
int main()
{
    int a[] = {2, 3, -5, -7, 6, 9};
    int i;
    int *p, *q;
    p = a;
    q = a+6-1;
    removenegative(a, p,q);
    for(i=0;i<6;i++)
        {
            printf("%2d", *p);
        }
    printf("\n");
}
void removenegative(int a[],int *p, int *q)
{
    int *x;
    x= &a[0];
    while (p<=q)
        {
            if (*p>=0)
                {
                    *x = *p;
                    x++;
                }
            p++;
        }
    for( ; x<=q; x++)
        {
            *x = -1;
        }
}

Upvotes: 2

Views: 6959

Answers (5)

Tommy
Tommy

Reputation: 100632

Your code is correct:

void removenegative(int a[],int *p, int *q)
{
    int *x;
    x= &a[0]; // let x point to the first thing in a

    while (p<=q) // continue while p points to an address before q
        {
            if (*p>=0)  // if the thing pointed to by p is greater than zero...
                {
                    *x = *p;  // copy from p to x, increment x
                    x++;
                }
            p++;  // increment p
        }
    for( ; x<=q; x++) // while x is less than q...
        {
            *x = -1;  // fill in -1
        }
}

So x is an incrementing write pointer, while p scans the array and q acts as an end-of-array marker.

As I've been beaten to saying while typing this, your output routine is incorrect.

Upvotes: 1

Barmar
Barmar

Reputation: 781028

Change:

printf("%2d", *p);

to:

printf("%2d", a[i]);

You're looping i, but not using it.

Upvotes: 2

mcleod_ideafix
mcleod_ideafix

Reputation: 11428

It just prints the first element over and over

Of course it does so...

    for(i=0;i<6;i++)
    {
        printf("%2d", *p);
    }

You always print *p, which is a[0]

Upvotes: 4

0xF1
0xF1

Reputation: 6116

You are printing only one value:

printf("%2d", *p);

do this before for loop:

p = a;

and add p++ inside loop;

Upvotes: 4

Guido
Guido

Reputation: 2634

for(i=0;i<6;i++)
    {
        printf("%2d", *p);
    }

You're not changing p!

Upvotes: 4

Related Questions