C Program To Print Character Pyramid Pattern
Here, we will build a C Program To Print Character Pyramid Pattern using 2 approaches i.e.
- Using for loop
- Using while loop
Input:
rows = 5
Output:
A
B B
C C C
D D D D
E E E E E
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.
Example:
C
#include <stdio.h>
int main()
{
int i, j;
int rows = 5;
char character = 'A' ;
for (i = 0; i < rows; i++) {
for (j = 0; j <= i; j++) {
printf ( "%c " , character);
}
printf ( "\n" );
character++;
}
return 0;
}
|
Output
A
B B
C C C
D D D D
E E E E E
Time complexity: O(R*R)
Here R is given no of rows.
Auxiliary space: O(1)
As constant extra space is used.
Approach 2: Printing pattern by converting a given number into a 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.
Example:
C
#include <stdio.h>
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);
printf ( "%c " , character);
}
printf ( "\n" );
number++;
}
return 0;
}
|
Output
A
B B
C C C
D D D D
E E E E E
Time complexity: O(R*R)
Here R is given no of rows.
Auxiliary space : O(1)
As constant extra space is used.
2. Using while loops:
Approach 1: The while loops check the condition until the condition is false. If the condition is true then enter into the loop and execute the statements.
Example:
C
#include <stdio.h>
int main()
{
int i = 1, j = 0;
int rows = 5;
char character = 'A' ;
while (i <= rows) {
while (j <= i - 1) {
printf ( "%c " , character);
j++;
}
printf ( "\n" );
character++;
j = 0;
i++;
}
return 0;
}
|
Output
A
B B
C C C
D D D D
E E E E E
Time complexity: O(R*R)
Here R is given no of rows.
Auxiliary space : O(1)
As constant extra space is used.
Approach 2: Printing pattern by converting given number into character using while loop
Example:
C
#include <stdio.h>
int main()
{
int i = 1, j = 0;
int rows = 5;
int number = 65;
while (i <= rows) {
while (j <= i - 1) {
char character = ( char )(number);
printf ( "%c " , character);
j++;
}
printf ( "\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(R*R) where R is given no of rows
Auxiliary space : O(1)
Last Updated :
26 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...