Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program for Hexagonal Pattern
We are given with an integer 'n' and the task is to generate the hexagonal pattern and display the final output.
Syntax
void pattern(int n);
Example
Let's see the hexagonal pattern for n=5 and n=4 −
Input: n=5
Output:
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
*
Input: n=4
Output:
*
* *
* *
* *
* *
* *
* *
*
Approach
The approach we are using in the given program is as follows −
- Input the number 'n' from user
- Divide the entire pattern into three parts: upper part, middle part and lower part
- Start loop for printing the upper part of the pattern from i=0 to i<n
- Start loop for printing the middle part of the pattern from m=0 to m<(n-2)
- Start loop for printing the lower part of the pattern from h=(n-1) to h>=0
- Print '*' at appropriate positions with spaces
Example: Complete C Program
#include <stdio.h>
// Function to print hexagon pattern
void pattern(int n) {
int len = 2 * n - 1;
// Upper part of the pattern
for (int i = 0; i < n; i++) {
int temp = i + n;
for (int k = 0; k < temp; k++) {
if ((k == n + i - 1) || (k == n - i - 1))
printf("*");
else
printf(" ");
}
printf("<br>");
}
// Middle part of the pattern
for (int m = 0; m < n - 2; m++) {
for (int j = 0; j < len; j++) {
if (j == 0 || j == len - 1)
printf("*");
else
printf(" ");
}
printf("<br>");
}
// Lower part of the pattern
int res = n - 1;
for (int h = res; h >= 0; h--) {
int temp2 = h + n;
for (int k = 0; k < temp2; k++) {
if ((k == n + h - 1) || (k == n - h - 1))
printf("*");
else
printf(" ");
}
printf("<br>");
}
}
int main() {
int n = 5;
printf("Hexagonal pattern for n = %d:<br>", n);
pattern(n);
return 0;
}
Hexagonal pattern for n = 5:
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
*
How It Works
The hexagonal pattern is divided into three distinct parts −
- Upper Part: Creates the expanding top portion where stars move outward
- Middle Part: Creates the parallel sides of the hexagon
- Lower Part: Creates the contracting bottom portion where stars move inward
The algorithm calculates the exact positions where stars should be placed and fills other positions with spaces to maintain the hexagonal shape.
Conclusion
This C program successfully generates a hexagonal pattern by dividing it into three logical parts and using nested loops to position stars correctly. The pattern maintains proper spacing and symmetry for any given input value n.
Advertisements
