【課題5−2】

 

(プログラム例1)

#include <stdio.h>

#define SIZE 10

void math_array(const int *src1, const int *src2, int *dst, int n);

int main(void) {

         int data1[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

         int data2[SIZE] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

         int result[SIZE];

         int i;

 

         math_array(data1, data2, result, SIZE);

         /* 2つのデータ配列data1, data2と結果を格納するための配列resultのアドレスと

           配列の大きさを引数にして関数math_arrayを呼び出し */

        

         for (i = 0; i < SIZE; i++) {

                 printf("%d\n", result[i]);

         }

 

         return 0;

}

 

/* 2つの整数型配列の要素同士を足す関数 */

void math_array(const int *src1, const int *src2, int *dst, int n) {

         int i;

         for (i = 0; i < n; i++) {

                 dst[i] = src1[i] + src2[i];

         }

}

 

 

(プログラム例2)

#include <stdio.h>

#define SIZE 10

int math_array(const int *src1, const int *src2, int *dst, int n, char c);

int main(void) {

         int data1[SIZE] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

         int data2[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

         int result[SIZE];

         int i;

         char op;

 

         printf("Input an operator (+,-,*,/,%): ");

         scanf("%c", &op);

 

         if (math_array(data1, data2, result, SIZE, op)!=0) {

                 printf("Unknown operator \"%c\".\n", op);

                 return 1;

         }

        

         for (i = 0; i < SIZE; i++) {

                 printf("%d\n", result[i]);

         }

 

         return 0;

}

 

/* 2つの整数型配列の要素同士の各種演算を行う関数 */

int math_array(const int *src1, const int *src2, int *dst, int n, char c) {

         int i;

 

         switch (c) {

         case '+':       for (i = 0; i < n; i++)

                                  dst[i] = src1[i] + src2[i];

                          break;

         case '-':       for (i = 0; i < n; i++)

                                  dst[i] = src1[i] - src2[i];

                          break;

         case '*':       for (i = 0; i < n; i++)

                                  dst[i] = src1[i] * src2[i];

                          break;

         case '/':       for (i = 0; i < n; i++)

                                  dst[i] = src1[i] / src2[i];

                          break;

         case '%':       for (i = 0; i < n; i++)

                                  dst[i] = src1[i] % src2[i];

                          break;

         default:        return 1; /* 不適切な文字だったら1を返す */

         }

         return 0;

}