Coding Challenge Day-6: Problem 2: Program to Interchange Diagonals of Matrix

Hello! So I’m doing a 30 day coding challenge where I solve around 3-5 questions per day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 6: Problem 2! Be sure to post your answers, queries etc in the comments!

Problem: Write a Program to Interchange Diagonals of Matrix

Sample: Original Matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Output: Diagonals Exchanged Matrix:
4 2 3 1
5 7 6 8
9 11 10 12
16 14 15 13

Solution:

package array;

public class Program006exchange_diagonals_of_matrix {
	
	public static void main (String [] args){
		int [][] matrix= {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};
		int n=4;
		
		System.out.println("Original Matrix: ");
		for(int l=0; l<n; l++){
			for(int m=0; m<n; m++){
				System.out.printf("%4d",matrix[l][m]);
			}
			
			System.out.println();
		}
		
		for(int i=0; i<n; i++){
			int temp= matrix[i][i];
			matrix[i][i]= matrix[i][n-i-1];
			matrix[i][n-i-1]= temp;
		}
		
		System.out.println();
		System.out.println("Diagonals Exchanged Matrix: ");
		
		for(int k=0; k<n; k++){
			for(int j=0; j<n; j++){
				System.out.printf("%4d",matrix[k][j]);
			}
			System.out.println();
		}
				
		
	}
	


}

Download Code

Happy Learning!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close