Home >Backend Development >C#.Net Tutorial >C language to implement deleting an element in an array

C language to implement deleting an element in an array

烟雨青岚
烟雨青岚forward
2020-06-17 12:37:0613544browse

C language to implement deleting an element in an array

C language implementation to delete an element in an array

Do you know how to delete an element in an array in C language? The following will describe two methods of deleting an element in an array in C language. Let’s take a look.

Method 1:

 /* 
 name: c语言  删除数组的某个元素 
 tip:
   数组元素的增/删/      改/查(简单遍历就ok) 
   数组增删操作在c语言中没有相应的函数------我们最好是 自己写个函数保存好 
   注意代码缩进,对齐 
*/
#include<stdio.h>
int main()
{
//删
int arr[]={1,3,10,5,4,} ;
int delect=0;
int i=0,j=0,k=0;
int n;//n为数组长度 
n=sizeof(arr)/sizeof(int);
//printf("%d\n",n);//测试n
 
 printf("删除前数组为:");
 for(k=0;k<=n-1;k++)
 {
  printf("%4d",arr[k]);
  
 }
 printf("\n");
 
 
//输入提示:
printf("请输入要删除的数:");
scanf("%d",&delect); 
for(i=0;i<=n-1;i++)
   {    
    if(delect==arr[i])
       {
       for(j=i;j<=n-2;j++)
          {
          arr[j]=arr[j+1];//覆盖 
}  
  // goto loop1; 
}/*执行完这个if引导的代码块后,删除工作已ok了,但程序还会把循环跑完,
会自然想到break ,但仔细一想,不好控制,不行,,,
最好的解决方法-goto  或  记录下标,出循环后处理这个下标 
 
*/
}
/*
此处 也可以使用 记录下标delectindex的方法 ---推荐使用,因为上面的 
代码在执行的时候 会多run些无用的步骤,具体见上面的注释 
*/
    //loop1: 
printf("删除后数组为:");
for(k=0;k<=n-2;k++)
   {
    printf("%4d",arr[k]);
}
printf("\n");
 
return 0;
}

Method 2: Record subscript

/* 
 name: c语言  删除数组的某个元素 
 tip:
   数组元素的增/删/      改/查(简单遍历就ok) 
   数组增删操作在c语言中没有相应的函数------我们最好是 自己写个函数保存好 
   注意代码缩进,对齐 
*/
#include<stdio.h>
int main()
{
//删
int arr[]={1,3,10,5,4,} ;
int delect=0;
int delectIndex=0;
int i=0;//相比于上一个代码,少定义了k,j,---这种用来控制循环的变量,在不是嵌套的情况下,可以只定义一个
//(尽量少定义变量,减少内存占用) 
int n;//n为数组长度 
n=sizeof(arr)/sizeof(int);
//printf("%d\n",n);//测试n
  
 printf("删除前数组为:");
 for(i=0;i<=n-1;i++)
 {
  printf("%4d",arr[i]);
  
 }
 printf("\n");
 
 
//输入提示:
printf("请输入要删除的数:");
scanf("%d",&delect); 
for(i=0;i<=n-1;i++)
   {    
    if(delect==arr[i]) delectIndex=i;//记录要删除元素的下标 
  }
  
  
for(i=delectIndex;i<=n-2;i++)
  {
  arr[i]=arr[i+1];
  }
  
  //想知道较为具体的执行过程---debug  或  写些printf(建议使用) 
   
printf("删除后数组为:");
for(i=0;i<=n-2;i++)
   {
    printf("%4d",arr[i]);
}
printf("\n");
 
return 0;
}

Thank you all for reading, I hope you all benefit from it.

This article is reproduced from: https://blog.csdn.net/csdn17355456893/article/details/76883951

Recommended tutorial: "Clanguage

The above is the detailed content of C language to implement deleting an element in an array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete