Even number pattern 2 in C

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

Example:
Input N: 5
Output:

Required knowledge

Basic C programming , Loop

Logic to print the given even number pattern

To get the logic of the pattern have a close look on to the pattern. You can observe following things about the pattern.
  1. The pattern consists of total N rows (where N is the total number of rows to be printed).
  2. To make things little easier let's divide the pattern in two internal parts.
  3. Loop formation to print the first part of the pattern will be for(j=2; j<=i*2; i+=2).
  4. Loop formation to print the second part of the pattern will be for(j=(i-1)*2; j>=2; j-=2).
Let's combine the logic of both parts in single program.

Program to print the given even number pattern

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

#include <stdio.h>

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

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

    for(i=1; i<=N; i++)
    {
        // Prints first part of the pattern
        for(j=2; j<=i*2; j+=2)
        {
            printf("%d", j);
        }

        // Prints second part of the pattern
        for(j=(i-1)*2; j>=2; j-=2)
        {
            printf("%d", j);
        }

        printf("\n");
    }

    return 0;
}


Output
Enter rows: 5
2
242
24642
2468642
2468108642


Screenshot

Number pattern in C


Once you get the logic of above pattern you can easily print the second pattern. You just need to add extra space before printing the numbers.

Program to print the above pattern

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

#include <stdio.h>

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

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

    for(i=1; i<=N; i++)
    {
        // Prints space
        for(j=i; j<N; j++)
        {
            printf(" ");
        }

        // Prints first part of the pattern
        for(j=2; j<=i*2; j+=2)
        {
            printf("%d", j);
        }

        // Prints second part of the pattern
        for(j=(i-1)*2; j>=2; j-=2)
        {
            printf("%d", j);
        }

        printf("\n");
    }

    return 0;
}


Screenshot

Number pattern in C


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