C++ Program To Print Continuous Character Pattern
Here we will build a C++ Program To Print Continuous Character patterns using 2 different methods i.e:
- Using for loops
- Using while loops
Input:
rows = 5
Output:
A
B C
D E F
G H I J
K L M N O
1. Using for loop
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 and increment the character value at each column to print a continuous character pattern.
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 << " " ;
character++;
}
cout << "\n" ;
}
return 0;
}
|
Output
A
B C
D E F
G H I J
K L M N O
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 and increment the character value at each column to print a continuous character pattern.
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 << " " ;
number++;
}
cout << "\n" ;
}
return 0;
}
|
Output
A
B C
D E F
G H I J
K L M N O
Using while loops:
Input:
rows=5
Output:
A
B C
D E F
G H I J
K L M N O
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++;
character++;
}
cout << "\n" ;
j = 0;
i++;
}
return 0;
}
|
Output
A
B C
D E F
G H I J
K L M N O
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++;
number++;
}
cout << "\n" ;
j = 0;
i++;
}
return 0;
}
|
Output
A
B C
D E F
G H I J
K L M N O
Time complexity: O(n2) where n is given no of rows
Space complexity: O(1)
Last Updated :
30 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...