Amol Sehgal
Amol Sehgal

Reputation: 41

How to delete an element from an array and printing the rest?

I want to print the array as it is after deleting the number 42 from the array. Here's the code which is running fine but I am not able to determine how to delete this one element and printing the rest.

#include <stdio.h>
int main()
    {
        int i,a;
        int arr[]={1,2,42,88,99};
        a=sizeof(arr);
        for(i=0;i<=a;i++)
        {
            printf("%d\n", arr[i]);
            if(arr[i]==42)
                break;
        }
        return 0;
    }
    `

Upvotes: 3

Views: 890

Answers (5)

Mike
Mike

Reputation: 167

writing a code here, which will delete given array elements. the code is :

    //delete elements
countDel=0;
for(i=0;i< n;i++)
{
    if(arr[i]==num)
    {
        countDel++;
        //shift all other elements up
        for(j=i;j< n;j++){
            arr[j]=arr[j+1];
        }
    }
}

Upvotes: 0

L.I.B L.I.B
L.I.B L.I.B

Reputation: 77

You could try this

#include <stdio.h>
int main()
{
    int i,a;
    int arr[]={1,2,42,88,99};
    a=sizeof(arr)/sizeof(arr[0]);
    for(i=0;i<a;i++) 
        if(arr[i]!=42) printf("%d\n", arr[i]);
    return 0;
}

Upvotes: 0

Michi
Michi

Reputation: 5307

Before you code something you need to know what exactly you need and how to code it.

The following things should be fixed:

a=sizeof(arr);

To get the length of the array you need:

a=sizeof arr / sizeof arr[0];

next you have this for:

for(i=0;i<=a;i++){}

here you need to check if i < a and not also to check if i becomes same as a like i == a, change it to:

or(i=0;i<a;i++){}

and here:

if(arr[i]==42)
    break;

You don't need to stop the loop, what you exactly need is to skip that number, this means you need continue here and not break:

if(arr[i]==42){
    continue;
}

and the last thing, move printf("%d\n", arr[i]); after that if.

Now putting all together you have this:

#include <stdio.h>

int main(void){
    int i,a;
    int arr[]={1,2,42,88,99};
    a=sizeof arr / sizeof arr[0];

    for(i=0;i<a;i++){
        if(arr[i]==42){
            continue;
        }
        printf("%d\n", arr[i]);
    }
        return 0;
}

Output:

1
2
88
99

Upvotes: 4

Niketan Raval
Niketan Raval

Reputation: 479

You just need to skip 42 with continue

 if(arr[i]==42)
     continue;
 }
 printf("%d\n", arr[i]);

Upvotes: 0

mikedu95
mikedu95

Reputation: 1736

First:

a = sizeof(arr) / sizeof(int);

Then i < a, not <=

And last, you need continue instead of break.

And you need to put the if before the printf.

Upvotes: 1

Related Questions