對數組進行操作,尋找、插入、刪除 複製代碼 代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int size = 0;
int flag = 0;
void output(int *arry)
{
int i = 0;
for(i=0; i<size; i++)
{
printf("arry[%d]=%dt",i,arry[i]);
if((i+1)%5 == 0)
printf("n");
}
printf("n");
}
void getarry(int *arry)
{
int i = 0;
srand(time(NULL));
for(i=0; i<size; i++)
{
arry[i] = rand() % 100;
}
}
void add(int *arry, int pos, int num)
{
int i = 0;
if(pos>=0 && pos<=size)
{
if(pos < size) //在中間插入
{
for(i=size; i>pos; i--)
{
arry[i] = arry[i-1];
}
arry[pos] = num;
}
else //在最後的位置插入
{
arry[size] = num;
}
size++;
}
else
printf("只能在0-%d的位置插入。n",size);
}
int search(int *arry, int num)
{
static int pos = 0;
if(flag)
pos++;
for(; pos<size; pos++)
{
if(arry[pos] == num)
{
flag = 0;
return pos;
}
}
return -1;
}
void mod(int *arry, int pos, int num)
{
if(pos>=0 && pos<size)
{
arry[pos] = num;
}
else
{
printf("輸入位置錯誤。n");
}
}
int del(int *arry, int num)
{
int count = 0;
int pos = 0;
int i = 0;
pos=search(arry, num);
while(pos+1)
{
for(i=pos; i<size; i++)
{
arry[i] = arry[i+1];
}
count++;
pos=search(arry, num);
}
return count;
}
int main()
{
//pos 0到size-1
int *arry = NULL;
int count = 0;
int pos = 0;
int num = 0;
printf("輸入要產生多少個隨機數:");
scanf("%d",&size);
arry = malloc(2*size*sizeof(int));
getarry(arry);
output(arry);
printf("輸入要添加的位置(0-%d):",size);
scanf("%d",&pos);
printf("輸入要添加的數字:");
scanf("%d",&num);
add(arry, pos, num);
output(arry);
printf("輸入要尋找的數字:");
scanf("%d",&num);
pos=search(arry, num);
while(pos+1)
{
flag = 1;
count++;
printf("arry[%d]=%dn",pos, num);
pos=search(arry, num);
}
printf("共找到%d個匹配數字n",count);
printf("輸入要修改的位置:");
scanf("%d",&pos);
printf("輸入要修改為數字:");
scanf("%d",&num);
mod(arry, pos, num);
output(arry);
printf("輸入要刪除的數字:");
scanf("%d",&num);
del(arry, num);
output(arry);
free(arry);
arry = NULL;
return 0;
}