C Program to print Pattern 9 2 4 6 8 10 12
Objective
Write a C program to print a triangle of sequential even numbers.
Algorithm / Approach
- Declare an independent counter
k = 1. - Run an outer loop
ifrom 1 ton. - Run an inner loop
jfrom 1 toi. - Print
2 * kand then incrementk. - Print a newline.
main.c
#include<stdio.h>
int main( ) {
int i, j,n,k=1;
printf("Enter the Number of row : ");
scanf("%d",&n);
for(i=1; i<=n; i++) {
for(j=1; j<=i; j++) {
printf("%d",2*k);
k++;
}
}
return 0;
}
Expected Output
2 4 6 8 10 12
Explanation of the Program
- This is a variation of Floyd's Triangle. Instead of printing the natural numbers (1, 2, 3), we want the even numbers (2, 4, 6).
- By maintaining our independent counter
kand simply multiplying it by 2 right before we print it, we easily generate a continuous stream of even numbers.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)