# C Program to Display Alternate Elements of a 2d Array

## Introduction

In this post, I am going to write a c program to display alternate elements of a 2d array. Here, 2d means two-dimensional array. We can call two-dimensional array as a matrix where rows and columns are used.

Before writing this program, let’s see the expected output first so that you will get the idea about the program.

### Expected Output of a C Program to Display Alternate Elements of a 2D Array

``````Enter the size of a matrix i.e. M * N
5
5
Enter elements in the 5 * 5 matrix
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Given Matrix is
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Alternate digits are
1   1   1
1   1
1   1   1
1   1
1   1   1``````

As you can see the above expected output, we are asking user to enter the size of the matrix. Suppose, the user has entered 5 and 5. That means, this matrix size is of 5*5 i.e. 5 rows and 5 columns. Next we are asking user to enter the elements for this matrix.

Also Read: Programs on Arrays in C

After reading elements, our program has entered the original matrix and then we will remove the alternate elements from the matrix.

See the following program.

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

``````#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
int i,j,flag=0,n,m;
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]);
flag=1;
}
else
{
printf("  ");
flag=0;
}
}
printf("\n");
}
return 0;
}``````

### Explanation

The above c program is displaying the alternate elements in a 2d array. Here, with the flag variable, we are displaying the alternate digits or elements. When the value of flag=0, then we print the element and make the value of flag=1. In the next run, when the value of flag=1, then will print the blank space instead of element and again make the value of flag=0. This process will continue until we reach the end of the matrix.

I hope you have understood this program. If you have any difficulties, please feel free to contact me.

Thank you.