c program to print 1 in diagonal positions of a matrix


Explanation of the program



This program reads a matrix and replaces the value stored in the diagonal positions with 1. The program uses two for loops, with loop variables i and j. The diagonal positions has the same value for i and j. If i and j equals, a 1 is stored at the position a[i][j].

Program



#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[50][50]={0},i,j,r,c;
printf("Enter the row and column value:\n\n");
scanf("%d%d",&r,&c);
printf("\nEnter the elements:\n\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(i==j)
{
a[i][j]=1;
}}}
printf("\nNew matrix:\n");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",a[i][j]);
}}
getch();
}


Output



c program to change diagonal elements of a matrix to 1
C program to change diagonal elements of a matrix to 1

No comments: