Write a program that zeros the elements of the main diagonal of a given square matrix A.
Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#define SIZE 50
void main()
{
int M[SIZE][SIZE]; /* Square matrix */
int N; /* dimension of the matrix */
int i, j;
do {
printf("Enter the dimension: ");
scanf("%d", &N);
} while (N <= 0 || N > SIZE);
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
printf("Enter M[%d][%d]=", i, j);
scanf("%d", &M[i][j]);
}
}
printf("\n\n*** Matrix ***\n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
printf("%4d", M[i][j]);
printf("\n");
}
for (i=0; i<N; i++)
M[i][i]=0;
printf("\n\n*** Matrix ***\n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
printf("%4d", M[i][j]);
printf("\n");
}
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Ancestors of a node in a Binary tree