
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print String of Odd Length in X Format in C
Given with a string program must print the string in ‘X’ format. For reference, see the image given below.
Here, one variable can be used to print from left right(“i”) and other variable can used to print from right to left(“j”) and we can take other variable k which is used for space calculation.
Below is the C++ implementation of the algorithm given.
Algorithm
START Step 1 ->Declare Function void print(string str, int len) Loop For int i = 0 and i < len and i++ Set int j = len-1- i Loop For int k = 0 and k < len and k++ IF k == i || k == j Print str[k] End Else Print " " End End Step 2 -> In main() Declare string str = "tutorialpoint" Set int len = str.size() Call print(str, len) STOP
Example
#include<iostream> using namespace std; void print(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 = "tutorialpoint"; int len = str.size(); print(str, len); return 0; }
Output
if we run above program then it will generate following output
Advertisements