C++ Program to Print Cross or X Pattern
Last Updated :
30 Oct, 2023
Given a number n, we need to print an X pattern of size n.
Input : n = 3
Output :
$ $
$
$ $
Input : n = 5
Output :
$ $
$ $
$
$ $
$ $
Input : n = 4
Output :
$ $
$$
$$
$ $
We need to print n rows and n columns. So we run two nested loops. The outer loop prints all rows one by one (runs for i = 1 to n). The inner loop (runs for j = 1 to n) runs all columns of current row. Now a row can contain spaces and ‘$’. How do we decide where to put space and where ‘$’. For i = 1 : First and last column should contain ‘$’ For i = 2 : Second and second last column should contain ‘$’ In general, i-th and (n + 1 – i)-th columns should contain ‘$’
C++14
#include <iostream>
using namespace std;
void printPattern( int & n)
{
for ( int i = 1; i <= n; i++) {
for ( int j = 1; j <= n; j++) {
if (j == i || j == (n + 1 - i))
cout << "$" ;
else
cout << " " ;
}
cout << endl;
}
}
int main()
{
int n = 6;
printPattern(n);
return 0;
}
|
Output
$ $
$ $
$$
$$
$ $
$ $
Time Complexity: O(n2), where n represents the given input.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...