C language applet array manipulation sample code

  • 2020-04-02 01:13:02
  • OfStack


#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)  //Insert in the middle
  {
   for(i=size; i>pos; i--)
   {
    arry[i] = arry[i-1];
   }
   arry[pos] = num;
  }
  else     //Insert at the last position
  {
   arry[size] = num;
  }
  size++;
 }
 else
  printf(" Only in the 0-%d Position insert. 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(" Incorrect input position. 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 to size 1
 int *arry = NULL;
 int count = 0;
 int pos = 0;
 int num = 0;
 printf(" Enter how many random Numbers to generate: ");
 scanf("%d",&size);
 arry = malloc(2*size*sizeof(int));
 getarry(arry);
 output(arry);
 printf(" Enter the location to add (0-%d) : ",size);
 scanf("%d",&pos);
 printf(" Enter the number to add: ");
 scanf("%d",&num);
 add(arry, pos, num);
 output(arry);
 printf(" Enter the number to look for: ");
 scanf("%d",&num);
 pos=search(arry, num);
 while(pos+1)
 {
  flag = 1;
  count++;
  printf("arry[%d]=%dn",pos, num);
  pos=search(arry, num);
 }
 printf(" A total of find %d Number of matches n",count);
 printf(" Enter the location to be modified: ");
 scanf("%d",&pos);
 printf(" To change the input to a number: ");
 scanf("%d",&num);
 mod(arry, pos, num);
 output(arry);
 printf(" Enter the number to delete: ");
 scanf("%d",&num);
 del(arry, num);
 output(arry);
 free(arry);
 arry = NULL;
 return 0;
}


Related articles: