Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print Pattern 9 2 4 6 8 10 12

C Code Example — Pattern Programs

ADVERTISEMENT

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

  1. Declare an independent counter k = 1.
  2. Run an outer loop i from 1 to n.
  3. Run an inner loop j from 1 to i.
  4. Print 2 * k and then increment k.
  5. 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 k and 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)
ADVERTISEMENT