如何使用 C 语言中的 for 循环将数组中的偶数和奇数分离?
数组是一组相关的数据项,它们以单个名称存储。
例如,int student[30]; //student 是一个数组名称,它使用单个变量名称保存 30 个数据项的集合
数组的操作
搜索 - 用于查找特定元素是否存在。
排序 - 有助于按升序或降序排列数组中的元素。
遍历 - 按顺序处理数组中的每个元素。
插入 - 有助于将元素插入数组。
删除 - 有助于删除数组中的元素。
查找**数组中的偶数**的逻辑如下:
for(i = 0; i < size; i ++){ if(a[i] % 2 == 0){ even[Ecount] = a[i]; Ecount++; } }
查找**数组中的奇数**的逻辑如下:
for(i = 0; i < size; i ++){ if(a[i] % 2 != 0){ odd[Ocount] = a[i]; Ocount++; } }
要显示**偶数**,请调用如下所示的 display 函数:
printf("no: of elements comes under even are = %d
", Ecount); printf("The elements that are present in an even array is: "); void display(int a[], int size){ int i; for(i = 0; i < size; i++){ printf("%d \t ", a[i]); } printf("
"); }
要显示**奇数**,请调用如下所示的 display 函数:
printf("no: of elements comes under odd are = %d
", Ocount); printf("The elements that are present in an odd array is : "); void display(int a[], int size){ int i; for(i = 0; i < size; i++){ printf("%d \t ", a[i]); } printf("
"); }
程序
以下是使用 for 循环将数组中的偶数和奇数分离的 C 程序:
#include<stdio.h> void display(int a[], int size); int main(){ int size, i, a[10], even[20], odd[20]; int Ecount = 0, Ocount = 0; printf("enter size of array :
"); scanf("%d", &size); printf("enter array elements:
"); for(i = 0; i < size; i++){ scanf("%d", &a[i]); } for(i = 0; i < size; i ++){ if(a[i] % 2 == 0){ even[Ecount] = a[i]; Ecount++; } else{ odd[Ocount] = a[i]; Ocount++; } } printf("no: of elements comes under even are = %d
", Ecount); printf("The elements that are present in an even array is: "); display(even, Ecount); printf("no: of elements comes under odd are = %d
", Ocount); printf("The elements that are present in an odd array is : "); display(odd, Ocount); return 0; } void display(int a[], int size){ int i; for(i = 0; i < size; i++){ printf("%d \t ", a[i]); } printf("
"); }
输出
执行上述程序时,会产生以下结果:
enter size of array: 5 enter array elements: 23 45 67 12 34 no: of elements comes under even are = 2 The elements that are present in an even array is: 12 34 no: of elements comes under odd are = 3 The elements that are present in an odd array is : 23 45 67
广告