Pattern Printing – String Characters
Print a pattern where each character of the input string is repeated on successive lines based on its position.
Understand the Problem
Problem Statement
Given a string S of length L, the program must print the pattern as described in the Example Input/Output.
Input Format:
First line contains the string S.
Output Format:
L lines containing the desired pattern.
Constraints
- 2 <= L <= 100
- String S contains only uppercase letters
- Output must consist of exactly L lines
Examples
ABCDA
BB
CCC
DDDDThe first character 'A' appears once on the first line, the second character 'B' appears twice on the second line, the third character 'C' appears three times on the third line, and the fourth character 'D' appears four times on the fourth line.
EAGLEE
AA
GGG
LLLL
EEEEEThe first character 'E' appears once on the first line, the second character 'A' appears twice on the second line, the third character 'G' appears three times on the third line, the fourth character 'L' appears four times on the fourth line, and the fifth character 'E' appears five times on the fifth line.
Solution
#include <stdio.h>
#include <string.h>
int main() {
char s[101];
fgets(s, sizeof(s), stdin);
// Remove newline if present
int len = strlen(s);
if (s[len-1] == '\n') {
s[len-1] = '\0';
len--;
}
for (int i = 0; i < len; i++) {
for (int j = 0; j <= i; j++) {
printf("%c", s[i]);
}
printf("\n");
}
return 0;
}The C solution reads the input string using fgets(), removes the trailing newline character, then uses nested loops. The outer loop iterates through each character position, and the inner loop prints the current character a number of times equal to its 1-based position.
For each character at index i, we print it (i+1) times, then move to the next line.