# C Programming – HackerRank Solution | 2D ARRAYS- Replace Elements |

### (HackerRank) Write a Modular C Programming code to solve 2D ARRAYS- Replace Elements, Write a modular C program to read a square matrix and replace all the diagonal elements with the next prime number

Write a modular C program to read a square matrix and replace all the diagonal elements with the next prime number in the sequence of the number and all the non-diagonal elements with ‘0’ (zero). If the diagonal element is already a prime number, do not replace the number.

Input Format

The first line is n indicates size of the matrix.

Next lines are matrix elements.

Constraints

n should be positive.

Output Format

Matrix after replacing the numbers.

Sample Input 0

```3
6 7 3
7 8 2
8 7 5
```

Sample Output 0

```7 0 0
0 11 0
0 0 5
```

Explanation 0

Matrix size is 3

Sample Input 1

```0
```

Sample Output 1

```Invalid matrix size.
```

Sample Input 2

```1
7
```

Sample Output 2

`7`

CODE:

```#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

int check_prime(int n);
int main() {
int n;
scanf("%d",&n);
if(n>0)
{
int matrix[n][n],i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&matrix[i][j]);
if(i!=j)
matrix[i][j]=0;
}
}
for(i=0;i<n;i++)
{
while(1)
{
if(check_prime(matrix[i][i]))
break;
else
matrix[i][i]++;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",matrix[i][j]);
}
printf("\n");
}

}
else{
printf("Invalid matrix size.");
}
return 0;
}
int check_prime(int n)
{
for(int i=2;i<n;i++)
{
if(n%i==0)
{
return 0;
exit(0);
}
}
return 1;
}
```

OUTPUT

```Congratulations, you passed the sample test case.

Click the Submit Code button to run your code against all the test cases.

Input (stdin)

3
6 7 3
7 8 2
8 7 5

7 0 0
0 11 0
0 0 5
Expected Output

7 0 0
0 11 0
0 0 5```

Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, Stacks, Queues, Binary Trees, MISC, Solved model question papers & Hacker Rank all solutions on the below page:

Top 100+ C Programming codes – KLE Technological University 