Reputation: 51
The user inputs length and height and the program should draw a rectangle with those characteristics and empty in the middle. The problem is that the program prints out a side longer than the other. (Note: the "x" is just a symbol that I used for drawing the rectangle, not a variable.)
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float lenght,height,i,j;
printf("insert lenght:\n");
scanf("%f",&lenght);
printf("insert height:\n");
scanf("%f",& height);
for (i=0; i<lenght; i++) //upper lenght
{
printf("x");
}
for (i=0; i<height; i++) //height
{
printf("x\n");
for (j=0; j<lenght; j++) //space
{
printf(" ");
}
printf("x\n");
}
for (j=0; j<=lenght; j++) //lower lenght
{
printf("x");
}
return 0;
}
Upvotes: 0
Views: 129
Reputation: 7726
The perfect and reliable way to do it (notice comments):
#include <stdio.h>
int main(void) {
int rows, columns;
printf("Input total rows and columns: ");
if (scanf("%d%d", &rows, &columns) != 2) {
// If the 'rows' and/or 'columns' are entered incorrectly
printf("Please input the values correctly!\n");
return 1;
}
// Iteration till 'rows'
for (int i = 1; i <= rows; i++) {
// Iteration till 'columns'
for (int j = 1; j <= columns; j++)
// Meanwhile, if 'i' is the first iteration or last iteration relative to 'rows'
// it will print an asterisk and similarly with 'j', otherwise, a space
if (i == 1 || i == rows || j == 1 || j == columns)
printf("*");
else
printf(" ");
// Will go to the next line on each iteration
printf("\n");
}
return 0;
}
A sample test case:
Input total rows and columns: 5 10
**********
* *
* *
* *
**********
Input total rows and columns: 10 10
**********
* *
* *
* *
* *
* *
* *
* *
* *
**********
Upvotes: 1