Print string of odd length in 'X' format - GeeksforGeeks
Given a string of odd length, print the string X format.
https://ideone.com/l8wyjY
Given a string of odd length, print the string X format.
Input: 12345 Output: 1 5 2 4 3 2 4 1 5The idea is to use two variables in a single loop, the first variable ‘i’ goes from left to right and second variables ‘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].
// Function to print given string in cross pattern
// Length of string must be odd
void
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
// til 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 spances
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;
}
}
}
- int main()
- {
- char str[100];
- int i,j,l;
- cin>>str;
- l=strlen(str);
- for(i=0;i<l;i++)
- {
- for(j=0;j<l;j++)
- {
- if(i==j||(i+j==l-1))
- cout<<str[j];
- else
- cout<<" ";
- }
- cout<<"\n";
- }
- return 0;
- }