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 create the code.
p.s. this is my first topic here, so feel free to give me some tips about how to correctly post a qustion.
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.
One easy way to remove even numbers from an array in C is to create a new array of all odd elements starting from 1 to the maximum element present in the original array and then compare the original array and odd elements array (and do intersection) and put it in another array with same elements present in both arrays.
Here is the program:
#include<stdio.h>
int main(){
int a[20],n,i,max,j,k=0,l=0;
printf("enter limit of array ");
scanf("%d",&n);
printf("enter the elements ");
for (i=0;i<n;i++){
scanf("%d",&a[i]);
}
max=a[0];
for (i=0;i<n;i++){
if (a[i]>max){
max=a[i];
}
}
int b[max],c[n],count=0;
for (j=2;j<=max;j=j+2){
c[k++]=j;
count++;
}
for (i=0;i<n;i++){
for (j=0;j<count;j++){
if (a[i]==c[j])
b[l++]=a[i];
}
}
for (i=0;i<count;i++){
printf("%d ",b[i]);
}
return 0;
}
Related
#include <stdio.h>
int removeduplicates(int arr[],int n){
int j=0;
int temp[15];
if(n==0 || n==1){
return n;
}
for(int i=0;i<n-1;i++){
if(arr[i]!=arr[i+1]){
temp[j++]=arr[i];
}
temp[j++]=arr[n-1];
}
for(int i=0;i<j;i++){
arr[i]=temp[i];
}
return j;
}
int main(){
int n;
int num[];
num[]= {1,2,3,3,4,4,5,5,5};
n= sizeof(num)/sizeof(num[0]);
n=removeduplicates(num,n);
printf("%d",n);
return 0;
}
Here in this question I was writing a code to remove duplicates from a sorted array. But I am getting the following error although I defined the array size and although I provided the array size.
main.c:36:9: error: array size missing in ‘num’
int num[];
^~~
main.c:37:9: error: expected expression before ‘]’ token
num[]= {1,2,3,3,4,4,5,5,5};
This code snippet
int num[];
num[]= {1,2,3,3,4,4,5,5,5};
is syntactically incorrect.
Instead write
int num[] = {1,2,3,3,4,4,5,5,5};
Also within the function this declaration with the magic number 15
int temp[15];
and this statement
temp[j++]=arr[n-1];
in the substatement of this for loop
for(int i=0;i<n-1;i++){
if(arr[i]!=arr[i+1]){
temp[j++]=arr[i];
}
temp[j++]=arr[n-1];
}
do not make a sense.
To remove duplicates there is no need to define an auxiliary array.
The function can be written for example the following way as shwon in the demonstrative program below.
#include <stdio.h>
size_t removeduplicates( int arr[], size_t n )
{
size_t m = 0;
for ( size_t i = 0; i != n; )
{
if ( m != i )
{
arr[m] = arr[i];
}
++m;
while ( ( ++i != n && arr[i] == arr[i-1] ) );
}
return m;
}
int main(void)
{
int num[]= { 1, 2, 3, 3, 4, 4, 5, 5, 5 };
const size_t N = sizeof( num ) / sizeof( *num );
for ( size_t i = 0; i != N; i++ )
{
printf( "%d ", num[i] );
}
putchar( '\n' );
size_t m = removeduplicates( num, N );
for ( size_t i = 0; i != m; i++ )
{
printf( "%d ", num[i] );
}
putchar( '\n' );
return 0;
}
The program output is
1 2 3 3 4 4 5 5 5
1 2 3 4 5
I want to print the number of unique elements instead of show the elements For example show 4. Means we have 4 unique elements
#include<stdio.h>
#define max 100
int ifexists(int z[], int u, int v)
{
int i;
for (i=0; i<u;i++)
if (z[i]==v) return (1);
return (0);
}
void main()
{
int p[max], q[max];
int m;
int i,k;
k=0;
printf("Enter length of the array:");
scanf("%d",&m);
printf("Enter %d elements of the array\n",m);
for(i=0;i<m;i++ )
scanf("%d",&p[i]);
q[0]=p[0];
k=1;
for (i=1;i<m;i++)
{
if(!ifexists(q,k,p[i]))
{
q[k]=p[i];
k++;
}
}
printf("\nThe unique elements in the array are:\n");
for(i = 0;i<k;i++)
printf("%d\n",q[i]);
}
https://onlinegdb.com/Bk3tvQMpw
Sort the array then iterate through the elements and print out if the current element is different than the last:
int cmpint(const void *a, const void *b) {
return *(int *) a) < *(int *) b :
-1 ?
(
*(int *) b) < *(int *) a ?
1 :
0
);
}
int main() {
/* ... */
qsort(p, m, sizeof(*p), cmpint);
int n = 0;
for(int i = 0; i < m; i++) {
if(!i || p[i-1] != p[i]) n++;
}
printf("Number of unique elements: %d\n", n);
}
where p is your now sorted array and length is m as per example code. As qsort is expected O(m *log(m)) so will this aglorithm. If you don't sort the array it will be O(m^2) due to m linear searches.
If I have understood the question correctly what you need is to count unique elements in an array using a function and without defining an auxiliary array. That is there is no need to output the unique elements themselves.
In this case the corresponding function can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
int is_unique( const int a[], size_t n, int value )
{
while ( n != 0 && a[ n - 1 ] != value ) --n;
return n == 0;
}
int main(void)
{
int a[] = { 1, 2, 3, 3, 2, 1 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t count = 0;
for ( size_t i = 0; i < N; i++ )
{
count += is_unique( a, count, a[i] );
}
printf( "There are %zu unique elements in the array.\n", count );
return 0;
}
The program output is
There are 3 unique elements in the array.
If you do not want to define one more function to count unique elements in an array then just move the loop in the function shown in the above demonstrative program inside main.
Here you are.
#include <stdio.h>
int main(void)
{
int a[] = { 1, 2, 3, 3, 2, 1 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t count = 0;
for ( size_t i = 0; i < N; i++ )
{
size_t j = i;
while ( j != 0 && a[j - 1] != a[i] ) --j;
count += j == 0;
}
printf( "There are %zu unique elements in the array.\n", count );
return 0;
}
The program output is the same as shown above that is
There are 3 unique elements in the array.
Pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )
instead of
void main()
Do I use correctly free() in the code below? Is it a memory leak? Is it a problem use free() in the main part and not in the function? If yes there is a method to free in the function and not in main?
This code copy an array in another one.
int *copy(const int *arr,int n);
int main(){
int *p_arr1,*p_arr2;
int n,i;
printf("Insert size of array: ");
scanf("%d",&n);
p_arr1 = calloc(n,sizeof(int));
for(i=0;i<n;i++){
printf("Insert element %d of the array: ",i+1);
scanf("%d",p_arr1+i);
}
p_arr2 = copy(p_arr1,n);
for(i=0;i<n;i++){
printf("%d ",*p_arr2);
p_arr2++;
}
free(p_arr1);
free(p_arr2);
return 0;
}
int *copy(const int *arr,int n){
int i;
int *new;
new = calloc(n, sizeof(int));
for(i=0;i<n;i++){
new[i] += arr[i];
}
return new;
}
As long as you have the pointer returned by malloc (or in your case calloc) you can pass it to free when and wherever you want, it doesn't have to be in the same function.
However, after the loop where you print the contents of p_arr2, you no longer have the pointer returned by calloc inside the function, because you modify the pointer in the loop.
You need to use a temporary pointer variable for the loop:
int *p_arr2_tmp = p_arr2;
for (size_t i = 0; i < n; ++i)
{
printf("%d ", *p_arr2_tmp);
++p_arr2_tmp;
}
// Now we can free the memory pointed to by the original p_arr2 pointer
free(p_arr2);
Or you could use simple array indexing instead:
for (size_t i = 0; i < n; ++i)
{
printf("%d ", p_arr2[i]);
}
// The pointer p_arr2 wasn't modified, so it can be passed to free
free(p_arr2);
In this loop
for(i=0;i<n;i++){
printf("%d ",*p_arr2);
p_arr2++;
}
the value of the pointer p_arr2 is being changed, So using the changed pointer in a call of free results in undefined behavior.
You should write
for(i=0;i<n;i++){
printf("%d ", p_arr2[i] );
}
Also it is unclear why you are using the compound operator += in the function instead of the operator =.
new[i] += arr[i];
The function can be defined the following way
int * copy( const int *arr, size_t n )
{
int *new_arr = malloc( n * sizeof( int ) );
if ( new_arr != NULL )
{
memcpy( new_arr, arr, n * sizeof( int ) );
}
return new_arr;
}
If you want to use a pointer in the loop that outputs the newly created array then it can look the following way
for ( const int *p = p_arr2; p != p_arr2 + n; ++p )
{
printf( "%d ",*p );
}
putchar( '\n' );
If the aim is to write a program that uses only pointers and excludes using of the subscript operator and indices then your program can look the following way
#include <stdio.h>
#include <stdlib.h>
int * copy( const int *arr, size_t n )
{
int *new_arr = malloc( n * sizeof( int ) );
if ( new_arr != NULL )
{
for ( int *p = new_arr; p != new_arr + n; ++p )
{
*p = *arr++;
}
}
return new_arr;
}
int main(void)
{
size_t n;
printf( "Insert size of array: " );
scanf( "%zu", &n );
int *p_arr1 = calloc( n, sizeof( int ) );
for ( int *p = p_arr1; p != p_arr1 + n; ++p )
{
printf( "Insert element %d of the array: ", ( int )( p - p_arr1 + 1 ) );
scanf( "%d", p );
}
int *p_arr2 = copy( p_arr1, n );
if ( p_arr2 != NULL )
{
for ( const int *p = p_arr2; p != p_arr2 + n; ++p )
{
printf( "%d ",*p );
}
putchar( '\n' );
}
free( p_arr2 );
free( p_arr1 );
return 0;
}
The program output might look like
Insert size of array: 10
Insert element 1 of the array: 0
Insert element 2 of the array: 1
Insert element 3 of the array: 2
Insert element 4 of the array: 3
Insert element 5 of the array: 4
Insert element 6 of the array: 5
Insert element 7 of the array: 6
Insert element 8 of the array: 7
Insert element 9 of the array: 8
Insert element 10 of the array: 9
0 1 2 3 4 5 6 7 8 9
I apologize if this question seems too vague, but I am a complete beginner and I am stuck on how to count instances of numbers from an array.
I have a function called create_hist() which has three inputs: an input double array for which the numbers range from 0 to 16, an input integer which indicates how many elements are in the array, and an output integer array of size 17. The goal is to count how many of each numbers are in the first array, and then assign that number to the correct index of the output array i.e:
If the input array contains {0,1,1,2,3,4,4} then the count will be 7, and the output array should be {1,2,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0}.
I am very new to C programming and I don't know where to start. My thoughts were that I could iterate through each element in the input array, and if the element was equal to zero, then add 1 to the first index of the output array and so on. I know this is wrong but I don't know another way. Could someone please guide me on how I could begin this? My first attempt is below.
int create_hist( double input_array[], int count, int hist[17] ) {
for ( int i = 0; i < count; i++ ) {
if ( input_array[i] == 0; ) {
// then add 1 to hist[0]
}
if ( input_array[i] == 1; ) {
// then add 1 to hist[1]
// etc.
}
}
You're not a million miles away from a good solution. If you already have count available to pass in, that's handy. Otherwise, you can replace it with:
sizeof(input_array)/sizeof(double)
If you know for sure the maximum value that can appear in input array, then the rest of the problem should be pretty easy.
Loop through each item in input_array, like you're already doing. Then increment the index of histwhich relates to the value of the current item, like so:
for(int i = 0; i<count; i++){
hist[input_array[i]]++;
}
This should give the output you're looking for. For future reference, this is called a count occurrence algorithm.
The function can look the following way
size_t create_hist( const double in[], size_t n, int out[] )
{
const size_t N = 17;
memset( out, 0, N * sizeof( *out ) );
for ( size_t i = 0; i < n; i++ ) ++out[( size_t )in[i]];
size_t m = 0;
for ( size_t i = 0; i < N; i++ )
{
if ( out[i] ) ++m;
}
return m;
}
Here is a demonstrative program
#include <stdio.h>
#include <string.h>
#define SIZE 17
size_t create_hist( const double in[], size_t n, int out[] )
{
const size_t N = SIZE;
memset( out, 0, N * sizeof( *out ) );
for ( size_t i = 0; i < n; i++ ) ++out[( size_t )in[i]];
size_t m = 0;
for ( size_t i = 0; i < N; i++ )
{
if ( out[i] ) ++m;
}
return m;
}
int main(void)
{
double a[] = { 0, 1, 1, 2, 3, 4, 4 };
int b[SIZE];
size_t n = create_hist( a, sizeof( a ) / sizeof( *a ), b );
printf( "There are %zu unique elements\n", n );
for ( size_t i = 0; i < SIZE; i++ ) printf( "%d ", b[i] );
putchar( '\n' );
return 0;
}
Its output is
There are 5 unique elements
1 2 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0
#include<stdio.h>
int find( int, int parent[10] );
int uni( int, int, int parent[10] );
int main()
{
int i, j, k, a, b, u, v, n, ne = 1;
int min, mincost = 0, cost[9][9], parent[9];
printf( "\n\tImplementation of Kruskal's algorithm\n" );
printf( "\nEnter the no. of vertices:" );
scanf( "%d", &n );
printf( "\nEnter the cost matrix:\n" );
for ( i = 1; i <= n; i++ )
{
for ( j = 1; j <= n; j++ )
{
printf( "Enter the cost of the edge(%d,%d)=", i, j );
scanf( "%d", &cost[i][j] );
if ( cost[i][j] == 0 )
{
cost[i][j] = 999;
}
}
}
printf( "The edges of Minimum Cost Spanning Tree are\n" );
while ( ne < n )
{
for ( i = 1, min = 999; i <= n; i++ )
{
for ( j = 1; j <= n; j++ )
{
if ( cost[i][j] < min )
{
min = cost[i][j];
a = u = i;
b = v = j;
}
}
}
u = find( u, parent );
v = find( v, parent );
if ( uni( u, v, parent ) == 1 )
{
printf( "%d edge (%d,%d) =%d\n", ne++, a, b, min );
mincost += min;
}
cost[a][b] = cost[b][a] = 999;
}
printf( "\n\tMinimum cost = %d\n", mincost );
}
int uni( int i, int j, int parent[10] )
{
if ( i != j )
{
parent[j] = i;
return 1;
}
return 0;
}
int find( int i, int parent[10] )
{
while ( parent[i] )
{
i = parent[i];
}
return i;
}
It is not able to calculate u,v,uni... i am able to enter the values but i am getting a message segmentation fault (core dumped). i guess there is some problem with the function find and uni(may be in passing of the array parent)..
Without trying to decipher what the code is actually about (single-letter variables, zero comments, no link to this "Kruskal's algorithm" or anything), and in addition to what I already wrote in my comment about adding printf()s to log intermediate values, checking scanf() return codes, mirroring user input back at the user, and sprinkling your code with assert()s...
int parent[9] is declared, but not initialized. find() uses the (uninitialized) contents. Undefined behaviour right there.
Various "fishy" details, like main() declaring parent[9] and cost[9][9], but the functions declaring parent[10]. You also let the user enter the number of vertices, but happily assume that it won't be more than 9 when you use that number as upper loop bound. If any of your assumptions on the amount of storage provided doesn't hold, you're looking at out-of-bounds accesses.
At this point of the code review I'd toss down the code printout on the desk, and give you one of those long, hard stares...