1. 程式人生 > >編寫函式fun(int *a, int n, int *odd, int *even)

編寫函式fun(int *a, int n, int *odd, int *even)

#include <stdio.h>

#define N 10

void fun(int *a, int n, int *odd, int *even)
{
int i = 0;

for (i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
{
*odd += a[i];   //遍歷陣列a尋找偶數相加
}
else
{
*even += a[i];  //奇數相加
}
}
}

void PrintArr(int *a, int n)
{
int i = 0;

for (i = 0; i < n; i++)
{
printf ("%d  ", a[i]);
}
printf ("\n");
}

int main()
{
int a[N] = {2,3,14,6,5,7,46,5,16,9};  //初始化陣列a
int odd = 0;
int even = 0;

printf ("The original array is :\n");
PrintArr(a, N);
fun (a, N, &odd, &even);
printf ("odd = %d\n", odd);
printf ("even = %d\n", even);

return 0;
}