Hello i\'m trying for about 2 hours to create a program which will remove even numbers from a dinamyc allocated array(with malloc)in c.Can somebody help me with some tips or cre
Let's assume that you already allocated dynamically an array of n elements and initialized it.
In this case the function that removes elements with even values can look the following way
size_t remove_even( int *a, size_t n )
{
size_t m = 0;
for ( size_t i = 0; i < n; i++ )
{
if ( a[i] % 2 != 0 )
{
if ( i != m ) a[m] = a[i];
++m;
}
}
return m;
}
It can be called the following way
size_t m = remove_even( p, n );
for ( size_t i = 0; i < m; i++ ) printf( "%d ", a[i] );
printf( "\n" );
where p is the pointer to your dynamically allocated array of n elements.
The function actually removes nothing. It simply moves odd elements to the beginning of the array.
You can then use standard C function realloc
to delete physically the removed elements.
For example
int *tmp = realloc( p, m * sizeof( int ) );
if ( tmp != NULL ) p = tmp;
Here is a demonstrative program
#include <stdlib.h>
#include <stdio.h>
size_t remove_even( int a[], size_t n )
{
size_t m = 0;
for ( size_t i = 0; i < n; i++ )
{
if ( a[i] % 2 != 0 )
{
if ( i != m ) a[m] = a[i];
++m;
}
}
return m;
}
#define N 10
int main( void )
{
int *a = malloc( N * sizeof( int ) );
for ( size_t i = 0; i < N; i++ ) a[i] = i;
for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
printf( "\n" );
size_t m = remove_even( a, N );
int *tmp = realloc( a, m * sizeof( int ) );
if ( tmp != NULL ) a = tmp;
for ( size_t i = 0; i < m; i++ ) printf( "%d ", a[i] );
printf( "\n" );
free( a );
}
Its output is
0 1 2 3 4 5 6 7 8 9
1 3 5 7 9
There are some things which you need to check before you try to code something, but I see that there is no code which you showed use.
SO is not a tutorial site, so this means that you should show us some code which actually does compile and ask here if there are some problems with that code.
Any way until than, this code should give you an Idea about how to check if a Number is odd
or even
:
#include<stdio.h>
#include<stdlib.h>
int main(void){
int n;
printf("Enter an integer:> ");
if((scanf("%d", &n)) != 1){
printf("Error, Fix it!\n");
exit(1);
}
if (n%2 == 0){
printf("Even\n");
}else{
printf("Odd\n");
}
return 0;
}
The whole story here is not about checking if Numbers inside an Array are odd
or even
, is about to find a way to check if a number is odd
or even
and only then you should check if inside that array there are odd
or even
numbers. I hope you understand my point.