In this tutorial, we will write various C pattern programs for String. Before that, you may go through the following topics in C.
C Pyramid String Pattern: 1
Enter the string: SIMPLE2CODE
Enter the no. of rows: 8
S
I M
P L E
2 C O D
E S I M P
L E 2 C O D
E S I M P L E
2 C O D E S I M
Source Code:
#include <stdio.h>
void main()
{
char str[20];
int rows, a = 0;
printf("Enter the string: ");
scanf("%[^\n]", str);
printf("Enter the no. of rows: ");
scanf("%d", &rows);
for (int i = 0; i <= rows - 1; i++)
{
for (int j = 0; j <= rows - i; j++)
printf(" ");
for (int k = 0; k <= i; k++)
{
printf("%2c", str[a++]);
if (str[a] == '\0')
a = 0;
}
printf("\n"); // for new line
}
}
Mirrored half diamond string pattern in C: 2
Enter the string: SIMPLE2CODE
S
SI
SIM
SIMP
SIMPL
SIMPLE
SIMPLE2
SIMPLE2C
SIMPLE2CO
SIMPLE2COD
SIMPLE2CODE
IMPLE2CODE
MPLE2CODE
PLE2CODE
LE2CODE
E2CODE
2CODE
CODE
ODE
DE
E
Source Code:
#include <stdio.h>
void main()
{
char str[20];
int strLength;
printf("Enter the string: ");
scanf("%[^\n]", str);
// count the no. of characters
for (strLength = 0; str[strLength] != '\0'; strLength++);
// for first half
for (int i = 0; i < strLength; i++)
{
for (int j = 0; j < strLength - i - 1; j++)
printf(" "); // space
for (int j = 0; j <= i; j++)
printf("%c", str[j]);
printf("\n"); // for a new line
}
// for second half
for (int i = 1; i < strLength; i++)
{
for (int j = 0; j < i; j++)
printf(" "); // space
for (int j = i; j < strLength; j++)
printf("%c", str[j]);
printf("\n"); // for a new line
}
}
Half diamond string pattern in C: 3
Enter the string: SIMPLE
S
SI
SIM
SIMP
SIMPL
SIMPLE
IMPLE
MPLE
PLE
LE
E
Source Code:
#include <stdio.h>
void main()
{
char str[20];
int strLength;
printf("Enter the string: ");
scanf("%[^\n]", str);
// count the no. of characters
for (strLength = 0; str[strLength] != '\0'; strLength++);
// for first half
for (int i = 0; i < strLength; i++)
{
for (int j = 0; j <= i; j++)
printf("%c", str[j]);
printf("\n"); // for a new line
}
// for second half
for (int i = 1; i < strLength; i++)
{
for (int j = i; j < strLength; j++)
printf("%c", str[j]);
printf("\n"); // for a new line
}
}
Half diamond string pattern in C: 4
Enter a string: PROGRAM
P
PR
PRO
PROG
PROGR
PROGRA
PROGRAM
PROGRA
PROGR
PROG
PRO
PR
P
Source Code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
char str[20];
int len, place;
printf("Enter a string: ");
scanf("%[^\n]", str);
// find the length of the string
for (len = 0; str[len] != '\0'; len++);
len--;
for (int i = 0; i < (2 *len + 1); i++)
{
if (i < len) place = i;
else place = abs(2 *len - i);
for (int j = 0; j <= place; j++)
printf("%c", str[j]);
printf("\n");
}
}
Half Pyramid String Pattern in C: 5
Enter a string: PROGRAM
P
PR
PRO
PROG
PROGR
PROGRA
PROGRAM
Source Code:
#include <stdio.h>
void main()
{
char str[20];
printf("Enter a string: ");
scanf("%[^\n]", str);
for (int i = 0; str[i] != '\0'; i++)
{
for (int j = 0; j <= i; j++)
printf("%c", str[j]);
printf("\n"); // new line
}
}