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.

t t u n t i o r a i l a p l o p i

Syntax

void printXPattern(char str[], int len);

Algorithm

  1. Use variable i to iterate through rows (0 to len-1)
  2. Calculate j = len-1-i for the right diagonal position
  3. For each column position k, print character if k == i or k == j, otherwise print space
  4. 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 i gives us characters from top-left to bottom-right
  • Right diagonal: Position j = len-1-i gives 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.

Updated on: 2026-03-15T11:53:39+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements