Sum of Corner Elements in a matrix java, Java Program to Print the Sum of Corner Elements in a 2-D matrix
In this tutorial, we will write a program to print the sum of corner elements in matrix java.
First, we will write the algorithm to print the sum of corner elements in matrix java,
then we will write the complete java code of this program.
A square matrix of size r*c will be passed as input by the user then, the
program will add and print the sum of corner elements of matrix.
Sum of Corner Elements in Matrix Algorithm:
Step 1: Enter the number of Rows (r)
Step 2: Enter number of Columns (c)
Step 3: Read the elements of Matrix (arr[i][j])
Step 4: Store the sum of corner elements (sum)
Step 5: Print the input matrix
Step 6: Print sum of corner elements
I will access the corner elements of matrix using the below
approach:-
left top corner: arr[0][0]
right top corner: arr[0][r-1]
left bottom corner: arr[r-1][0]
right bottom corner: arr[r-1][r-1]
Checkout:- ISC Specimen Papers for Class 12 Computer Practical 2020 Solution
Checkout:-
Spy Number In Java - Solved Program
Sum of Corner Elements in matrix Java program
import java.util.*;
class Sum_of_Corner_Elements
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of Rows");
int r=sc.nextInt();
System.out.println("Enter the number of Columns");
int c=sc.nextInt();
int arr[][]=new int[r][c];
int sum=0;
System.out.println("Enter the elements of Matrix");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
arr[i][j]=sc.nextInt();
}
}
System.out.println("Input Matrix Is:");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println("");
}
sum=arr[0][0]+arr[0][r-1]+arr[r-1][0]+arr[r-1][r-1];
System.out.println("Sum of Corner Elements is="+sum);
}
}
-----------
OUTPUT:-
-----------
Enter the number of Rows
3
Enter the number of Columns
3
Enter the elements of Matrix
1
5
9
8
7
5
3
2
4
Input Matrix Is:
1 5 9
8 7 5
3 2 4
Sum of Corner Elements is = 17
Checkout:- Bubble Sort Ascending Order Java Program
Checkout:- Bubble Sort In Descending Order Java
0 Comments
Just write down your question to get the answer...