Monday, September 25, 2017

Pattern - ZigZag Number Square

Given an integer N as the input, print the pattern as given in the Example Input/Output section.

Input Format:
The first line contains N.

Output Format:
N lines containing the desired pattern.

Boundary Conditions: 2 <= N <= 50

Example Input/Output:
Input:
5
Output:
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25

Solution:
#include<stdio.h>
void printPattern(int n)
{
 for(int i=1;i<=n;i++)
 {
    for(int j=(i*n)-n+1;j<=i*n&&i%2==1;j++)
      printf("%d ",j);
    for(int j=(i*n);j>(i*n)-n&&i%2==0;j--)
      printf("%d ",j);
    printf("\n");
 }
}
int main()
{
    int N;
    scanf("%d",&N);
    printPattern(N);
    return 0;
}


Share: