Print snake pattern using two loop | ZOHO

Print snake pattern using two loop | ZOHO

Question

Write a program to print snake pattern without using arrays and using two-loop. Give an efficient solution. The output should be like the one given below.

print snake pattern

Explanation:

From the image,  you can see that the number of spaces at the beginning of the line decreases one by one.  Numbers increase one by one in the left to the right direction.  This format should be followed for any input.

Logic:

  • Get the input from the user which is n.
  • Then row size is n and column size is (2*n)-i, ie i value is 1, 2, 3,….etc
  • Print space in front of numbers for each row which satisfying the condition j<=n-i.
  • For odd row increment k and for even decrement k.
  • The starting value for each row is k+n.
  • Using the above conditions print the snake pattern.

Brief Explanation:

  • Let us consider input n=4 and then went to the loop to print the pattern
  • The outer loop executes for 4 times which is the row size
  • The inner loop determines the column size ie, changing for every row by using the formula (2*n)-i
  • For the first row, the column value is 7 in that space is n-i which is 3 spaces are printed and the starting value is determined  by k is incremented for odd rows and decremented for even rows here k=1 and printed up to 4
  • The next row is even k value is added with n which is 4 and k=8, 2 spaces are printed and k value is decremented up to 5
  • The same thing will happen for each odd and even row and at last, we have a snake pattern

Program:

#include<stdio.h>
void main()
{
    int n,i,j,k=0;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=(2*n)-i;j++)   //(2*n)-i  is number columns for each row
        {
            if(j<=n-i)            //print the spaces
            {
                printf(" ");
            }
            else if(i%2==1)       //print the odd rows
            {
                k++;
                printf("%d ",k);
            }
            else                  //print the even rows
            {
                printf("%d ",k);
                k--;             //decrement the values
            }
        }k+=n;                   //starting value for each row
        printf("\n");
    }
}

 

 

Join Group: WhatsApp Group link

You might also like:

Print Sequence Of Numbers Without Using Loop

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.
3.5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x