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
C Program for Reversed String Pattern
In C programming, a reversed string pattern is a way to display a string in a triangular format where each row contains characters in reverse order, and when the string runs out, asterisks (*) fill the remaining positions. This creates an interesting visual pattern that grows row by row.
Syntax
void printReversedPattern(char str[], int length);
Algorithm
The approach to create this pattern involves the following steps −
- Start from the first row and print increasing number of characters
- For each row, calculate the starting position using formula: k = ((i*(i+1))/2)-1
- Print characters in reverse order, filling with '*' when string ends
- Move to the next line after completing each row
Example 1: Simple String Pattern
Let's create a reversed pattern for a simple string "abcd" −
#include <stdio.h>
#include <string.h>
void printReversedPattern(char str[], int n) {
int i, j, k;
for(i = 1; i <= n; i++) {
k = ((i * (i - 1)) / 2) + i - 1;
for(j = 0; j < i; j++) {
if(k >= n) {
printf("* ");
} else {
printf("%c ", str[k]);
}
k--;
}
printf("<br>");
}
}
int main() {
char str[] = "abcd";
int length = strlen(str);
printf("Input: %s<br>", str);
printf("Pattern:<br>");
printReversedPattern(str, length);
return 0;
}
Input: abcd Pattern: a c b * * d * * * *
Example 2: Longer String Pattern
Here's an example with a longer string to better demonstrate the pattern −
#include <stdio.h>
#include <string.h>
void printReversedPattern(char str[], int n) {
int i, j, k;
for(i = 1; i <= n; i++) {
k = ((i * (i - 1)) / 2) + i - 1;
for(j = 0; j < i; j++) {
if(k >= n) {
printf("* ");
} else {
printf("%c ", str[k]);
}
k--;
}
printf("<br>");
}
}
int main() {
char str[] = "hello";
int length = strlen(str);
printf("String: %s<br>", str);
printf("Reversed Pattern:<br>");
printReversedPattern(str, length);
return 0;
}
String: hello Reversed Pattern: h e l l l e o * * h * * * * *
How It Works
The pattern works by calculating the position of each character using the triangular number formula. For each row i, we start from position k = ((i*(i-1))/2) + i - 1 and move backwards, printing characters or asterisks as needed.
Key Points
- Each row contains one more character than the previous row
- Characters are printed in reverse order within each row
- When string characters are exhausted, asterisks (*) fill remaining positions
- The pattern continues until all rows are complete
Conclusion
The reversed string pattern is an interesting way to display strings in a triangular format. By using mathematical formulas and loops, we can create visually appealing patterns that demonstrate string manipulation techniques in C programming.
