C program to print number pattern with 1, 0 at alternate columns
10101
10101
10101
10101
10101

C Programming Language / Loop control in C Language

3445

Program:

/**
 * C program to print number pattern with 1/0 at even/odd position
 * www.atnyla.com 
 */

#include <stdio.h>

int main()
{
    int rows, cols, i, j;

    /* Input rows and columns from user */
    printf("Enter number of rows: ");
    scanf("%d", &rows);
    printf("Enter number of columns: ");
    scanf("%d", &cols);

    for(i=1; i<=rows; i++)
    {
        for(j=1; j<=cols; j++)
        {
            // Print 1 if current column is even
            if(j%2 == 1)
            {
                printf("0");
            }
            else
            {
                printf("1");
            }
        }

        printf("\n");
    }

    return 0;
}

Output:

Enter number of rows: 5
Enter number of columns: 5
10101
10101
10101
10101
10101

Explanation:

Required knowledge

Basic C programming, Loop

Must know - Program to check even number

Logic to print number pattern with 1, 0 at alternate columns

In previous post I explained a similar pattern. Logic to print this is almost similar. If you have noticed the pattern carefully, for every odd columns 0 is printed and for every even columns 1 is printed.

Below is the step by step descriptive logic to print the given pattern.

  1. Input number of rows and columns to print from user. Store it in some variable say rows and cols.
  2. To iterate through rows run an outer loop from 1 to rows. The loop structure should look like for(i=1; i<=rows; i++).
  3. To iterate through columns run an inner loop from 1 to cols. The loop structure should look like for(j=1; j<=cols; j++).
  4. Inside the inner loop print 1 if current column is even otherwise print 0. Means if(j%2==0) then print 1 otherwise print 0.
  5. Finally move to the next line after printing one column.

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.