Print matrix in snake pattern from the last column in C Programming.

In C, printing a matrix in snake pattern from the last column means traversing the matrix row by row, alternating the direction of column traversal. For odd-numbered rows (index 0, 2, 4...), we print from right to left, and for even-numbered rows (index 1, 3, 5...), we print from left to right.

Matrix Snake Pattern from Last Column 10 20 30 40 50 60 70 80 90 100 110 120 Row 0: Right to Left Row 1: Left to Right Row 2: Right to Left Output: 40 30 20 10 50 60 70 80 120 110 100 90

Syntax

for (int i = 0; i < n; i++) {
    if (i % 2 == 0) {
        // Even rows: right to left
        for (int j = n - 1; j >= 0; j--) {
            printf("%d ", arr[i][j]);
        }
    } else {
        // Odd rows: left to right
        for (int j = 0; j < n; j++) {
            printf("%d ", arr[i][j]);
        }
    }
}

Example

Here's a complete program that demonstrates snake pattern printing starting from the last column −

#include <stdio.h>

int main() {
    int n = 4;
    int arr[4][4] = {
        {100, 99, 98, 97},
        {93, 94, 95, 96},
        {92, 91, 90, 89},
        {85, 86, 87, 88}
    };
    
    printf("Matrix:
"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf("%3d ", arr[i][j]); } printf("
"); } printf("\nSnake pattern from last column: "); for (int i = 0; i < n; i++) { if (i % 2 == 0) { // Even rows (0, 2, 4...): print right to left for (int j = n - 1; j >= 0; j--) { printf("%d ", arr[i][j]); } } else { // Odd rows (1, 3, 5...): print left to right for (int j = 0; j < n; j++) { printf("%d ", arr[i][j]); } } } printf("
"); return 0; }
Matrix:
100  99  98  97
 93  94  95  96
 92  91  90  89
 85  86  87  88

Snake pattern from last column: 97 98 99 100 93 94 95 96 89 90 91 92 85 86 87 88

How It Works

  • The algorithm uses the modulo operator i % 2 to determine the traversal direction
  • For even-indexed rows (0, 2, 4...), it starts from the last column and moves left
  • For odd-indexed rows (1, 3, 5...), it starts from the first column and moves right
  • This creates a snake-like zigzag pattern through the matrix

Conclusion

The snake pattern traversal from the last column efficiently prints matrix elements in a zigzag manner. This technique is useful in various matrix manipulation problems and demonstrates how simple conditional logic can create complex traversal patterns.

Updated on: 2026-03-15T12:00:59+05:30

430 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements