Number pattern 13 in C

Write a C program to print the given number pattern using for loop. How to print the given number pattern of m rows n columns using for loop in C programming. Logic to print the given number pattern using for loop in C program.

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

Required knowledge

Basic C programming, Loop

Logic to print the given number pattern

Before discussing about this pattern you must get acquainted with the basics of printing number pattern.

Once you get acquainted with the basics of logic of printing number pattern. Look to the pattern carefully and you will notice that for all odd rows n odd numbers are printed and for even rows n even numbers are printed (Where n is the number of columns to be printed). Here in this program we will use an extra variable to print numbers in each column.

Program to print the given number pattern

/**
 * C program to print number pattern
 */

#include <stdio.h>

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

    /*
     * Reads number of rows, columns to be printed
     */
    printf("Enter number of rows: ");
    scanf("%d", &rows);
    printf("Enter number of columns: ");
    scanf("%d", &cols);

    k=1;

    for(i=1; i<=rows; i++)
    {
        //If current row is even the start with even number
        if(i%2 == 0)
            k = 2;
        else
            k = 1;

        for(j=1; j<=cols; j++)
        {
            printf("%-3d", k);

            k += 2;
        }

        printf("\n");
    }

    return 0;
}


Note: In the printf("%-3d", k); %-3d is used to print an integer with 3 characters wide.


Output
Enter number of rows: 5
Enter number of columns: 5
1 3 5 7 9
2 4 6 8 10
1 3 5 7 9
2 4 6 8 10
1 3 5 7 9


C program to print number pattern


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