In this article, we will show how to write a C program to print the numbers in an X pattern or shape 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 will print the number pattern in an X shape.
#include <stdio.h>
int main()
{
int rows, i, j;
printf("Enter Rows = ");
scanf("%d",&rows);
for (i = 0 ; i < rows; i++ )
{
for (j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
printf("%d ", j + 1);
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
Enter Rows = 12
1 12
2 11
3 10
4 9
5 8
6 7
6 7
5 8
4 9
3 10
2 11
1 12
Instead of a for loop, this program uses a while loop to iterate the X shape of rows and columns and prints the numbers in every row of a pattern. For more number programs, click here.
#include <stdio.h>
int main()
{
int rows, i, j;
printf("Enter Rows = ");
scanf("%d",&rows);
i = 0;
while (i < rows )
{
j = 0;
while (j < rows )
{
if (i == j || j == rows - 1 - i)
{
printf("%d", j + 1);
}
else
{
printf(" ");
}
j++;
}
printf("\n");
i++;
}
return 0;
}
Enter Rows = 15
1 15
2 14
3 13
4 12
5 11
6 10
7 9
8
7 9
6 10
5 11
4 12
3 13
2 14
1 15
In this C program, we create a NumbersinXShape function that accepts the user entered rows and prints the numbers pattern in an alphabet X shape.
#include <stdio.h>
void NumbersinXShape(int rows)
{
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
printf("%d ", j + 1);
}
else
{
printf(" ");
}
}
printf("\n");
}
}
int main()
{
int rows;
printf("Enter Rows = ");
scanf("%d",&rows);
NumbersinXShape(rows);
return 0;
}