# Print string of odd length in ‘X’ format

StringViews 1142

INPUT
s = “abcde”

OUTPUT

a            e
b     d
c
b     d
a             e

## Algorithm

1. Traverse the string with two varaiables, i and j, where i is increasing and j is decreasing

2. Print the upper part ie, if(i<j)
a. Print i spaces
b. print ith character
c. Print j-i-1 spaces
d. Print jth character

3. Print the centre point ie, if(i==j)
a. Print i spaces
b. Print middle character

4. Print the lower part ie, if(i>j)
a. Print j spaces
b. print ith character
c. Print j-i-1 spaces
d. Print jth character

## C++ Program

```#include<iostream>
using namespace std;

// Function to print given string in cross pattern
// Length of string must be odd
void printXFormat(string s)
{
int len = s.length();

// i varaible from start to end, j from end to start
for (int i=0,j=len-1; i<=len,j>=0; i++,j--)
{
//Printing upper part, ie till middle element
if (i<j)
{
// Print i spaces
for (int x=0; x<i; x++)
cout << " ";

// Print i'th character
cout << s[i];

// Print j-i-1 spaces
for (int x=0; x<j-i-1; x++)
cout << " ";

// Print j'th character
cout << s[j] << endl;
}

// To print center point
if (i==j)
{
// Print i spaces
for (int x=0; x<i; x++)
cout << " ";

// Print middle character
cout << s[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 << s[j];

// Print i-j-1 spaces
for (int x=0; x<i-j-1; x++)
cout << " ";

// Print i'h character
cout << s[i] << endl;
}
}
}

int main()
{
printXFormat("abcde");
return 0;
}```

Translate »