Diamond with Plus Pattern
Print a diamond pattern formed by asterisks and plus pattern, surrounded by hyphens as empty spaces
Understand the Problem
Problem Statement
The program must accept an integer N as the input. The program must print (2*N)-1 lines of pattern as shown in the Example Input/Output section. The asterisks in the pattern indicate the diamond and plus symbols. The hyphens in the pattern indicate the empty spaces.
Constraints
- 2 ≤ N ≤ 50
- Pattern consists of exactly (2*N)-1 lines
- Each line contains only asterisks (*) and hyphens (-)
Examples
5--------*
------*-*-*
----*---*---*
--*-----*-----*
*-*-*-*-*-*-*-*-*
--*-----*-----*
----*---*---*
------*-*-*
--------*For N=5, the pattern has 9 lines. The middle line (5th) contains 17 characters with alternating '*' and '-' starting with '*'. The upper and lower halves form a diamond shape with asterisks at the edges and center column.
3----*
--*-*-*
*-*-*-*-*
--*-*-*
----*For N=3, the pattern has 5 lines. The middle line has 9 characters with alternating '*' and '-' pattern. The diamond shape is smaller but follows the same logic.
6----------*
--------*-*-*
------*---*---*
----*-----*-----*
--*-------*-------*
*-*-*-*-*-*-*-*-*-*-*
--*-------*-------*
----*-----*-----*
------*---*---*
--------*-*-*
----------*For N=6, the pattern has 11 lines. The middle line has 21 characters with the full horizontal bar pattern. The diamond extends further with more spacing between asterisks in the upper and lower halves.
Solution
#include <stdio.h>
int main() {
int N;
scanf("%d", &N);
// Upper half including middle line
for (int i = 0; i < N; i++) {
// Print leading hyphens
for (int j = 0; j < 2 * (N - 1 - i); j++) {
printf("-");
}
if (i == N - 1) {
// Middle line: horizontal bar of plus
for (int k = 0; k < 2 * N - 1; k++) {
printf("*");
if (k < 2 * N - 2) printf("-");
}
} else {
// Diamond pattern with vertical bar
printf("*");
// Left inner part
for (int j = 0; j < 2 * i - 1; j++) {
printf("-");
}
if (i > 0) printf("*");
// Right inner part
for (int j = 0; j < 2 * i - 1; j++) {
printf("-");
}
if (i > 0) printf("*");
}
printf("\n");
}
// Lower half
for (int i = N - 2; i >= 0; i--) {
// Print leading hyphens
for (int j = 0; j < 2 * (N - 1 - i); j++) {
printf("-");
}
if (i == 0) {
printf("*");
} else {
printf("*");
// Left inner part
for (int j = 0; j < 2 * i - 1; j++) {
printf("-");
}
printf("*");
// Right inner part
for (int j = 0; j < 2 * i - 1; j++) {
printf("-");
}
printf("*");
}
printf("\n");
}
return 0;
}The C solution follows the same logic as described in the approach. It uses nested loops to:
- Print leading hyphens for each line
- Handle the middle line specially with the horizontal bar pattern
- Print the diamond pattern for other lines with vertical bar
- Mirror the upper half for the lower half
The key is managing the spacing correctly with the formula 2*(N-1-i) for leading hyphens and 2*i-1 for inner hyphens.