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

Write a C program to print the given number pattern of 1's and 0's at alternate rows using loop. How to print square number pattern of one and zero with one at odd row and zero at even row using loop in C programming. Logic to print number pattern of 1 and 0 with alternate rows.

Example:
Input rows: 5
Input columns: 5
Output:
11111
00000
11111
00000
11111

Required knowledge

Basic C programming, Loop

Logic to print 1, 0 at alternate rows

Printing this pattern would be easy if you are acquainted with printing square or rectangle number pattern.

Now, if you look to the pattern carefully you will notice that 1's are printed for the odd rows and 0's for the even. Hence, if you are done with the previous number pattern you could easily get the logic of this. What we need to do is we only need to check whether the current row is even or odd before printing inside inner loop. If the current row is odd then print 1 otherwise 0.

Program to print number pattern of 1's and 0's at alternate rows

/**
 * C program to print number pattern of 1, 0 at even/odd rows
 */

#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 row is odd
            if(i%2 == 1)
            {
                printf("1");
            }
            else
            {
                printf("0");
            }
        }

        printf("\n");
    }

    return 0;
}


Output
Enter number of rows: 5
Enter number of columns: 5
11111
00000
11111
00000
11111

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 of 1, 0 at alternate rows" title=


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