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
Print string of odd length in 'X' format in C Program.
Given a string of odd length, we need to print it in 'X' format where characters are displayed diagonally from top-left to bottom-right and top-right to bottom-left, creating an X pattern.
Syntax
void printXPattern(char str[], int len);
Algorithm
- Use variable
ito iterate through rows (0 to len-1) - Calculate
j = len-1-ifor the right diagonal position - For each column position
k, print character ifk == iork == j, otherwise print space - Move to next line after each row
Example
Here's the C implementation to print a string in X format −
#include <stdio.h>
#include <string.h>
void printXPattern(char str[], int len) {
for (int i = 0; i < len; i++) {
int j = len - 1 - i;
for (int k = 0; k < len; k++) {
if (k == i || k == j)
printf("%c", str[k]);
else
printf(" ");
}
printf("
");
}
}
int main() {
char str[] = "tutorialpoint";
int len = strlen(str);
printf("String in X format:
");
printXPattern(str, len);
return 0;
}
String in X format:
t t
u n
t i
o a
r l
i p
a
l o
p i
o n
i t
n t
t u
How It Works
-
Left diagonal: Position
igives us characters from top-left to bottom-right -
Right diagonal: Position
j = len-1-igives us characters from top-right to bottom-left - Space filling: All other positions are filled with spaces to maintain the X structure
- Center intersection: For odd-length strings, the center character appears at the intersection of both diagonals
Key Points
- This algorithm works best with odd-length strings to create a symmetric X pattern
- Time complexity is O(n²) where n is the string length
- Space complexity is O(1) as no extra space is used
Conclusion
The X pattern printing technique uses two diagonal traversals to create an intersection pattern. This approach effectively demonstrates nested loops and conditional character placement in C programming.
Advertisements
