Print string of odd length in 'X' format - GeeksforGeeks

25 Nov, 2021
Given a string of odd length, print the string X format.Examples : 
Input: 12345
Output:
1       5
  2   4
    3
  2   4
1       5 

Input: geeksforgeeks
Output:
g                         s
  e                     k
    e                 e
      k             e
        s         g
          f      r
             o
          f     r
        s         g
      k             e
    e                 e
  e                      k
g                          s 
We strongly recommend you to minimize your browser and try this yourself first.The idea is to use two variables in a single loop, the first variable ‘i’ goes from left to right and second variable ‘j’ goes from right to left. The upper part of Cross (or X) is printed before they meet. The central character is printed when they meet and lower parted is printed after they cross each other. In the upper part str[i] is printed before str[j] and in the lower part, str[j] is printed before str[i].Below is the implementation of above idea.  
C
Java
Python3
C#
PHP
Javascript
// C++ program to print Cross pattern#include<iostream>using namespace std; // Function to print given string in cross pattern// Length of string must be oddvoid printPattern(string str){    int len = str.length();     // i goes from 0 to len and j goes from len-1 to 0    for (int i=0,j=len-1; i<=len,j>=0; i++,j--)    {        // To print the upper part. This loop runs        // till middle point of string (i and j become        // same        if (i<j)        {            // Print i spaces            for (int x=0; x<i; x++)                cout << " ";             // Print i'th character            cout << str[i];             // Print j-i-1 spaces            for (int x=0; x<j-i-1; x++)                cout << " ";             // Print j'th character            cout << str[j] << endl;        }         // To print center point        if (i==j)        {            // Print i spaces            for (int x=0; x<i; x++)                cout << " ";             // Print middle character            cout << str[i] << endl;        }         // To print lower part        else if (i>j)        {            // Print j spaces            for (int x = j-1; x>=0; x--)                cout << " ";             // Print j'th character            cout << str[j];             // Print i-j-1 spaces            for (int x=0; x<i-j-1; x++)                cout << " ";             // Print i'h character            cout << str[i] << endl;        }    }} // Driver programint main(){    printPattern("geeksforgeeks");    return 0;}
// Java program to// print cross patternclass GFG{ // Function to print given// string in cross patternstatic void pattern(String str,                    int len){         // i and j are the indexes    // of characters to be    // displayed in the ith    // iteration i = 0 initially    // and go upto length of string    // j = length of string initially    // in each iteration of i,    // we increment i and decrement j,    // we print character only    // of k==i or k==j    for (int i = 0; i < len; i++)    {        int j = len - 1 - i;        for (int k = 0; k < len; k++)        {            if (k == i || k == j)                System.out.print(str.charAt(k));            else                System.out.print(" ");        }        System.out.println("");    }} // Driver codepublic static void main (String[] args){    String str = "geeksforgeeks";    int len = str.length();    pattern(str, len); }} // This code is contributed// by Smitha
# Python 3 program to# print cross pattern # Function to print given# string in cross patterndef pattern(str, len):         # i and j are the indexes    # of characters to be    # displayed in the ith    # iteration i = 0 initially    # and go upto length of string    # j = length of string initially    # in each iteration of i, we    # increment i and decrement j,    # we print character only of    # k==i or k==j    for i in range(0, len):             j = len -1 - i        for k in range(0, len):                     if (k == i or k == j):                print(str[k],                      end = "")            else:                print(end = " ")                 print(" ") # Driver codestr = "geeksforgeeks"len = len(str)pattern(str, len) # This code is contributed# by Smitha
// C# program to print// cross patternusing System; class GFG{ // Function to print given// string in cross patternstatic void pattern(String str,                    int len){         // i and j are the indexes    // of characters to be    // displayed in the ith    // iteration i = 0 initially    // and go upto length of string    // j = length of string initially    // in each iteration of i, we    // increment i and decrement j,    // we print character only of    // k==i or k==j    for (int i = 0; i < len; i++)    {        int j = len - 1 - i;        for (int k = 0; k < len; k++)        {            if (k == i || k == j)                Console.Write(str[k]);            else                Console.Write(" ");        }        Console.Write("\n");    }} // Driver codepublic static void Main (){    String str = "geeksforgeeks";    int len = str.Length;    pattern(str, len);}} // This code is contributed by Smitha
<?php// PHP program to print// Cross pattern // Function to print given// string in cross pattern,// Length of string must be oddfunction printPattern($str){    $len = strlen($str);     // i goes from 0 to len and    // j goes from len-1 to 0    for ($i = 0, $j = $len - 1;         $i <= $len, $j >= 0;         $i++, $j--)    {        // To print the upper part.        // This loop runs till middle point        // of string i and j become same        if ($i < $j)        {            // Print i spaces            for ($x = 0; $x < $i; $x++)                echo " ";             // Print i'th character            echo $str[$i];             // Print j-i-1 spaces            for ( $x = 0; $x < $j - $i - 1;                                      $x++)                echo " ";             // Print j'th character            echo $str[$j]."\n";        }         // To print center point        if ($i == $j)        {            // Print i spaces            for ($x = 0; $x < $i; $x++)                echo " ";             // Print middle character            echo $str[$i]."\n";        }         // To print lower part        else if ($i > $j)        {            // Print j spaces            for ($x = $j - 1; $x >= 0;                                 $x--)                echo " ";             // Print j'th character            echo $str[$j];             // Print i-j-1 spaces            for ( $x = 0; $x < $i - $j - 1;                                      $x++)                echo " ";             // Print i'h character            echo $str[$i]."\n";        }    }} // Driver codeprintPattern("geeksforgeeks"); // This code is contributed by mits?>
<script> // javascript program to// print cross pattern // Function to print given// string in cross patternfunction pattern(str,len){         // i and j are the indexes    // of characters to be    // displayed in the ith    // iteration i = 0 initially    // and go upto length of string    // j = length of string initially    // in each iteration of i,    // we increment i and decrement j,    // we print character only    // of k==i or k==j    for (i = 0; i < len; i++)    {        var j = len - 1 - i;        for (k = 0; k < len; k++)        {            if (k == i || k == j)                document.write(str.charAt(k));            else                document.write(" ");        }        document.write("<br>");    }} // Driver codestr = "geeksforgeeks";var len = str.length;pattern(str, len); // This code is contributed by Amit Katiyar</script>
Output : 
g           s
 e         k
  e       e
   k     e
    s   g
     f r
      o
     f r
    s   g
   k     e
  e       e
 e         k
g           s
Alternative Solution :  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to print cross pattern#include<bits/stdc++.h>using namespace std; // Function to print given string in// cross patternvoid pattern(string str, int len){         // i and j are the indexes of characters    // to be displayed in the ith iteration    // i = 0 initially and go upto length of    // string    // j = length of string initially    // in each iteration of i, we increment    // i and decrement j, we print character    // only of k==i or k==j    for (int i = 0; i < len; i++)    {        int j = len -1 - i;        for (int k = 0; k < len; k++)        {            if (k == i || k == j)                cout << str[k];            else                cout << " ";        }        cout << endl;          }} // driver codeint main (){    string str = "geeksforgeeks";    int len = str.size();    pattern(str, len);     return 0;}// This code is contributed by Satinder Kaur
// Java program to print cross pattern class GFG{ // Function to print given // string in cross patternstatic void pattern(String str, int len){         // i and j are the indexes of    // characters  to be displayed    // in the ith iteration i = 0    // initially and go upto length    // of string j = length of string     // initially in each iteration    // of i, we increment i and decrement    // j, we print character only    // of k==i or k==j    for (int i = 0; i < len; i++)    {        int j = len -1 - i;        for (int k = 0; k < len; k++)        {            if (k == i || k == j)                System.out.print(str.charAt(k));                             else                System.out.print(" ");        }        System.out.println("");        }} // driver codepublic static void main(String[] args){    String str = "geeksforgeeks";    int len = str.length();    pattern(str, len);}} // This code is contributed by 29AjayKumar
# Python 3 program to print cross pattern # Function to print given string in# cross patterndef pattern(st, length):         # i and j are the indexes of characters    # to be displayed in the ith iteration    # i = 0 initially and go upto length of    # string    # j = length of string initially    # in each iteration of i, we increment    # i and decrement j, we print character    # only of k==i or k==j    for i in range(length):        j = length -1 - i        for k in range(length):            if (k == i or k == j):                print(st[k],end="")            else:                print(" ",end="")        print() # driver codeif __name__ == "__main__":       st = "geeksforgeeks"    length = len(st)    pattern(st, length)
// C# program to print cross patternusing System; class GFG{ // Function to print given// string in cross patternstatic void pattern(String str, int len){         // i and j are the indexes of    // characters to be displayed    // in the ith iteration i = 0    // initially and go upto length    // of string j = length of string    // initially in each iteration    // of i, we increment i and decrement    // j, we print character only    // of k==i or k==j    for (int i = 0; i < len; i++)    {        int j = len -1 - i;        for (int k = 0; k < len; k++)        {            if (k == i || k == j)                Console.Write(str[k]);                             else                Console.Write(" ");        }        Console.WriteLine("");        }} // Driver codepublic static void Main(String[] args){    String str = "geeksforgeeks";    int len = str.Length;    pattern(str, len);}} // This code is contributed by Rajput-Ji
<?php// PHP program to print// cross pattern // Function to print given// string in cross patternfunction pattern($str, $len){         // i and j are the indexes of    // characters  to be displayed    // in the ith iteration i = 0    // initially and go upto length of    // string    // j = length of string initially    // in each iteration of i, we    // increment i and decrement j, we    // print character only of k==i or k==j    for ($i = 0; $i < $len; $i++)    {        $j = $len -1 - $i;        for ($k = 0; $k < $len; $k++)        {            if ($k == $i || $k == $j)                echo $str[$k];            else                echo " ";        }        echo "\n";    }} // Driver code$str = "geeksforgeeks";$len = strlen($str);pattern($str, $len); // This code is contributed by mits?>
<script> // Javascript program to print cross pattern // Function to print given // string in cross patternfunction pattern(str , len){         // i and j are the indexes of    // characters  to be displayed    // in the ith iteration i = 0    // initially and go upto length    // of string j = length of string     // initially in each iteration    // of i, we increment i and decrement    // j, we print character only    // of k==i or k==j    for (var i = 0; i < len; i++)    {        var j = len -1 - i;        for (var k = 0; k < len; k++)        {            if (k == i || k == j)                document.write(str.charAt(k));                             else                document.write(" ");        }        document.write('<br>');        }} // driver codevar str = "geeksforgeeks";var len = str.length;pattern(str, len);  // This code is contributed by 29AjayKumar </script>
Output : 
g           s
 e         k
  e       e
   k     e
    s   g
     f r
      o
     f r
    s   g
   k     e
  e       e
 e         k
g           s
Solution 3: This problem can also be solved by observing that the characters are printed along the left and right diagonals only if we enclose the pattern within a matrix. Now, if the length of the string is len then the pattern can be enclosed within a square matrix of order len.  
The elements along the left diagonal can be accessed by the condition ( i==j ) where i and j are the row and column numbers respectively.
The elements along the right diagonal can be accessed by the condition (i+j == len-1).
So, run a nested loop of order len and fill the positions satisfying at the above two conditions with respective characters and the rest of the positions with blank spaces.Below is the implementation of the above approach:  
CPP
Java
Python3
C#
Javascript
// C++ program to print the given pattern #include<bits/stdc++.h>using namespace std; // Function to print the given// string in respective patternvoid printPattern(string str, int len){      for(int i = 0; i < len; i++)    {        for(int j = 0; j < len; j++)        {              // Print characters at corresponding            // places satisfying the two conditions            if((i == j) || (i + j == len-1))                cout<<str[j];            // Print blank space at rest of places            else                cout<<" ";        }                 cout<<endl;    }} // Driver Codeint main(){    string str = "geeksforgeeks";         int len = str.size();         printPattern(str, len);         return 0;} // This code and Approach is contributed by// Aravind Kimonn
// Java program to print the given patternimport java.io.*;class GFG{   // Function to print the given  // string in respective pattern  static void printPattern(String str, int len)  {    for(int i = 0; i < len; i++)    {      for(int j = 0; j < len; j++)      {           // Print characters at corresponding        // places satisfying the two conditions        if((i == j) || (i + j == len - 1))          System.out.print(str.charAt(j));         // Print blank space at rest of places        else          System.out.print(" ");      }       System.out.println();    }  }   // Driver code  public static void main (String[] args)  {       String str = "geeksforgeeks";    int len = str.length();    printPattern(str, len);  }} // This code is contributed by rag2127.
# Python3 program to print the given pattern # Function to print the given# string in respective patterndef printPattern (Str, Len) :    for i in range(Len) :        for j in range(Len) :                         # Print characters at corresponding            # places satisfying the two conditions            if ((i == j) or (i + j == Len - 1)) :                print(Str[j], end = "")                             # Print blank space at rest of places            else :                print(" ", end = "")        print()                  Str = "geeksforgeeks"Len = len(Str)printPattern(Str, Len) # This code is contributed by divyeshrabadiya07.
// C# program to print the given patternusing System;public class GFG{   // Function to print the given  // string in respective pattern  static void printPattern(string str, int len)  {    for(int i = 0; i < len; i++)    {      for(int j = 0; j < len; j++)      {           // Print characters at corresponding        // places satisfying the two conditions        if((i == j) || (i + j == len - 1))          Console.Write(str[j]);         // Print blank space at rest of places        else          Console.Write(" ");      }      Console.WriteLine();    }  }   // Driver code    static public void Main ()  {    String str = "geeksforgeeks";    int len = str.Length;    printPattern(str, len);  }} // This code is contributed by avanitrachhadiya2155
<script>// javascript program to print the given pattern // Function to print the given  // string in respective pattern  function printPattern(str , len)  {    for(var i = 0; i < len; i++)    {      for(var j = 0; j < len; j++)      {           // Print characters at corresponding        // places satisfying the two conditions        if((i == j) || (i + j == len - 1))          document.write(str.charAt(j));         // Print blank space at rest of places        else          document.write(" ");      }       document.write('<br>');    }  }   // Driver code  var str = "geeksforgeeks";  var len = str.length;  printPattern(str, len); // This code is contributed by 29AjayKumar</script>
Output : 
g           s
 e         k
  e       e
   k     e
    s   g
     f r
      o
     f r
    s   g
   k     e
  e       e
 e         k
g           s
https://youtu.be/7gyjMrezEos  
This article is contributed by Dinesh T.P.D. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
 
Mithun Kumar
Smitha Dinesh Semwal
29AjayKumar
Rajput-Ji
Akanksha_Rai
ManasChhabra2
ukasp
kavinkumar999
rag2127
avanitrachhadiya2155
divyeshrabadiya07
amit143katiyar
simranarora5sos
surinderdawra388
pattern-printing
Zoho
Strings
Zoho
Strings
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different methods to reverse a string in C/C++
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Reverse words in a given string
Check whether two strings are anagram of each other