C++ or C program to calculate sum of diagonal elements of a matrix.

file name:-sumdmat.cpp

#include<iostream.h>
#include<conio.h>
#define R 3
#define C 3
void main(){
int A[R][C], sum=0,i,j;
clrscr();
cout<<"Enter elements of matrix A"<<endl;
for(i=0;i<R;i++){
for(j=0;j<C;j++){
cout<<"Enter A["<<i<<"]["<<j<<]= ";
cin>>A[i][j];
if(i==j) sum=sum+A[i][j];
}
}
cout<<"Sum of diagonal elements of matrix A = "<<sum<<endl;
getch();
}

file name:-sumdmat.c

#include<stdio.h>
#include<conio.h>
#define R 3
#define C 3
void main(){
int A[R][C], sum=0,i,j;
clrscr();
printf("Enter Elements of Matrix A\n");
for(i=0;i<R;i++){
for(j=0;j<C;j++){
printf("Enter A[%d][%d]=",i,j);
scanf("%d",&A[i][j]);
if(i==j)
sum=sum+A[i][j];
}}
printf("Sum of Diagonal Elements of Matrix A =%d\n",sum);
getch();
}

No comments:

Post a Comment

Stack Data Structure, Push, Pop and Peek Operations , Applications of Stack

Stack is a linear data structure. It is collection of ordered data elements. It is also known as LIFO system (last in first out). It means i...