C programming, eliminating zeros from an array

Status
Not open for further replies.

Sooner49

Beta member
Messages
1
I'm trying to write a program with several functions in it. Unfortunately i haven't gotten past the first function. The question is:

Write a function that receives an array of integers >= in parameter and return a compacted version of the array containing only the values > 0.

Below is what i have, it looks bad i know, but its a working progress, any help would be appreciated.


#include<stdio.h>
#include<math.h>
#define SIZE 81

void array_easy( int a[]);

int main(){

int value[SIZE] = {5,6,3,4,0,0,1,2};

array_easy(value);
return 0;
}
void array_easy(int a[]){
int i;
int hold =0;

for(i=0; i < SIZE; i++){
if(i <= 0){
i =+ hold;
}}
printf("\nThis is the array with numbers greater than zero\n");
for(i=0; i < SIZE; i++){
printf("%d",a);
}
printf("\n");
//return a;
}
 
You can't return an array from a function in C. It's not such a big deal because you can pass the array by reference and then edit the values in the array in the function to whatever it is you want then it will be automatically updated in the main function.

I see what you want from the function. You want to trim all the 0 elements out and have an array with no 0s in it. But from the code you have provided, you add the value hold, which is 0, to the elements <= 0 so you don't change the value at all. Then you just print out all the values of the array, even if they have a 0 in it. I think this is what you want:

=========

#include <stdio.h>
#define SIZE 81

void array_easy(int *a);

int main()
{

int value[SIZE] = {5,6,3,4,0,0,1,2};
array_easy(value);

return 0;
}

void array_easy(int *a)
{
int temp[SIZE];
int i, j = 0;

for(i = 0; i < SIZE; i++)
{
if(a > 0)
{
temp[j] = a;
j++;
}
}

a = temp;
}

============

The original value of the array will be lost and only the values in the new array, temp, will be saved.
 
Status
Not open for further replies.
Back
Top Bottom