# C Program to Add Alternate Elements of a 2D Array

## Introduction

In this post, I am going to write a c program to add alternate elements of the 2d array. Here, 2d means two-dimensional array. The other name for the two-dimensional array is a matrix. You can also read my another post on C Program to Display Alternate Elements of a 2d Array.

Here, we have to find the sum of the alternate elements in the matrix. But, before doing this, we need to find the alternate digits.

Let’s see the output first.

### Expected Output

``````Enter the size of a matrix i.e. M * N
3 3
Enter elements in the 3 * 3 matrix
1 2 3 4 5 6 7 8 9
Given Matrix is
1 2 3
4 5 6
7 8 9
Alternate digits are
1   3
5
7   9
Sum of Alternate Elements = 25``````

As you can see the above output, first we are asking user to enter size of the matrix or 2d array. After knowing the size, user has entered 9 elements. Next, we have displayed the original array and the array with alternate elements. At the last, we have displayed the sum of the alternate elements of the 2d array.

Also Read: Programs on Arrays in C

Now, see the actual program.

### C Program to Add Alternate Elements of a 2D Array

``````#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
int i,j,flag=0,n,m, sum=0;
printf("Enter the size of a matrix i.e. M * N\n");
scanf("%d%d",&m,&n);
printf("Enter elements in the %d * %d matrix\n",m,n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Given Matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
printf("Alternate digits are\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(flag==0)
{
printf("%d ",a[i][j]);
sum=sum+a[i][j];
flag=1;
}
else
{
printf("  ");
flag=0;
}
}
printf("\n");
}
printf("\nSum of Alternate Elements = %d",sum);
return 0;
}
``````

### Explanation of adding an alternate elements in 2d array

The above program is finding the sum of alternate elements in a 2d array. For this, we have used the flag to know the alternate elements in the array. After reading each and every element, we are changing the value of the variable flag. It helps us to understand that which element is alternate and which element is not.

For example, when the value of the flag is 0 then we are adding that element with the variable sum and changing the status of flag=1. Because we don’t need to add the next element with the variable sum.

I hope you have understood this program. If you still have some doubt or difficulty, then please feel free to contact with me.

Thank you.