How to perform the arithmetic operations on arrays in C language?


An array is a group of related data items that are stored with single name.

For example, int student[30]; //student is an array name that holds 30 collection of data items with a single variable name

Operations of array

  • Searching − It is used to find whether particular element is present or not

  • Sorting − It helps in arranging the elements in an array either in ascending or descending order.

  • Traversing − It processes every element in an array sequentially.

  • Inserting − It helps in inserting the elements in an array.

  • Deleting − It helps in deleting an element in an array.

The logic to perform all arithmetic operations in an array is as follows −

for(i = 0; i < size; i ++){
   add [i]= A[i] + B[i];
   sub [i]= A[i] - B[i];
   mul [i]= A[i] * B[i];
   div [i] = A[i] / B[i];
   mod [i] = A[i] % B[i];
}

Program

Following is the C program for arithmetic operations on arrays −

 Live Demo

#include<stdio.h>
int main(){
   int size, i, A[50], B[50];
   int add[10], sub[10], mul[10], mod[10];
   float div[10];
   printf("enter array size:
");    scanf("%d", &size);    printf("enter elements of 1st array:
");    for(i = 0; i < size; i++){       scanf("%d", &A[i]);    }    printf("enter the elements of 2nd array:
");    for(i = 0; i < size; i ++){       scanf("%d", &B[i]);    }    for(i = 0; i < size; i ++){       add [i]= A[i] + B[i];       sub [i]= A[i] - B[i];       mul [i]= A[i] * B[i];       div [i] = A[i] / B[i];       mod [i] = A[i] % B[i];    }    printf("
add\t sub\t Mul\t Div\t Mod
");    printf("------------------------------------
");    for(i = 0; i <size; i++){       printf("
%d\t ", add[i]);       printf("%d \t ", sub[i]);       printf("%d \t ", mul[i]);       printf("%.2f\t ", div[i]);       printf("%d \t ", mod[i]);    }    return 0; }

Output

When the above program is executed, it produces the following result −

Run 1:
enter array size:
2
enter elements of 1st array:
23
45
enter the elements of 2nd array:
67
89
add    sub     Mul    Div    Mod
------------------------------------
90    -44     1541  0.00    23
134    -44    4005  0.00    45
Run 2:
enter array size:
4
enter elements of 1st array:
89
23
12
56
enter the elements of 2nd array:
2
4
7
8
add  sub Mul  Div   Mod
------------------------------------
91  87  178   44.00  1
27  19  92    5.00   3
19  5   84    1.00    5
64  48  448   7.00    0

Updated on: 24-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements