Hello, my C friends, today we'll be seeing how to add a 2D array using the C language.
But first, I want you to know that you require a little knowledge of arrays and for loops to understand what's going on in this lesson.
Alright so we want to add a 2D array, but let's first see what we know about 2D arrays.
- They are represented in matrix form. What I mean is you can represent 2D arrays as a matrix, making it easy to add.
- They're arrays within an array.
- They're indexed with two subscripts.
- They're easy to learn as long as you know how to use the
for loops
.
Let's start off with the code below, I'll explain in the code using comments.
#include<stdio.h>
int main(void) {
//first, we have to declare two 2D arrays
int a[2][2];
int b[2][2];
int sum[2][2];
printf("Enter elements of the first array: \n");
//now, use a for loop to get the user to enter the numbers in the array
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
printf("Enter element a[%d][%d] : ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\n Enter the elements of the second array: \n");
// now I'm taking the input of the second array
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
printf("Enter element b[%d][%d] : ",i,j);
scanf("%d",&b[i][j]);
}
}
//now, we're going to create another for loop which takes the sum of the two arrays.
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
//This is the last loop used to display the sum
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
printf("%d\t ", sum[i][j]);
}
printf("\n");
}
return 0;
}
And there you have it, how to add two arrays using C.
Until next time.
Peace.