-
nested for loops
I am working on a program that uses nested for loops to display a hollow rectangle from "*". The dimentions are to be specified by user
I cannot figure how to write the loop to make this retangle hollow. I can only make it solid. This program is for a mandatory class that is not related to my major and my patience is evapotating quickly. Please help if you can.
Thank you in advance, Ian
-
try this on for size...
Code:
#include <stdio.h>
int main(void)
{
int length, width, x, y;
printf("Enter length: ");
scanf("%d",&length);
printf("Enter width: ");
scanf("%d",&width);
for(x = 0; x < width; x++)
printf("*");
printf("\n");
for(x = 0; x< length; x++)
{
printf("*");
for(y = 0; y< (width-2); y++)
printf(" ");
printf("*");
printf("\n");
}
for(x = 0; x < width; x++)
printf("*");
return 0;
}
would you like me to explain it or an you figure it out?
-
Hi Ken,
Thank you for your prompt answer to my question. I wonder if you could explain the for loop a little. I think I understand it but I would like to know for sure. Thank you again
Ian
-
I'll add in comments where you'll probably want them...
Code:
#include <stdio.h>
int main(void)
{
int length, width, x, y;
printf("Enter length: ");
scanf("%d",&length);
printf("Enter width: ");
scanf("%d",&width);
/*print out the top row of stars*/
for(x = 0; x < width; x++)
printf("*");
/*go to the next line*/
printf("\n");
/*here's the fun part...*/
for(x = 0; x< length; x++)
{
/*go all the way down the line and print out both sides...first print out the leftmost character.*/
printf("*");
/*now print out spaces al the way to where the right column should be...*/
for(y = 0; y< (width-2); y++)
printf(" ");
/*...and print out a star in the right column*/
printf("*");
/*go to the next line*/
printf("\n");
}
/*print out the bottom row*/
for(x = 0; x < width; x++)
printf("*");
return 0;
}
That better?
-
Here, this way it comes out formatted better:
Code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(void)
{
int length, width, x, y;
printf("Enter length: ");
scanf("%d",&length);
printf("Enter width: ");
scanf("%d",&width);
system("cls");
for(x = 0; x < width; x++)
printf("* ");
printf("\n");
for(x = 0; x< length; x++)
{
printf("* ");
for(y = 0; y< (width-2); y++)
printf(" ");
printf("* ");
printf("\n");
}
for(x = 0; x < width; x++)
printf("* ");
printf("\n");
getch();
return 0;
}