Problem 18: Write a program to print the following pyramid:
A
AB
ABC
ABCD
ABCDE
ABCDEF
Solution:
When we will try to print a pyramid, first we have to count how many rows/lines we have to print. For the above example, it has 6 rows/lines. Then we have to consider how many columns will need to print for each row/line.
Have a close look at the following code..
#include<stdio.h>
void Print() {
int i, j;
for(i = 0; i<6; i++) {
for(j = 0; j<= i; j++) {
printf("%c",j+'A');
}
printf("\n");
}
}
int main() {
Print();
return 0;
}
|
Analysis:
When i = 0, j = 0, we print j+'A' = 0 + 'A' = 0 + 65 = 65 ( A)
When i = 1, j = 0, 1, we print 0+'A' and 1+'A' = 65 and 66 = 'A' and B
When i = 2, j = 0, 1, 2, we print ABC ( similar way)
.
.
.
When i = 5, j = 0, 1, 2, 3, 4, 5 = 'A'+0,'A' + 1, ...... 'A'+5 = ABCDEF
.
.
One point to note: int d = 'A'+ 10 = 65 + 10 = 75 as we know the ASCII of 'A' = 65
Other point: printf("%c",65) will print 'A', because when we print an integer with "%c", it prints the corresponding ASCII character of that integer.
Back to Problem list