C语言小程序 数组操作示例代码

所属分类: 软件编程 / C 语言 阅读数: 100
收藏 0 赞 0 分享
复制代码 代码如下:

#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]=%d\t",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]=%d\n",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;
}

更多精彩内容其他人还在看

从汇编看c++中变量类型的深入分析

本篇文章是对c++中的变量类型进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

从汇编看c++的默认析构函数的使用详解

本篇文章是对c++中默认析构函数的使用进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

基于c++中的默认拷贝函数的使用详解

本篇文章对c++中默认拷贝函数的使用进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

解析c++中的默认operator=操作的详解

本篇文章是对c++中的默认operator=操作的应用进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

解析c++中参数对象与局部对象的析构顺序的详解

本篇文章是对c++中参数对象与局部对象的析构顺序进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入c++中临时对象的析构时机的详解

本篇文章对c++中临时对象的析构时机进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

解析内存对齐 Data alignment: Straighten up and fly right的详解

对于所有直接操作内存的程序员来说,数据对齐都是很重要的问题.数据对齐对你的程序的表现甚至能否正常运行都会产生影响
收藏 0 赞 0 分享

深入内存对齐的详解

本篇文章是对内存对齐进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入C语言把文件读入字符串以及将字符串写入文件的解决方法

本篇文章是对C语言把文件读入字符串以及将字符串写入文件的方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入Windows下的回车是回车换行(\r\n)还是换行回车(\n\r)的详解

本篇文章对Windows下的回车是回车换行(\r\n)还是换行回车(\n\r)进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享
查看更多