Reads n integers from the keyboard into the array, writes the function compactintegers, deletes all elements with a value of 0 in the array, and then moves the elements to the first end of the array. Note that the Compactintegers function needs to accept the array and its number of elements as arguments, and the function return value should be the number of new elements of the array after the delete operation executes. Outputs the number of elements in the array after deletion and sequentially outputs the array elements. Sample input: (Input format Description: 5 is the number of input data, 3 4 0 0 2 is a space-separated 5 integers)
5
3 4 0) 0 2
Sample output: (Output Format Description: 3 is the number of non-0 data, 3 4 2 is a space-separated 3 non-zero integers)
3
3 4 2 Sample Input 7
0 0 7 0 0 9 0 Sample Output 2
7 9 Example Input 3
0 0 0 Sample Output 0
Answer:
#include <stdio.h>
#include <string.h>
void compactintegers (int array[], int *n)
{
int i,j;
int k = *n;//k number of elements in an array
for (i = 0; I <k; i + +) {
Starting with the specified 0, let
if (array[i]==0) {
for (j = i; J < K-1; J + +) {
array[j]=array[j+1];//move the elements behind 0 forward.
}
array[k]=0;
i--;//minus and Plus, let I also be the value of the current period, because the following elements move forward.
k--;//Delete the element as 0
}
}
*n = k;
}
int main (int argc, const char * argv[]) {
Input data
int n,i;
scanf ("%d", &n);
int count[n];
for (i = 0; i < n; i + +) {
scanf ("%d", &count[i]);
}
Compactintegers (count, &n);
Prints the number of elements and elements after deleting 0 elements in an array
printf ("%d\n", N);
for (i = 0; i < n; i + +) {
printf ("%d", count[i]);
}
return 0;
}
Blue Bridge Cup--delete array 0 elements