To print snake pattern using two loop | ZOHO

To print snake pattern using two loop | ZOHO

Question:

Write a program to print snake pattern without using arrays and  using two loop

Snake

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.
  • Starting value for each row is k+n.
  • Using the above conditions print the 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

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.