In this article, we will show how to write a C program to print the rectangle star pattern with an X shape inside it 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 X shape inside the rectangle star pattern.
#include <stdio.h>
int main()
{
int rows;
printf("Enter Rows = ");
scanf("%d",&rows);
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || i + j == rows - 1)
{
if (i + j == rows - 1)
{
printf("/");
}
else
{
printf("\\");
}
}
else
{
printf("*");
}
}
printf("\n");
}
return 0;
}
Enter Rows = 13
\***********/
*\*********/*
**\*******/**
***\*****/***
****\***/****
*****\*/*****
******/******
*****/*\*****
****/***\****
***/*****\***
**/*******\**
*/*********\*
/***********\
Instead of a for loop, this program uses a while loop to iterate the rectangle rows and columns and prints the numbers in every row of a rectangle pattern except the diagonal (X) shape. For more star 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 || i + j == rows - 1)
{
if (i + j == rows - 1)
{
printf("/");
}
else
{
printf("\\");
}
}
else
{
printf("*");
}
j++;
}
i++;
printf("\n");
}
return 0;
}
Enter Rows = 15
\*************/
*\***********/*
**\*********/**
***\*******/***
****\*****/****
*****\***/*****
******\*/******
*******/*******
******/*\******
*****/***\*****
****/*****\****
***/*******\***
**/*********\**
*/***********\*
/*************\
In this C program, we create an XshapeinRectangleStars function that accepts the user-entered rows and prints the rectangle star pattern with an X shape inside it.
#include <stdio.h>
void XshapeinRectangleStars(int rows)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
if (i == j || i + j == rows - 1)
{
if (i + j == rows - 1)
{
printf("/");
}
else
{
printf("\\");
}
}
else
{
printf("*");
}
}
printf("\n");
}
}
int main() {
int rows;
printf("Enter Rows = ");
scanf("%d", &rows);
XshapeinRectangleStars(rows);
return 0;
}