Java program matrix diagonal sum without mid value repetition

Java program matrix diagonal sum without mid value repetition
import java.util.*;
/**
 *
 * Double dimension array diagonal addition
 * Each diagonal sum without repetition of mid value
 * InspireSkills : Khurshid Md Anwar
 *
 */
public class MatrixAddWithoutRepetingMidValue
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int i,j,s1,s2,r,c,a;
        System.out.println("Enter Row or Col");
        r=sc.nextInt();
        int n[][]=new int[r][r];
        s1=s2=0;
        System.out.println("Enter values into Matrix");
        for(i=0;i<r;i++)
        {
            for(j=0;j<r;j++)
            {
                n[i][j] = sc.nextInt();
            }

        }
        System.out.println("Print Matrix");
        for(i=0; i<r; i++)
        {
            for(j=0; j<r; j++)
            {
                System.out.print(n[i][j] + " ");
            }
            System.out.println();
        }
        for(i=0; i<r; i++)
        {
            s1 = s1 + n[i][i];
        }
        c = r-1;
        for(i=0;i<r;i++)
        {
            s2 = s2 + n[i][c];
            c--;
        }
        // Excluding the repeating mid value
        s2 = s2 - n[r/2][r/2];
        System.out.println("Mid Value="+n[r/2][r/2]);
        System.out.println("First Diagonal sum=" + s1);
        System.out.println("Second Diagonal sum=" + s2);
        System.out.println("Sum of Two diagonal without repeating value is "+ (s1+s2));
    }
}

Output
Enter Row or Col
3
Enter values into Matrix
9
8
7
6
5
4
3
2
1
Print Matrix
9 8 7 
6 5 4 
3 2 1 
Mid Value=5
First Diagonal sum=15
Second Diagonal sum=10
Sum of Two diagonal without repeating value is 25

Few more program


SHARE THIS
Previous Post
Next Post