Adding 2D Arrays In C.

Tifu Kelison Tifu Kelison
2 min read

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.

1
Subscribe to my newsletter

Read articles from Tifu Kelison directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tifu Kelison
Tifu Kelison

I am a Graphic Designer and Front-end developer and UI Designer(still in process) from Cameroon. I am the founder and CEO of the Design Archive. I love to write and as it turns out, hashnode is just the community I needed to start doing that. I at the time of writing this bio, I'm in my first year of university that's why you see writing articles about C. If you ever what to chat, feel free to hit me up on any social media platform.