Reputation: 41
I am quite new to programming and I have got an assignment which I cannot move with.
So the program must take the user input, the length and width of a rectangle and then draw the rectangle using stars *
based on the parameters length and width. I have to do it using for
loops, more precisely one for
loop inside the other.
It does not work and I am stuck with it, so please if someone would be so kind to help me, I would be thankful.
Here is what I got:
int main() {
printf("\n\n***Rectangle***");
printf("\n\n\nInsert side a: ");
scanf("%f", &sideA);
printf("\n\nInsert side b: ");
scanf("%f", &sideB);
printf("\n\nRectangle: \n\n");
for (int i = 0; i < sideA; i++) {
for (int j = 0; j < sideB; j++) {
if (i == 0 || i == sideB - 1 || j == 0 || j == sideA - 1) {
printf("*");
} else {
printf(" ");
}
printf("\n");
}
}
}
Thanks so much in advance
Upvotes: 2
Views: 2346
Reputation: 144969
There are multiple problems:
<stdio.h>
sideA
and sideB
should be defined as int
.scanf("%f", &sideA);
should be scanf("%d", &sideA);
and the same for sideB
. Furthermore, you should test for input failure: scanf()
returns the number of successful conversions, which must be 1
in this case.i
should be compared to sizeA
and j
to sizeB
.Here is a corrected version:
#include <stdio.h>
int main() {
int sideA, sideB;
printf("\n\n***Rectangle***");
printf("\n\n\nInsert side a: ");
if (scanf("%d", &sideA) != 1)
return 1;
printf("\n\nInsert side b: ");
if (scanf("%d", &sideB) != 1)
return 1;
printf("\n\nRectangle: \n\n");
for (int i = 0; i < sideA; i++) {
for (int j = 0; j < sideB; j++) {
if (i == 0 || i == sideA - 1 || j == 0 || j == sideB - 1) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
Upvotes: 2
Reputation: 93554
You have two problems with this code:
i
and j
the wrong way around in your '*' test.Move the newline to the outer loop, swap 'i' and 'j' in the if
condition:
for (int i = 0; i < sideA; i++)
{
for (int j = 0; j < sideB; j++)
{
if (j == 0 || j == sideB - 1 || i == 0 || i == sideA - 1 ) // MODIFIED
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n"); // MOVED
}
Alternatively be "less clever" and break it down thus:
width
asterisks ('*'
) followed by newline.length - 2
lines starting '*'
, followed by width - 2
spaces, then '*' + newline.Upvotes: 0