代码要素
int arr[10] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
/*
用户指定替换元素的下标位置 5;
替换使用的新元素 20;
要求:
1.需要知晓被替换的元素情况
2.数组的内容被替换之后 : {1, 3, 5, 7, 9, 20, 4, 6, 8, 10};
【隐含条件】
对用户提供的下标进行合法性判断
*/
代码如下
//C语言标注库头文件 #include <stdio.h> #include <stdlib.h> /* 在控制台展示用户提供的 int 类型数组 @param arr 用户提供的 int 类型数组 @param capacity 用户提供数组的容量 */ void print_int_array(int arr[], int capacity); int main(int argc, char *argv[]) { //被替换元素的原数组 int arr[10] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}; int index = 10; //替换的数据 int num = 11; //用户指定下标合法性判断 if (index < 0 || index > 10 - 1) { printf("下标不合法 \n"); //表示程序运行失败状态退出 return EXIT_FAILURE; } //遍历数组找到指定下标 for (int i = 0; i < 10; i++) { if (index == i) { //替换数据 arr[i] = num; } } //被替换的数据说明 int temp = arr[index]; printf("被替换的数据为 %d\n",temp); show_int_array(arr , 10); return 0; } void show_int_array(int arr[], int capacity) { /* 利用 for 循环对数组中的元素进行 printf 展示操作 */ for (int i = 0; i < capacity; i++) { printf ("%d\n",arr[i]); } }