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

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.

Example:
Input rows: 5
Input columns: 5
Output:
01010
01010
01010
01010
01010

Required knowledge

Basic C programming, Loop

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

Before moving on to this programs logic you must know how to check even odd numbers.

Logic to this program is almost similar to the previous number pattern (Print 1, 0 number pattern at alternate rows). The only thing we need to do change from previous program is check before print 1 that if the current column if 0 or not. If the current column is even then print 0 otherwise 0.

Program to print number pattern with 1, 0 at even/odd columns

/**
 * C program to print number pattern with 1/0 at even/odd position
 */

#include <stdio.h>

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

    /*
     * Reads number of rows, columns to be printed
     */
    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("1");
            }
            else
            {
                printf("0");
            }
        }

        printf("\n");
    }

    return 0;
}
Output
Enter number of rows: 5
Enter number of columns: 5
10101
10101
10101
10101
10101


Note: You can also print this pattern as rectangle number pattern just you need to change the number of rows or columns. Also you can print 1 for even rows and 0 for odd rows, for that just change printf("1"); to printf("0"); and vice versa.


Screenshot

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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment