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.
This is an easy solution based on make square legth ( 2*n-1 ) measuring the distance to the middle whose value is known =1 when i=j=n
small example for n=3 so it willl be square of 3*2-1=5
now in 25 we will get |2-3|=1 , |5-3|=2
will choose the max wich is 2 and add 1 so it will be 3
in 33 |3-3|=0 , 0+1=1
in 52 |5-3|=2 , |2-3|=1 max is 2 ,2+1=3
look at following code
#include<stdio.h>#include<string.h>#include<math.h>#include<stdlib.h>intmain(){intn=0,disi=0,disj=0,dis=0;//define varsscanf("%d",&n);//get the numberfor(inti=1;i<=2*n-1;i++){//vertical loopfor(intj=1;j<=2*n-1;j++){//horizontal loopdisi=abs(i-n);//measure vertically to middle & make it absolute valuedisj=abs(j-n);//measure horizontally to middle & make it absolute valueif(disi>disj){//choose the largest distancedis=disi;}else{dis=disj;}printf("%d ",dis+1);//print the distance +1}printf("\n");}return0;}
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 →
This is an easy solution based on make square legth ( 2*n-1 ) measuring the distance to the middle whose value is known =1 when i=j=n small example for n=3 so it willl be square of 3*2-1=5