Number pattern 35 in C

Write a C program to print the given number pattern using loop. How to print the given number pattern using for loop in C programming. Logic to print the given number pattern using loop in C program.

Input N: 5

Required knowledge

Basic C programming, If else, Loop

Logic to print the given number pattern

Logic to this pattern can be little tricky on first look. The pattern contains N rows (where N is the total number of rows to be printed). There are exactly i columns per row (where i is the current row number). Now, when you look to the pattern carefully you will find that the pattern contains odd and even columns.

If you don't know how to check even or odd, it is recommended that learn the logic of checking even or odd before continuing to this pattern.

When the row number is odd then the columns are odd, starting from first odd number and when it is even then the columns are even, starting from the first even number. For printing the numbers we will use an extra variable say k that will keep track of next number to be printed.

Step-by-step-descriptive logic:

  1. To iterate through rows, run an outer loop from 1 to N.
  2. Inside this loop initialize a variable k = 1 if the current row is odd otherwise k = 2.
  3. To iterate through columns, run an inner loop from 1 to i (where i is current row number).
    Inside this loop print the value of k and increment k = k + 2 to get the next even or odd number.

Program to print the given number pattern

 * C program to print number pattern

#include <stdio.h>

int main()
    int i, j, k, N;

    printf("Enter N: ");
    scanf("%d", &N);

    for(i=1; i<=N; i++)
        //Checking even or odd 
            k = 1;
            k = 2;

        //Logic to print numbers
        for(j=1; j<=i; j++, k+=2)
            printf("%d", k);


    return 0;

Enter N: 5


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