
数组是一组以单一名称存储的相关数据项。
例如 int Student[30]; //student是一个数组名,包含单个变量名的30个数据项集合
搜索 - 用于查找特定元素是否存在
排序 - 它有助于排列数组中的元素按升序或降序排列。
立即学习“C语言免费学习笔记(深入)”;
遍历 - 它按顺序处理数组中的每个元素。
插入 - 它有助于在数组中插入元素。
删除 - 它有助于删除数组中的元素。数组中的元素。
在数组中查找偶数的逻辑如下 -
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++;
}
}要显示偶数,请调用下面提到的显示函数 -
printf("no: of elements comes under even are = %d </p><p>", 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("</p><p>");
}要显示奇数,请按照以下方式调用显示函数 −
printf("no: of elements comes under odd are = %d </p><p>", 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("</p><p>");
}以下是使用 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 :</p><p>");
scanf("%d", &size);
printf("enter array elements:</p><p>");
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 </p><p>", Ecount);
printf("The elements that are present in an even array is: ");
display(even, Ecount);
printf("no: of elements comes under odd are = %d </p><p>", 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("</p><p>");
}当执行上述程序时,会产生以下结果 -
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
以上就是如何使用C语言中的for循环将数组中的偶数和奇数分开?的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号