Home / Programs / C program to print number pattern with 1, 0 at alternate columns 10101 10101 10101 10101 10101
Programming Example

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

👁 3,463 Views
💻 Practical Program
📘 Step by Step Learning
Write a C program to print the given number pattern series of 1's and 0's at alternate columns using loop. How to print number pattern with one's at even column and zero's at odd column using for loop in C programming. Logic to print given number pattern of 1 and 0 at alternate columns.

Program Code

/**
 * 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.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.