Table of contents
1.
Introduction
2.
What is Common in Number Pattern Programs?
3.
What are various Number Pattern Programs in C?
3.1.
Half Pyramid of Numbers
3.2.
Inverted Half Pyramid
3.3.
Full Pyramid
3.4.
Pascal’s Triangle
3.5.
Floyd's Triangle
3.6.
Diamond Pattern
3.7.
Cross Pattern
3.8.
Binary Square Pattern
3.9.
Diamond Number Pattern
4.
Frequently Asked Questions
4.1.
In C, why do we employ conditional statements?
4.2.
How can I prevent getting trapped in an endless loop?
4.3.
What is a ternary operator in C?
5.
Conclusion
Last Updated: Nov 24, 2024
Easy

Number pattern programs in C

Author Nidhi Kumari
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Number pattern programs are important concepts in programming that help in understanding loops and nested loops. These programs are commonly used to build logic and enhance problem-solving skills. However, for beginners, they might seem complex to implement. Therefore, it is important to learn and practice them to gain confidence in coding.

Introduction to Number Pattern programs in C

In this article, we will explore various number pattern programs in C by discussing their structure, logic, and implementation. We will also provide examples to illustrate each pattern, ensuring clarity and better understanding. By the end, you will have a clear understanding of how to create number patterns and use them to improve your programming skills.

What is Common in Number Pattern Programs?

The common elements in Number Pattern Programs are Conditional Statements.  We can create patterns by combining Number Patterns with conditional loops and syntax.

Let's look closely at the pattern interpretation of number pattern programs in C.

The first and second groups of the C pattern programme are the conditions for loops and the print statement, respectively.

for(condition of the outer loop){
  for(condition of the inner loop){
    print(...);
  }
}
You can also try this code with Online C Compiler
Run Code

 

Consider the advice given below with a level of caution, as it may not fit every situation.

The loops' conditions can be created as follows:
 

  • If the number of elements in the rows grows, the outer loop will start at i = 1. Otherwise, it will start at i = row or i = n, where n can be any integer.
     
  • The inner loop will start at j = 1 if the elements in each row are growing. Otherwise, it will start at j = row, j = i, or j = n, where n can be any integer.

 

The above approach often works with patterns, but we should constantly cross-check the loop's conditions. In other words, to create a number pattern programs in C, consider the following points:
 

  • Developing number pattern programs in C is simple if you are familiar with loops like the for and while loops.
     
  • To display number pattern programs in C, most of the time, two nested loops are required.
     
  • The outer loop determines the number of rows, while the inner loop decides what will go in each row.

What are various Number Pattern Programs in C?

Let’s discuss the various Number Pattern Programs in C one by one.

Half Pyramid of Numbers

A half pyramid of numbers is a simple pattern made of numbers, where each row increases in numbers, starting from 1. The number of rows is decided by the user. 

Code

#include <stdio.h>
int main() 
{
   int n;
   //User Input
   printf("Enter the number of rows: ");
   scanf("%d",&n);
   
   for (int i = 1; i <= n; ++i) 
   {
        for (int j = 1; j <= i; ++j) 
        {
            printf("%d ", j);
        }
        printf("\n");
   }
   return 0;
}

You can also try this code with Online C Compiler
Run Code

 

Output

Enter the number of rows: 6
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
You can also try this code with Online C Compiler
Run Code


Explanation: 

This program prints a number pattern based on the number of rows entered by the user. Here's how it works:
 

  1. The program asks the user to input the number of rows they want in the pattern.
     
  2. It uses two loops:
    • The outer loop determines the number of rows.
       
    • The inner loop prints numbers from 1 up to the current row number.
       
  3. After printing the numbers for a row, it moves to the next line.

Inverted Half Pyramid

The inverted half pyramid is a simple yet interesting pattern. It is essentially the opposite of the regular half pyramid, where each row starts with the highest number and decreases as you move down the rows. In this case, the outer loop runs in reverse to print the pattern in an upside-down triangle shape.

Code

#include <stdio.h>
int main() 
{
   int n;
   // User Input
   printf("Enter the number of rows: ");
   scanf("%d", &n);
   
   //outer loop moving in the opposite direction
   for (int i = n; i >= 1; --i) 
   {
        for (int j = 1; j <= i; ++j) 
        {
            printf("%d ", j);
        }
        printf("\n");
   }
   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter the number of rows: 6
1 2 3 4 5 6 
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 
You can also try this code with Online C Compiler
Run Code

 

Explanation:

This program prints a reverse number pattern based on the number of rows entered by the user. 

  1. The user inputs the total number of rows (n).
     
  2. The outer loop starts from n and decreases with each iteration, determining the number of rows and the numbers to print in each row.
     
  3. The inner loop prints numbers from 1 up to the current value of the outer loop (i).
     
  4. After printing the numbers for a row, the program moves to the next line.

Full Pyramid

A Full Pyramid Pattern is visually similar to an equilateral triangle and is a combination of two patterns: the left half and the right half. It can be created using different symbols like stars, numbers, or alphabets. Here's an example of how to print the Full Pyramid pattern using numbers.

Full Pyramid

Code

#include<stdio.h>
int main() {
  int n;
  printf("Enter the number of rows: ");
  scanf("%d",&n);
  for (int i = 1; i <= n; i++) {
  
    //Pattern 1 starts here
    //first, we print all the blank spaces n-i times
    for (int j = 1; j <= n - i; j++) {
      printf("  ");
    }
    
    //The elements that can be seen in each pattern row and 
    // whose values range from i to 2*i-1 are then printed.
    for (int j = i; j < 2 * i; j++) {
      printf("%d ", j);
    }
    
    //Pattern 2 starts here
    //each row begins with 2*(i-1) and then decremented i - 1 times
    int k = 2 * (i - 1);
    for (int j = 1; j <= i - 1; j++) {
      printf("%d ", k--);
    }
    
   //after completing each row, we print a new line.
    printf("\n");
  }
  return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter the number of rows: 5
         1 
      2 3 2 
    3 4 5 4 3 
  4 5 6 7 6 5 4 
5 6 7 8 9 8 7 6 5 
You can also try this code with Online C Compiler
Run Code

 

Explanation:

This program prints a pyramid of numbers based on the number of rows you enter. 

  • Input: You are asked to enter the number of rows for the pyramid.
     
  • Outer Loop (Rows): The outer loop runs for each row, starting from 1 and going up to the number you entered.
     
  • Spaces: Before printing numbers, the program prints spaces to align the numbers in the shape of a pyramid. The number of spaces decreases as the rows go down.
     
  • Ascending Numbers: After spaces, the program prints numbers in increasing order, starting from the row number (i) to 2 * i - 1.
     
  • Descending Numbers: Then, it prints numbers in decreasing order, starting from 2 * (i - 1) and going down.
     
  • Next Line: After finishing one row, the program moves to the next row.
     

Here is another example of a Full pyramid number pattern program in C.

Code

#include<stdio.h>
int main() {
  int n;
  // User Input
  printf("Enter the number of rows: ");
  scanf("%d", & n);
  
  // Outer for loop runs n times (the number of rows to print)
  for (int i = 1; i <= n; i++) {
  
    // The number of spaces at the front will be n - i
    for (int j = n; j > i; j--) {
      printf(" ");
    }
    
    // Print the numbers in the current row from 1 to i
    for (int j = 1; j <= i; j++) {
      printf("%d ", j);
    }
    printf("\n");
  }
  return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter the number of rows: 5
    1 
   1 2 
  1 2 3 
 1 2 3 4 
1 2 3 4 5 
You can also try this code with Online C Compiler
Run Code

 

Explanation:

The program generates a right-aligned number pattern based on user input.

  • The user is prompted to enter the number of rows (n).
     
  • The outer loop runs from 1 to n, iterating over each row.
     
  • The first inner loop prints spaces (n - i) to create right alignment for the numbers.
     
  • The second inner loop prints numbers from 1 to the current row number (i).
     
  • A newline is added after each row to move to the next line.

Pascal’s Triangle

Binomial coefficients are arranged in a triangular form in Pascal's triangle. Each row is numbered from the left, starting with j = 0, with the top row having the number i =0 ( the 0th row). The unique element at the 0th row is 1. For the rest of the numbers, the sum of two numbers located in the previous row and precisely at the top of the current cell is used to get each number.

 

Pascal's Triangle

The formula of combinations, often known as "n choose k" or the number of combinations of k elements from n elements, is used to calculate each row element in a Pascal triangle. 

C(n, k)  = n! / (n-k) ! * k!

The following pattern appears if we are in row i and column j:

C(i,j) = i! / ( (i-j)! * j! )

Combinations of Pascal Triangle

Let's now try to get C(i,j) using C(i, j-1):

C(i, j)   = i! / ( (i-j)! * j! )

C(i, j-1) = i! / ( (i - j + 1)! * (j-1)! )

From the two expressions above, we can get the following expression.

C(i, j) = C(i, j-1) * (i - j + 1) / j

Formula Derivation

Therefore, in O(1) time, C(i, j) can be derived from C(i, j-1). As a result, we can maintain a variable whose value can be changed to show the pattern.

Code

#include<stdio.h>
int main()
{
    int n;
    printf("Enter the number of rows: ");
    scanf("%d",&n);
    for (int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n-i; j++)
        {
            printf("  ");
        }
        
        int C = 1; // used to represent C(i, i)
        for (int j = 1; j <= i; j++)
        {
            printf("%d   ", C);
            C = C * (i - j) / j;
            
        }
        printf("\n");
    }
    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter the number of rows: 6
          1   
        1   1   
      1   2   1   
    1   3   3   1   
  1   4   6   4   1   
1   5   10   10   5   1
You can also try this code with Online C Compiler
Run Code

 

Explanation:

This program prints Pascal's Triangle based on the number of rows you input.

  • Input: The user is asked to enter the number of rows for the triangle.
     
  • Outer Loop: It runs from row 1 to the number of rows entered.
     
  • Spaces: It prints spaces before numbers to align the triangle.
     
  • Pascal's Triangle: The program calculates each number using the formula C = C * (i - j) / j and prints the values for each row.
     
  • New Line: After each row, it moves to the next line to print the next row.

Floyd's Triangle

A right-angled triangle with consecutive natural numbers is called Floyd's triangle. The number in Floyd's triangle begins with 1 in the top left corner and fills the specified rows one at a time using the numbers.

Floyd's Triangle

The only tricky part of this pattern is keeping a separate variable(num) that may be updated and shown during each loop iteration.

Code

#include <stdio.h>
int main() 
{
   int n;
   printf("Enter the number of rows: ");
   scanf("%d", &n);
   int num = 1;
   for (int i = 1; i <= n; i++) 
   {
        for (int j = 1; j <= i; ++j) 
        {
            printf("%d ", num);
            ++num;
        }
        printf("\n");
   }
   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter the number of rows: 5
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
You can also try this code with Online C Compiler
Run Code

 

Explanation:

This program prints a right-angled triangle of numbers in increasing order.

  • Input: The user is prompted to enter the number of rows for the triangle.
     
  • Outer Loop (Rows): The outer loop runs from 1 to the number of rows entered.
     
  • Inner Loop (Numbers): In each row, the inner loop prints numbers starting from 1, increasing sequentially as the program progresses.
     
  • Number Update: After each number is printed, it is incremented by 1 to ensure the next number appears.
     
  • New Line: After each row is printed, the program moves to the next line to print the next row.

Diamond Pattern

The user can input the desired number of rows to print the Diamond pattern of numbers in the following Number pattern program in C.

Code

#include<stdio.h>
int main() {
  int n;
  printf("Enter the number of rows: ");
  scanf("%d", & n);
  
  for (int i = 1; i <= n; i++) {
  
    for (int j = i; j < n; j++) {
      printf(" ");
    }
    
    for (int k = 1; k < (i * 2); k++) {
      printf("%d", k);
    }
    
    printf("\n");
  }
  for (int i = 4; i >= 1; i--) {
  
    for (int j = n; j > i; j--) {
      printf(" ");
    }
    
    for (int k = 1; k < (i * 2); k++) {
      printf("%d", k);
    }
    printf("\n");
  }
  return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter the number of rows: 5
     1
   123
  12345
 1234567
123456789
 1234567
  12345
   123
    1
You can also try this code with Online C Compiler
Run Code

 

Explanation:

  • This program prints a diamond pattern with numbers.
     
  • Input: The user enters the number of rows for the top half of the diamond.

Top Half:

  • Prints spaces to create alignment.
  • Prints numbers starting from 1 up to 2*i - 1 for each row.

Bottom Half:

  • Prints spaces and numbers in reverse order to form the bottom half of the diamond.

Cross Pattern

The Cross Pattern is a C program that prints a cross shape using numbers. The user can input the desired number of rows to generate a dynamic pattern.

Code

#include<stdio.h>
int main()
{
    int i, j, num = 1;
    int m[7][7] = {0};
    for (i = 1; i <= 7; i++)
    {
        for (j = 1; j <= 7; j++)
            if (j == i || 8 - i == j)
                m[i - 1][j - 1] = num;
        if (i < 4)
            num++;
        else
            --num;
    }
    for (i = 0; i < 7; i++)
    {
        for (j = 0; j < 7; j++)
        {
            if (m[i][j] == 0)
                printf(" ");
            else
                printf("%d", m[i][j]);
        }
        printf("\n");
    }
    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

1     1
 2   2 
  3 3  
   4   
  3 3  
 2   2 
1     1
You can also try this code with Online C Compiler
Run Code

 

Explanation:

This program generates a number-based "X" pattern using a matrix.

  • Matrix Initialization: A 7x7 matrix (m) is initialized with zeros.
     
  • Filling the Matrix:
     
  • The i and j loops traverse the matrix.
     
  • Numbers are placed where the conditions j == i (diagonal from top-left) or 8 - i == j (diagonal from top-right) are met.
     
  • The number starts at 1, increases to 4 for the first half, and then decreases back to 1 for the second half.

Printing the Matrix:

  • If the matrix value is 0, a space is printed; otherwise, the number in the matrix is displayed.
     
  • Each row is printed on a new line, forming the "X" pattern.

Binary Square Pattern

The Binary Square Pattern is a simple C program that prints a rectangular grid where each row alternates between 1s and 0s. The pattern is based on whether the row index is odd or even. For odd rows, the program prints 1s, and for even rows, it prints 0s.

Code

#include <stdio.h>
int main()
{
    int rows, cols, i, j;
    /* Input rows and columns from user */
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    
    printf("Enter the number of columns: ");
    scanf("%d", &cols);

    for (i = 1; i <= rows; i++)
    {
        for (j = 1; j <= cols; j++)
        {
            // Print 1 if the current row is odd
            if (i % 2 == 1)
            {
                printf("1");
            }
            else
            {
                printf("0");
            }
        }

        printf("\n");
    }

    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter the number of rows: 5
Enter the number of columns: 5
11111
00000
11111
00000
11111
You can also try this code with Online C Compiler
Run Code

 

Explanation:

  • This program prints a matrix pattern with alternating rows of 1s and 0s based on the user input for rows and columns.
     
  • Input: The user is prompted to enter the number of rows and columns for the matrix.
     
  • Outer Loop: It iterates from 1 to the number of rows entered by the user.
     
  • Inner Loop: It runs for each column in the current row.
     
  • Odd Row: If the row number is odd, it prints 1 for all columns in that row.
     
  • Even Row: If the row number is even, it prints 0 for all columns in that row.
     
  • New Line: After printing all columns of a row, the program moves to the next line.

Diamond Number Pattern

The Diamond Number Pattern is a combination of multiple smaller patterns arranged in a diamond shape. This pattern involves a series of numbers, printed in a way that creates a diamond-like appearance. It can be achieved by using a mix of loops to print spaces and numbers.

Diamond Number Pattern

Code

#include <stdio.h>
int main()
{
    int i, j, n;

    printf("Enter the value of n: ");
    scanf("%d", &n);

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

        printf("\n");
    }

    // Print second(lower) part of the pattern
    for (i = n - 1; i >= 1; i--)
    {
        for (j = 1; j <= i; j++)
        {
            printf("%d", j);
        }
        printf("\n");
    }

    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter the value of n: 5
1
12
123
1234
12345
1234
123
12
1
You can also try this code with Online C Compiler
Run Code

 

Explanation:

  • This program prints a number pyramid pattern with an ascending upper part and a descending lower part based on user input.
     
  • Input: The user is prompted to enter the value of n, which determines the number of rows for the upper and lower parts of the pattern.
     

Upper Part:

  • The outer loop runs from 1 to n to create rows.
     
  • The inner loop prints numbers starting from 1 up to the current row number (i).
     

Lower Part:

  • The outer loop runs from n-1 to 1 to create rows.
     
  • The inner loop prints numbers starting from 1 up to the current row number (i).
     
  • New Line: After completing the numbers for each row, the program moves to the next line.

Frequently Asked Questions

In C, why do we employ conditional statements?

In C programming, conditional statements are employed to make decisions based on the conditions. When no condition encloses the statements, conditional statements are executed sequentially. The execution flow may vary if a condition is added to a block of statements depending on the outcome of the condition's analysis.

How can I prevent getting trapped in an endless loop?

Ensure that the loop has at least one instruction that updates the comparison variable's value. (That is, the variable you employ in the condition statement of the loop.) Also, Never rely on the user to determine the terminating condition.

What is a ternary operator in C?

A ternary operator is a shorthand way of writing if-else statements. It takes three operands (one of its kind). The syntax of the ternary operator is: 

Val = condition? expr1: expr2

 

If the condition is trueVal = expr1, else Val = expr2.

Conclusion

We discussed some critical number pattern programs in C. Developing a number pattern program in C is simple if you are familiar with loops like the for and while loops. To display a number pattern program in C, at least two nested loops are required.

We hope this blog has helped you. We recommend you visit our articles on different topics of C language, such as

 C vs C++.

           Getch in C

 Header Files.

 Identifiers and Keywords.

Ternary Operator in C

If you liked our article, do upvote our article and help other ninjas grow.  You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!!

Happy Reading!!

Live masterclass