Add and subtract two arrays.

C program to add and subtract two one dimensional arrays.

Program

#include<stdio.h>
#include<conio.h>
#define MAX 50

void read_array(int a[MAX], int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        printf("Element %d\t:",i+1);
        scanf("%d",&a[i]);
    }
}

void print_array(int a[MAX], int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        printf("Element %d\t:%d\n",i+1,a[i]);
    }
}

void add_array(int a[MAX], int b[MAX], int c[MAX], int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        c[i] = a[i] + b[i];
    }
}

void sub_array(int a[MAX], int b[MAX], int c[MAX], int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        c[i] = a[i] - b[i];
    }
}

void main()
{
	int arr1[MAX], arr2[MAX], add[MAX], sub[MAX];
    int i, n;

    printf("Enter the number of elements in the array\t:");
    scanf("%d",&n);

    printf("Enter the elements of first array\n");
    read_array(arr1, n);
    printf("Enter the elements of second array\n");
    read_array(arr2, n);

    add_array(arr1, arr2, add, n);
    sub_array(arr1, arr2, sub, n);

    printf("\nArray elements after addition\n");
    print_array(add, n);
    printf("\nArray elements after subtraction\n");
    print_array(sub, n);

    getch();
}

Output

Enter the number of elements in the array       :8
Enter the elements of first array
Element 1       :1
Element 2       :2
Element 3       :5
Element 4       :4
Element 5       :3
Element 6       :6
Element 7       :7
Element 8       :9
Enter the elements of second array
Element 1       :7
Element 2       :5
Element 3       :4
Element 4       :1
Element 5       :2
Element 6       :6
Element 7       :9
Element 8       :8

Array elements after addition
Element 1       :8
Element 2       :7
Element 3       :9
Element 4       :5
Element 5       :5
Element 6       :12
Element 7       :16
Element 8       :17

Array elements after subtraction
Element 1       :-6
Element 2       :-3
Element 3       :1
Element 4       :3
Element 5       :1
Element 6       :0
Element 7       :-2
Element 8       :1