介绍
数组(Array)是一组存储在连续内存位置中的相似数据项的集合,由元素组成。可以通过索引对应内存位置来访问元素。有时,根据位置或值删除数组中的某个元素变得至关重要。在本实验中,我们将学习如何根据位置和值从数组中删除元素。
数组(Array)是一组存储在连续内存位置中的相似数据项的集合,由元素组成。可以通过索引对应内存位置来访问元素。有时,根据位置或值删除数组中的某个元素变得至关重要。在本实验中,我们将学习如何根据位置和值从数组中删除元素。
首先,我们需要在代码编辑器中创建一个 C 项目。在 ~/project/
目录下创建一个新文件 "main.c",并编写以下代码:
#include <stdio.h>
int main()
{
return 0;
}
在这一步中,我们将用 C 语言编写一个程序,该程序接受一个整数数组、数组的大小以及要删除的元素的位置。然后,我们将删除该元素并打印更新后的数组。
#include <stdio.h>
int main()
{
int arr[100], position, c, n;
printf("Enter the number of elements in array: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for(c = 0; c < n; c++)
scanf("%d", &arr[c]);
printf("Enter the location of the element to delete: ");
scanf("%d", &position);
if (position >= n + 1)
printf("Deletion not possible.\n");
else
for (c = position - 1; c < n - 1; c++)
arr[c] = arr[c+1];
printf("The updated array is: ");
for(c = 0; c < n-1; c++)
printf("%d ", arr[c]);
return 0;
}
代码解释:
arr[100]
,它可以存储最多 100 个元素。n
,它表示数组中的元素数量。for
循环通过 scanf
函数从用户那里接收输入并存储到数组 arr
中。printf
语句输出更新后的数组。在这一步中,我们将用 C 语言编写一个程序,根据用户输入的值删除数组中的元素。
#include<stdio.h>
int main()
{
int arr[10], element, c, n, pos, found=0;
printf("Enter the number of elements in array: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (c = 0; c < n; c++)
scanf("%d", &arr[c]);
printf("Enter the element to delete: ");
scanf("%d", &element);
for (c = 0; c < n; c++)
{
if (arr[c] == element)
{
found = 1;
pos = c;
break;
}
}
if (found == 1)
{
for (c = pos; c < n - 1; c++)
arr[c] = arr[c+1];
printf("The updated array is: ");
for (c = 0; c < n - 1; c++)
printf("%d ", arr[c]);
}
else
printf("Element not found in array.");
return 0;
}
代码解释:
arr[10]
。n
中存储要添加的元素数量。for
循环通过 scanf
函数逐个接收 n
个整数并存储到整数数组 arr
中。for
循环遍历数组,从 0 到 n-1,然后使用 if
语句检查用户输入的元素是否等于数组中的任何元素。pos
,在其中存储该元素的索引。for
循环删除该元素并移动数组中的剩余元素。printf
语句输出更新后的数组。在本实验中,我们学习了如何在 C 编程中通过位置或值从数组中删除元素。删除数组中元素的程序接收数组、数组大小以及要删除元素的位置/值作为输入,使用 for
循环遍历数组,找到目标元素的位置或值,然后使用循环删除该元素。这是通过将待删除元素右侧的元素向左复制直到数组末尾来实现的。删除后,数组的大小减少一。