We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
With this kind of problems, I always think about separating it into several shapes. Here's what I do with this problem:
voidprint_upper_part(intn){inti,j,k,m;for(i=n;i>=1;i--){// generate left triangle of numbers// the shape is somethin like:// *// **// ***// ****// *****for(j=n;j>=i;j--){printf("%d ",j);}// use the value before the last decrementj++;// generate the reverse pyramid using value of j// the shape is something like:// *******// *****// ***// *for(k=1;k<=(2*j)-3;k++){printf("%d ",j);}// avoid printing 1 again since 1 has been printed at the left trianglej=j==1?2:j;// generate right triangle of numbers// the shape is somethin like:// *// **// ***// ****// *****for(m=j;m<=n;m++){printf("%d ",m);}printf("\n");}}voidprint_lower_part(intn){inti,j,k,m;for(i=2;i<=n;i++){// generate left triangle of numbers// the shape is somethin like:// *****// ****// ***// **// *for(j=n;j>=i;j--){printf("%d ",j);}// use the value before the last decrementj++;// generate the pyramid using value of j// the shape is something like:// * // ***// *****// *******for(k=1;k<=(2*j)-3;k++){printf("%d ",j);}// generate right triangle of numbers// the shape is somethin like:// *****// ****// ***// **// *for(m=i;m<=n;m++){printf("%d ",m);}printf("\n");}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Printing Pattern Using Loops
You are viewing a single comment's thread. Return to all comments →
With this kind of problems, I always think about separating it into several shapes. Here's what I do with this problem: