In this article, we will show how to write a C program to print the alphabets in an X shape pattern using for loop, while loop, and functions. The below example allows the user to enter the total number of rows, and the nested for loop iterates them from start to end. Next, the program uses the If Else statement to print the X pattern of the alphabet.
#include <stdio.h>
int main()
{
int rows, a = 65;
printf("Enter Rows = ");
scanf("%d",&rows);
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
printf("%c", a + j);
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
Enter Rows = 15
A O
B N
C M
D L
E K
F J
G I
H
G I
F J
E K
D L
C M
B N
A O
Instead of a for loop, this program uses a while loop to iterate the X shape of rows and columns and prints the alphabet in an X pattern. For more Alphabet pattern examples, Click Here.
#include <stdio.h>
int main()
{
int i, j, rows, a = 65;
printf("Enter Rows = ");
scanf("%d",&rows);
i = 0 ;
while (i < rows)
{
j = 0;
while (j < rows )
{
if (i == j || j == rows - 1 - i)
{
printf("%c", a + j);
}
else
{
printf(" ");
}
j++;
}
printf("\n");
i++;
}
return 0;
}
Enter Rows = 13
A M
B L
C K
D J
E I
F H
G
F H
E I
D J
C K
B L
A M
In this C program, we create an AlphabetsXPattern function that accepts the user entered rows and prints the alphabet in an X pattern.
#include <stdio.h>
void AlphabetsXPattern(int rows)
{
int a = 65;
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
printf("%c", a + j);
}
else
{
printf(" ");
}
}
printf("\n");
}
}
int main()
{
int rows;
printf("Enter Rows = ");
scanf("%d",&rows);
AlphabetsXPattern(rows);
return 0;
}