Print string of odd length in ‘X’ format
Last Updated :
11 Sep, 2023
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 part 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++
#include <iostream>
using namespace std;
void printPattern(string str)
{
int len = str.length();
for ( int i = 0, j = len - 1; i <= len, j >= 0;
i++, j--) {
if (i < j) {
for ( int x = 0; x < i; x++)
cout << " " ;
cout << str[i];
for ( int x = 0; x < j - i - 1; x++)
cout << " " ;
cout << str[j] << endl;
}
if (i == j) {
for ( int x = 0; x < i; x++)
cout << " " ;
cout << str[i] << endl;
}
else if (i > j) {
for ( int x = j - 1; x >= 0; x--)
cout << " " ;
cout << str[j];
for ( int x = 0; x < i - j - 1; x++)
cout << " " ;
cout << str[i] << endl;
}
}
}
int main()
{
printPattern( "geeksforgeeks" );
return 0;
}
|
Java
class GFG {
static void pattern(String 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)
System.out.print(str.charAt(k));
else
System.out.print( " " );
}
System.out.println( "" );
}
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
int len = str.length();
pattern(str, len);
}
}
|
Python3
def pattern( str , len ):
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 ( " " )
str = "geeksforgeeks"
len = len ( str )
pattern( str , len )
|
C#
using System;
class GFG {
static void pattern(String 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)
Console.Write(str[k]);
else
Console.Write( " " );
}
Console.Write( "\n" );
}
}
public static void Main()
{
String str = "geeksforgeeks" ;
int len = str.Length;
pattern(str, len);
}
}
|
PHP
<?php
function printPattern( $str )
{
$len = strlen ( $str );
for ( $i = 0, $j = $len - 1;
$i <= $len , $j >= 0;
$i ++, $j --)
{
if ( $i < $j )
{
for ( $x = 0; $x < $i ; $x ++)
echo " " ;
echo $str [ $i ];
for ( $x = 0; $x < $j - $i - 1;
$x ++)
echo " " ;
echo $str [ $j ]. "\n" ;
}
if ( $i == $j )
{
for ( $x = 0; $x < $i ; $x ++)
echo " " ;
echo $str [ $i ]. "\n" ;
}
else if ( $i > $j )
{
for ( $x = $j - 1; $x >= 0;
$x --)
echo " " ;
echo $str [ $j ];
for ( $x = 0; $x < $i - $j - 1;
$x ++)
echo " " ;
echo $str [ $i ]. "\n" ;
}
}
}
printPattern( "geeksforgeeks" );
?>
|
Javascript
<script>
function pattern(str,len)
{
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>" );
}
}
str = "geeksforgeeks" ;
var len = str.length;
pattern(str, len);
</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
Time Complexity: O(len*len), where len is the length of the string.
Auxiliary Space: O(1).
Alternative Solution :
C++
#include <bits/stdc++.h>
using namespace std;
void pattern(string 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)
cout << str[k];
else
cout << " " ;
}
cout << endl;
}
}
int main()
{
string str = "geeksforgeeks" ;
int len = str.size();
pattern(str, len);
return 0;
}
|
Java
class GFG {
static void pattern(String 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)
System.out.print(str.charAt(k));
else
System.out.print( " " );
}
System.out.println( "" );
}
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
int len = str.length();
pattern(str, len);
}
}
|
Python3
def pattern(st, length):
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 ()
if __name__ = = "__main__" :
st = "geeksforgeeks"
length = len (st)
pattern(st, length)
|
C#
using System;
class GFG {
static void pattern(String 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)
Console.Write(str[k]);
else
Console.Write( " " );
}
Console.WriteLine( "" );
}
}
public static void Main(String[] args)
{
String str = "geeksforgeeks" ;
int len = str.Length;
pattern(str, len);
}
}
|
PHP
<?php
function pattern( $str , $len )
{
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" ;
}
}
$str = "geeksforgeeks" ;
$len = strlen ( $str );
pattern( $str , $len );
?>
|
Javascript
<script>
function pattern(str , len)
{
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>' );
}
}
var str = "geeksforgeeks" ;
var len = str.length;
pattern(str, len);
</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
Time Complexity: O(len*len), where len is the length of the string.
Auxiliary Space: O(1).
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
#include <bits/stdc++.h>
using namespace std;
void printPattern(string str, int len)
{
for ( int i = 0; i < len; i++) {
for ( int j = 0; j < len; j++) {
if ((i == j) || (i + j == len - 1))
cout << str[j];
else
cout << " " ;
}
cout << endl;
}
}
int main()
{
string str = "geeksforgeeks" ;
int len = str.size();
printPattern(str, len);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void printPattern(String str, int len)
{
for ( int i = 0 ; i < len; i++) {
for ( int j = 0 ; j < len; j++) {
if ((i == j) || (i + j == len - 1 ))
System.out.print(str.charAt(j));
else
System.out.print( " " );
}
System.out.println();
}
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
int len = str.length();
printPattern(str, len);
}
}
|
Python3
def printPattern( Str , Len ):
for i in range ( Len ):
for j in range ( Len ):
if ((i = = j) or (i + j = = Len - 1 )):
print ( Str [j], end = "")
else :
print ( " " , end = "")
print ()
Str = "geeksforgeeks"
Len = len ( Str )
printPattern( Str , Len )
|
C#
using System;
public class GFG {
static void printPattern( string str, int len)
{
for ( int i = 0; i < len; i++) {
for ( int j = 0; j < len; j++) {
if ((i == j) || (i + j == len - 1))
Console.Write(str[j]);
else
Console.Write( " " );
}
Console.WriteLine();
}
}
static public void Main()
{
String str = "geeksforgeeks" ;
int len = str.Length;
printPattern(str, len);
}
}
|
Javascript
<script>
function printPattern(str , len)
{
for ( var i = 0; i < len; i++)
{
for ( var j = 0; j < len; j++)
{
if ((i == j) || (i + j == len - 1))
document.write(str.charAt(j));
else
document.write( " " );
}
document.write( '<br>' );
}
}
var str = "geeksforgeeks" ;
var len = str.length;
printPattern(str, len);
</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
Time Complexity: O(len*len), where len is the length of the string.
Auxiliary Space: O(1).
This article is contributed by Dinesh T.P.D.
Similar Reads
Find max length odd parity substring
Given a binary string str, the task is to find the maximum length of the sub-string of str that has odd parity. A binary string is said be odd parity if it contains odd number of 1s. Examples: Input: str = "1001110" Output: 6 "001110" is the valid sub-string. Input: str = "101101" Output: 5 Recommen
11 min read
Length of a String
Given a string s, the task is to find the length of the string. Examples: Input: s = "abc"Output: 3 Input: s = "GeeksforGeeks"Output: 13 Input: s = ""Output: 0 Using In-built methodsEvery programming language offers a built-in method as well to find the length [GFGTABS] C++ // C++ program to find le
3 min read
Print the middle character of a string
Given string str, the task is to print the middle character of a string. If the length of the string is even, then there would be two middle characters, we need to print the second middle character. Examples: Input: str = "Java"Output: vExplanation: The length of the given string is even. Therefore,
3 min read
Java String format() Method
In Java, the String.format() method allows us to create a formatted string using a specified format string and arguments. We can concatenate the strings using this method, and at the same time, we can format the output with options such as width, alignment, decimal places, and more. Example: In the
5 min read
Formatted Output in Java using printf()
Sometimes in programming, it is essential to print the output in a given specified format. Most users are familiar with the printf function in C. Let us discuss how we can Formatting Output with printf() in Java in this article. Formatting Using Java Printf()printf() uses format specifiers for forma
5 min read
Check if all the palindromic sub-strings are of odd length
Given a string 's' check if all of its palindromic sub-strings are of odd length or not. If yes then print "YES" or "NO" otherwise. Examples: Input: str = "geeksforgeeks" Output: NO Since, "ee" is a palindromic sub-string of even length. Input: str = "madamimadam" Output: YES Brute Force Approach: S
10 min read
Rotations of a Binary String with Odd Value
Given a binary string. We are allowed to do circular rotation of the string without changing the relative order of the bits in the string. For Example, all possible circular rotation of string "011001" are: 101100 010110 001011 100101 110010 We are required to tell total number of distinct odd decim
3 min read
Print lower triangle with alternate '*' and '#'
Given a number N which denotes the number of rows, the task is to follow the below pattern to print the first N rows of it. Pattern: **#*#**#*#*#*#* Examples: Input: N = 2Output:**# Input: N = 6Output: **#*#**#*#*#*#**#*#*# Approach: Follow the below steps to implement the above pattern: Initialize
4 min read
Number of even substrings in a string of digits
Given a string of digits 0 - 9. The task is to count a number of substrings which when converting into integer form an even number. Examples : Input : str = "1234".Output : 6"2", "4", "12", "34", "234", "1234" are 6 substring which are even.Input : str = "154".Output : 3Input : str = "15".Output : 0
9 min read
K-th lexicographical string of given length
Given two integers N and K, the task is to find lexicographically Kth string of length N. If the number of possible strings of length N is less than K, print -1.Examples: Input: N = 3, K = 10 Output: "aaj" Explanation: The 10th string in the lexicographical order starting from "aaa" is "aaj".Input:
7 min read