Take the number of rows and columns as input from the user ( length and breadth of the rectangle) and store it in two different variables. (‘r’ and ‘c’ in this case)
Run a loop ‘r’ number of times to iterate through all the rows. From i=0 to i<r. The loop should be structured as for(i=0 ; i<r ; i++)
Run a nested loop ‘c’ times to iterate though each column of a row. From j=0 to j<c. The loop should be structured as for(j=0 ; j<c ; j++).
Inside the nested loop print star if i=0 or i=r-1 or j=0 or j=c-1.
Else print a white-space.
Inside the main loop print a newline to move to the next line.
CODE IN C:
#include<stdio.h>
int main()
{
int i,j,r,c; //declaring integers i,j for loops and r,c for number of rows and columns
printf("Enter the number of rows\n"); //asking user for number of rows
scanf("%d",&r); //saving number of rows in a variable r
printf("Enter the number of columns\n"); //asking user for number of columns
scanf("%d",&c); //saving number of columns in a variable c
for(i=0;i<r;i++) //outer loop for number of rows
{
for(j=0;j<c;j++) //inner loop for number of columns
{
if(i==0 || i==r-1 || j==0 || j==c-1) //conditions for printing stars in a given column
{
printf("*"); //printing stars
}
else //else condition to print whitespace
{
printf(" "); //printing whitespace
}
}
printf("\n"); //printing newline after a row
}
}
Login/Signup to comment