如何使用 For 循环、While 循环、函数和示例编写 C 程序来计算数组中的偶数和奇数?
C 语言计算数组中偶数和奇数个数的程序
此程序允许用户输入一维数组的大小和元素。接下来,我们使用 For 循环迭代数组值并检查偶数和奇数。
#include<stdio.h>
int main()
{
int Size, i, a[10];
int Even_Count = 0, Odd_Count = 0;
printf("\n Please Enter the Size of an Array : ");
scanf("%d", &Size);
printf("\nPlease Enter the Array Elements\n");
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
for(i = 0; i < Size; i ++)
{
if(a[i] % 2 == 0)
{
Even_Count++;
}
else
{
Odd_Count++;
}
}
printf("\n Total Number of Even Numbers in this Array = %d ", Even_Count);
printf("\n Total Number of Odd Numbers in this Array = %d ", Odd_Count);
return 0;
}

在这里,For 循环将确保该数字在 0 到最大大小值之间。在此示例中,它将从 0 到 4。
for(i = 0; i < Size; i ++)
在下一行,我们声明了If语句
if(a[i] % 2 == 0)
任何能被 2 整除的数都是偶数。If 条件将检查当前 一维数组元素除以 2 的余数是否正好等于 0。
使用 While 循环计算数组中偶数和奇数的程序
此程序与上面相同,但这次我们使用了While 循环来计算数组中的偶数和奇数。
#include<stdio.h>
int main()
{
int Size, i, j = 0, a[10];
int Even_Count = 0, Odd_Count = 0;
printf("\n Please Enter the Size of an Array : ");
scanf("%d", &Size);
printf("\nPlease Enter the Array Elements\n");
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
while(j < Size)
{
if(a[j] % 2 == 0)
{
Even_Count++;
}
else
{
Odd_Count++;
}
j++;
}
printf("\n Total Number of Even Numbers in this Array = %d ", Even_Count);
printf("\n Total Number of Odd Numbers in this Array = %d ", Odd_Count);
return 0;
}
计算数组中的偶数和奇数输出
Please Enter the Size of an Array : 7
Please Enter the Array Elements
22 15 65 89 16 2 19
Total Number of Even Numbers in this Array = 3
Total Number of Odd Numbers in this Array = 4
使用函数计算数组中偶数和奇数的 C 程序
此C 程序与第一个示例相同。但是,我们使用函数将计算偶数和奇数的逻辑分开。
#include<stdio.h>
int CountEvenNumbers(int a[], int Size);
int CountOddNumbers(int a[], int Size);
int main()
{
int Size, i, a[10];
int Even_Count = 0, Odd_Count = 0;
printf("\n Please Enter the Size of an Array\n");
scanf("%d", &Size);
printf("\nPlease Enter the Array Elements : ");
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
Even_Count = CountEvenNumbers(a, Size);
Odd_Count = CountOddNumbers(a, Size);
printf("\n Total Number of Even Numbers in this Array = %d ", Even_Count);
printf("\n Total Number of Odd Numbers in this Array = %d ", Odd_Count);
return 0;
}
int CountEvenNumbers(int a[], int Size)
{
int i, Even_Count = 0;
printf("\n List of Even Numbers in this Array: ");
for(i = 0; i < Size; i ++)
{
if(a[i] % 2 == 0)
{
printf("%d ", a[i]);
Even_Count++;
}
}
return Even_Count;
}
int CountOddNumbers(int a[], int Size)
{
int i, Odd_Count = 0;
printf("\n List of Odd Numbers in this Array: ");
for(i = 0; i < Size; i ++)
{
if(a[i] % 2 != 0)
{
printf("%d ", a[i]);
Odd_Count++;
}
}
return Odd_Count;
}
Please Enter the Size of an Array
10
Please Enter the Array Elements : 10 15 13 2 48 19 85 97 56 94
List of Even Numbers in this Array: 10 2 48 56 94
List of Odd Numbers in this Array: 15 13 19 85 97
Total Number of Even Numbers in this Array = 5
Total Number of Odd Numbers in this Array = 5