Printing Pattern using Loops hackerrank step by step solution

Printing Pattern using Loops hackerrank solution:
Welcome back, Guys!!
In this post, we will break the Printing Pattern using Loops hackerrank practice problem.
It is a medium level problem using the concept of nested loops...


Problem Statement is as follows:


In this problem, you need to print the pattern of the following form containing the numbers from  to .

                            4 4 4 4 4 4 4 
                            4 3 3 3 3 3 4 
                            4 3 2 2 2 3 4 
                            4 3 2 1 2 3 4 
                            4 3 2 2 2 3 4 
                            4 3 3 3 3 3 4 
                            4 4 4 4 4 4 4 

Input Format


The input will contain a single integer .

Constraints

1<= n<=1000

Output Format


Print the pattern mentioned in the problem statement.

Sample Input 0

2
Sample Output 0

2 2 2
2 1 2
2 2 2
Sample Input 1

5
Sample Output 1

5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5
Sample Input 2

7
Sample Output 2

7 7 7 7 7 7 7 7 7 7 7 7 7
7 6 6 6 6 6 6 6 6 6 6 6 7
7 6 5 5 5 5 5 5 5 5 5 6 7
7 6 5 4 4 4 4 4 4 4 5 6 7
7 6 5 4 3 3 3 3 3 4 5 6 7
7 6 5 4 3 2 2 2 3 4 5 6 7
7 6 5 4 3 2 1 2 3 4 5 6 7
7 6 5 4 3 2 2 2 3 4 5 6 7
7 6 5 4 3 3 3 3 3 4 5 6 7
7 6 5 4 4 4 4 4 4 4 5 6 7
7 6 5 5 5 5 5 5 5 5 5 6 7
7 6 6 6 6 6 6 6 6 6 6 6 7

7 7 7 7 7 7 7 7 7 7 7 7 7


Printing Pattern using Loops hackerrank solution :

There can be many alternative codes to solve this problem. I have used nested
loops and if-else statements to solve the problem.

#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int i,j,n,k; scanf("%d",&n); for(i=1;i<2*n;i++) { k=n; if(i<=n) { for(j=1;j<2*n;j++) { printf("%d ",k); if(i>j) { k--; } if(i+j>=2*n) { k++; } } } if(i>n) {for(j=1;j<2*n;j++) { printf("%d ",k); if(j>=i) { k++; } if(i+j<2*n) { k--; } } } printf("\n"); } return 0; }


Analyze the code properly.
Feel  free to share your thoughts in the comments sections , if any doubt post it in comments as well , See you next time

Post a Comment

1 Comments

  1. Printing Pattern Using Loops – Hacker Rank Solution
    https://www.codeworld19.com/printing-pattern-using-loops-hacker-rank-solution/

    ReplyDelete