Decreasing String in Center – Pattern
Print a pattern where a string is displayed with characters removed from the center in each subsequent line, replaced by asterisks.
Understand the Problem
Problem Statement
A string S is passed as the input to the program. The program must print the pattern as shown in the Example Input/Output sections.
Note: The length of the string is always even.
Constraints
- 1 <= Length of the string <= 100
- String contains only lowercase letters
- String length is always even
Examples
barberbarber
*baer*
**br**
******Starting with 'barber', we remove 1 character from each side of the center in each step: 'barber' → '*baer*' (removed 'r' and 'b') → '**br**' (removed 'a' and 'e') → '******' (removed 'b' and 'r').
databasedatabase
*datase*
**dase**
***de***
********Starting with 'database', we remove characters from the center progressively: 'database' → '*datase*' (removed 't' and 'a') → '**dase**' (removed 'a' and 's') → '***de***' (removed 'd' and 'a') → '********' (removed 'a' and 't').
Solution
#include <stdio.h>
#include <string.h>
void printAsterisks(int count) {
for (int i = 0; i < count; i++) {
printf("*");
}
}
int main() {
char str[101];
fgets(str, sizeof(str), stdin);
int len = strlen(str);
if (str[len-1] == '\n') {
str[len-1] = '\0';
len--;
}
int half = len / 2;
for (int i = 0; i <= half; i++) {
// Print leading asterisks
printAsterisks(i);
// Print left portion (first half-i characters)
for (int j = 0; j < half - i; j++) {
printf("%c", str[j]);
}
// Print right portion (last half-i characters)
for (int j = len - (half - i); j < len; j++) {
printf("%c", str[j]);
}
// Print trailing asterisks
printAsterisks(i);
printf("\n");
}
return 0;
}The C solution uses a function printAsterisks to handle asterisk printing. The main logic:
- Read the input string and calculate its length
- For each iteration i from 0 to half the string length:
- Print i leading asterisks
- Print the first (half-i) characters from the left side
- Print the last (half-i) characters from the right side
- Print i trailing asterisks
- Move to next line