Number Patterns
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
Input N: 5
Output
2 242 24642 2468642 2468108642
2
242
24642
2468642
2468108642
Required knowledge
Basic C programming , Loop
Logic to print the given even number pattern
2 242 24642 2468642 2468108642
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.
2 24 246 2468 246810
2
42
642
8642
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
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.
2
242
24642
2468642
2468108642
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;
}
