C++ Program To Print Character Pattern
Here we will build a C++ Program To Print Character patterns using 2 Approaches i.e.
- Using for loop
- Using while loop
Printing 1 character pattern in C++ using different approaches.
1. Using for loop
Input:
rows = 5
Output:
A
B B
C C C
D D D D
E E E E E
Approach 1:
Assign any character to one variable for the printing pattern. The first for loop is used to iterate the number of rows and the second for loop is used to repeat the number of columns. Then print the character based on the number of columns.
C++
#include <iostream>
using namespace std;
int main()
{
int i, j;
int rows = 5;
char character = 'A' ;
for (i = 0; i < rows; i++) {
for (j = 0; j <= i; j++) {
cout << character << " " ;
}
cout << "\n" ;
character++;
}
return 0;
}
|
Output
A
B B
C C C
D D D D
E E E E E
Approach 2:
Printing pattern by converting given number into character.
Assign any number to one variable for the printing pattern. The first for loop is used to iterate the number of rows and the second for loop is used to repeat the number of columns. After entering into the loop convert the given number into character to print the required pattern based on the number of columns.
C++
#include <iostream>
using namespace std;
int main()
{
int i, j;
int rows = 5;
int number = 65;
for (i = 0; i < rows; i++) {
for (j = 0; j <= i; j++) {
char character = char (number);
cout << character << " " ;
}
cout << "\n" ;
number++;
}
return 0;
}
|
Output
A
B B
C C C
D D D D
E E E E E
2. Using while loops
Input:
rows = 5
Output:
A
B B
C C C
D D D D
E E E E E
Approach 1:
The while loops check the condition until the condition is false. If the condition is true then it enters into the loop and executes the statements.
C++
#include <iostream>
using namespace std;
int main()
{
int i = 1, j = 0;
int rows = 5;
char character = 'A' ;
while (i <= rows) {
while (j <= i - 1) {
cout << character << " " ;
j++;
}
cout << "\n" ;
character++;
j = 0;
i++;
}
return 0;
}
|
Output
A
B B
C C C
D D D D
E E E E E
Approach 2:
Printing pattern by converting given number into character using while loop.
C++
#include <iostream>
using namespace std;
int main()
{
int i = 1, j = 0;
int rows = 5;
int number = 65;
while (i <= rows) {
while (j <= i - 1) {
char character = char (number);
cout << character << " " ;
j++;
}
cout << "\n" ;
number++;
j = 0;
i++;
}
return 0;
}
|
Output
A
B B
C C C
D D D D
E E E E E
Time complexity: O(n2) where n is given no of rows
Space complexity: O(1)
Last Updated :
10 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...