Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to perform the arithmetic operations on arrays in C language?
In C programming, arrays allow us to store multiple related data items under a single name. We can perform arithmetic operations like addition, subtraction, multiplication, division, and modulus on corresponding elements of two arrays.
For example, int student[30]; declares an array named student that can hold 30 integer values.
Array Operations
- Searching − Finding whether a particular element is present in the array
- Sorting − Arranging elements in ascending or descending order
- Traversing − Processing every element sequentially
- Inserting − Adding new elements to the array
- Deleting − Removing elements from the array
Syntax
for(i = 0; i < size; i++){
add[i] = A[i] + B[i]; // Addition
sub[i] = A[i] - B[i]; // Subtraction
mul[i] = A[i] * B[i]; // Multiplication
div[i] = A[i] / B[i]; // Division
mod[i] = A[i] % B[i]; // Modulus
}
Example: Arithmetic Operations on Arrays
The following program demonstrates how to perform all basic arithmetic operations on two arrays −
#include <stdio.h>
int main() {
int A[4] = {23, 45, 89, 12};
int B[4] = {67, 89, 2, 7};
int size = 4;
int i;
int add[4], sub[4], mul[4], mod[4];
float div[4];
// Performing arithmetic operations
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] = (float)A[i] / B[i];
mod[i] = A[i] % B[i];
}
// Displaying results
printf("Array A: ");
for(i = 0; i < size; i++) {
printf("%d ", A[i]);
}
printf("\nArray B: ");
for(i = 0; i < size; i++) {
printf("%d ", B[i]);
}
printf("<br>\nArithmetic Operations:<br>");
printf("Add\tSub\tMul\tDiv\tMod<br>");
printf("-----------------------------------<br>");
for(i = 0; i < size; i++) {
printf("%d\t%d\t%d\t%.2f\t%d<br>",
add[i], sub[i], mul[i], div[i], mod[i]);
}
return 0;
}
Array A: 23 45 89 12 Array B: 67 89 2 7 Arithmetic Operations: Add Sub Mul Div Mod ----------------------------------- 90 -44 1541 0.34 23 134 -44 4005 0.51 45 91 87 178 44.50 1 19 5 84 1.71 5
Key Points
- Both arrays must have the same size for element-wise operations
- Division should use
floatcasting to avoid integer division truncation - Modulus operation (
%) works only with integer operands - Always ensure array bounds are not exceeded during operations
Conclusion
Arithmetic operations on arrays in C involve processing corresponding elements from two arrays using loops. These operations are fundamental for mathematical computations and data processing in array-based algorithms.
Advertisements
