创建一个函数,将和有n个元素的数组中的key相等的所有元素的下标存储在另一个数组中,并返回和key元素相同的元素的个数。
1、数组元素的查找
#include <stdio.h>
#define NUMBER 10
int func1(const int x[], int y[], int z, int p)
{
int i = 0;
int j = 0;
while (i < p)
{
if (x[i] == z)
{
y[j] = i;
j++;
}
i++;
}
return j;
}
int main(void)
{
int i, num, key,a[NUMBER], b[NUMBER];
puts("please input the elements.");
for (i = 0; i < NUMBER; i++)
{
printf("a[%d]: ", i); scanf("%d", &a[i]);
}
printf("the target element: "); scanf("%d", &key);
num = func1(a, b, key, NUMBER);
for (i = 0; i < num; i++)
{
printf("b[%d] = %d\n", i, b[i]);
}
printf("the number of target element: %d\n", num);
return 0;
}
↓
#include <stdio.h>
#define NUMBER 7
int search(const int v[], int idx[], int key, int n)
{
int i = 0, j = 0;
while (i < n)
{
if (v[i] == key)
{
idx[j] = i;
j++;
}
i++;
}
printf("{");
for (i = 0; i < j; i++)
{
printf("%d ", idx[i]);
}
printf("}\n");
printf("the number is %d\n", j);
}
int main(void)
{
int i, nu, a[NUMBER], b[NUMBER];
puts("please input the elements.");
for (i = 0; i < NUMBER; i++)
{
printf("a[%d] = ", i); scanf("%d", &a[i]);
}
printf("nu = "); scanf("%d", &nu);
search(a, b, nu, NUMBER );
return 0;
}