Character Matrix – Alternate Ends
Print characters from a matrix alternating between first N characters from odd rows and last N characters from even rows.
Understand the Problem
Problem Statement
Given a character matrix of size RxC, print characters based on the following alternating pattern:
- First character from row 1
- Last 2 characters from row 2
- First 3 characters from row 3
- Last 4 characters from row 4
- Continue this pattern for all rows
The pattern alternates between taking characters from the beginning (odd rows) and end (even rows) of each row, with the number of characters increasing by 1 for each subsequent row.
Constraints
- 2 ≤ R, C ≤ 100
- All characters in the matrix are printable characters
- Each row has exactly C characters
- The number of characters to extract from each row will not exceed the matrix width C
Examples
6 6
a b c d e f
g h i j k l
m n o p q r
s t u v w x
y z a b c d
e f g h i ja
kl
mno
uvwx
yzabc
efghijRow 1: First 1 character → 'a' Row 2: Last 2 characters → 'k' 'l' → 'kl' Row 3: First 3 characters → 'm' 'n' 'o' → 'mno' Row 4: Last 4 characters → 'u' 'v' 'w' 'x' → 'uvwx' Row 5: First 5 characters → 'y' 'z' 'a' 'b' 'c' → 'yzabc' Row 6: Last 6 characters → 'e' 'f' 'g' 'h' 'i' 'j' → 'efghij'
8 5
v f b z c
w o j E a
o F f b k
s o f x l
v n i n C
o u r r B
c p w E x
E r b l ov
Ea
oFf
ofxl
vninC
ourrB
cpwEx
ErbloRow 1: First 1 character → 'v' Row 2: Last 2 characters → 'E' 'a' → 'Ea' Row 3: First 3 characters → 'o' 'F' 'f' → 'oFf' Row 4: Last 4 characters → 'o' 'f' 'x' 'l' → 'ofxl' Row 5: First 5 characters → 'v' 'n' 'i' 'n' 'C' → 'vninC' Row 6: Last 6 characters → 'o' 'u' 'r' 'r' 'B' → 'ourrB' Row 7: First 7 characters → 'c' 'p' 'w' 'E' 'x' → 'cpwEx' Row 8: Last 8 characters → 'E' 'r' 'b' 'l' 'o' → 'Erblo'
Solution
#include <stdio.h>
#include <string.h>
int main() {
int R, C;
scanf("%d %d", &R, &C);
char matrix[R][C];
// Read the matrix
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
scanf(" %c", &matrix[i][j]);
}
}
// Process and print according to the pattern
for (int i = 0; i < R; i++) {
int row_num = i + 1;
if (row_num % 2 == 1) {
// Odd row: print first 'row_num' characters
for (int j = 0; j < row_num && j < C; j++) {
printf("%c", matrix[i][j]);
}
} else {
// Even row: print last 'row_num' characters
for (int j = C - row_num; j < C; j++) {
if (j >= 0) {
printf("%c", matrix[i][j]);
}
}
}
printf("\n");
}
return 0;
}C Solution Explanation:
- Declare a 2D character array to store the matrix
- Read R and C, then read the matrix character by character
- For each row (1-indexed):
- If row number is odd: Print characters from index 0 to (row_num-1)
- If row number is even: Print characters from index (C-row_num) to (C-1)
- The condition j < C in odd rows prevents accessing beyond matrix bounds
- The condition j >= 0 in even rows ensures we don't access negative indices