Reputation: 209
I was doing some hackerrank practice and I couldnt solve it. I am newbie any ideas to solve this problem?
Please write a software program that prints the following pyramid pattern to the screen. Your program should get a number “n” as an input and should print n lines of the pyramid. (For example if your input is 4, then the following output is expected.)
(You can choose any programming language that you want.)
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
#include<stdio.h>
int main()
{
int i,j,k,l=1;
for(i=1; i<=5; i++)
{
for(j=4; j>=i; j--)
{
printf(" ");
}
for(k=1; k<=l; k++)
{
printf("%d",k);
}
l = l+2;
printf("\n");
}
return 0;
}
Upvotes: 0
Views: 465
Reputation: 5309
These types of problems can be solved by simple mathematics.
I would advice you to solve this by problem by breaking it into simpler and smaller use cases as follows:
Number of blank spaces on each line.
Number of Elements (on each line) until the centre of pyramid.
Number of Elements (on each line) after the centre of pyramid.
#include<stdio.h>
int main()
{
int N;
scanf("%d", &N);
int numberOfBlankSpaces = N + 2;
for(int i=1; i<=N ;i++){
for(int j=0;j<numberOfBlankSpaces;j++){
printf(" ");
}
numberOfBlankSpaces -= 2;
int number_of_elements_until_centre_on_each_line = i;
int startingElement = i;
//Print increasing order until center
while(number_of_elements_until_centre_on_each_line--){
printf("%d ", startingElement);
startingElement++;
}
// Starting element = Element at center - 1
startingElement-=2;
//Print decresing order
while(startingElement >= i){
printf("%d ", startingElement);
startingElement--;
}
printf("\n");
}
return 0;
}
Input: 4
Output:
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
Upvotes: 2