Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to Print the Squared Matrix in Z form in C
In C programming, printing a squared matrix in Z form means displaying the elements in a specific pattern − first the top row, then the diagonal elements from top-right to bottom-left, and finally the bottom row. This creates a Z-shaped traversal pattern through the matrix.
Syntax
/* Z-form traversal pattern */ // First row: matrix[0][0] to matrix[0][n-1] // Diagonal: matrix[i][n-1-i] where i goes from 1 to n-2 // Last row: matrix[n-1][1] to matrix[n-1][n-1]
Algorithm
The Z-form traversal follows these steps −
- Print all elements of the first row
- Print diagonal elements from top-right to bottom-left (excluding corners)
- Print all elements of the last row (excluding first element to avoid duplication)
Example
Here's a complete program to print a square matrix in Z form −
#include <stdio.h>
int main() {
int n, i, j;
int matrix[10][10];
printf("Enter the size of square matrix: ");
scanf("%d", &n);
printf("Enter the elements of the matrix:<br>");
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("\nOriginal Matrix:<br>");
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("<br>");
}
printf("\nZ-form traversal: ");
/* Print first row */
for(j = 0; j < n; j++) {
printf("%d ", matrix[0][j]);
}
/* Print diagonal elements (excluding corners) */
for(i = 1; i < n-1; i++) {
printf("%d ", matrix[i][n-1-i]);
}
/* Print last row (excluding first element) */
if(n > 1) {
for(j = 1; j < n; j++) {
printf("%d ", matrix[n-1][j]);
}
}
printf("<br>");
return 0;
}
Enter the size of square matrix: 4 Enter the elements of the matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Original Matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Z-form traversal: 1 2 3 4 7 10 14 15 16
Key Points
- The algorithm works only for square matrices (n × n)
- For a 1×1 matrix, only the single element is printed
- The diagonal traversal goes from matrix[1][n-2] to matrix[n-2][1]
- Care is taken to avoid printing corner elements twice
Conclusion
The Z-form matrix traversal is an efficient way to print matrix elements in a specific pattern. It demonstrates array indexing and loop control techniques essential for matrix operations in C programming.
Advertisements
