# Printing Pattern Using Loops in C HackerRank Solution

Printing Pattern using Loops HackeRrank Solution in C. Printing Pattern Using Loops in C HackerRank Solution. In pattern programs in C, we already developed many printing patterns using loops, see more here:- pattern programs in C.

Here a pattern is given. We will write a program for printing patterns using loops in C language.

Sample Inputs/outputs:-

Input: 2
2 2 2
2 1 2
2 2 2

Input: 5
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

In this pattern, digits are from 1 to n. To print these patterns we need nested loops. We can use while loops or for loops but writing programs with for loop is easier than using while loops.

Note:- Outer loop represents rows and the inner loop represents columns.

By observing these input and output we can conclude that for input N, the pattern contains 2*N-1 rows and columns. For example:- if input = 2, then number of rows = 3 and columns = 3 i.e. 2*2-1 = 3; Similarly, if input = 5, then number of rows = 9, and columns = 9 i.e. 2*5-1 = 9.

## Program for Printing Pattern using Loops in C

``````#include<stdio.h>
int main()
{
int n;

printf("Enter n value: ");
scanf("%d",&n);

int len = 2*n-1;
for(int row=0; row<len; row++)
{
for(int col=0; col<len; col++)
{
int min = row<col? row:col;
min=min<len-row? min:len-row-1;
min=min<len-col? min:len-col-1;
printf("%d ",n-min);
}

printf("\n");
}

return 0;
}``````

For the input N, both row and column sizes are (2*N – 1), so we take the variable “len” to store the size of the row and column.

Using the ternary operator or conditional operator we checked that at any position, the row number is lesser than the column number. The lesser value is stored in the variable “min“.

Digits are from 1 to n so, using two more ternary operators we find the minimum value, and ( n – min ) is displayed on the screen.

Similar Pattern Programs in C:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!