简体   繁体   中英

drawing a rectangle for user-defined dimensions using for lops, using extended ASCII characters

I did some part of it but can't seem to get the whole rectangle. Could someone point out what I'm doing wrong?

Here is my code:

printf("Enter the length and width of the rectangle : ");
scanf("%d%d",&length,&width);


printf("\n%c", 218);
for(i=1;i<=length;i++)
{
        printf("%c",196);

}

printf("%c",191);


 for(j=1;j<=width;j++)
 {
     printf("\n");
     printf("%c",179);
 }
    printf("\n");
    printf("%c", 192);

     for(i=1;i<=length;i++)
{
        printf("%c",196);

}

printf("%c", 217);

return 0;

My output

You are only printing the first column and not the second one. An approach would be to loop over the whole rectangle and check if you are at an edge or not.

#include <stdio.h>

int main()
{
    int length, width, i, j;

    printf("Enter the length and width of the rectangle : ");
    scanf("%d%d",&length, &width);

    for(i=0;i<width;i++)
    {
        for(j=0;j<length;j++)
        {
            if( j==0 || j==length-1 || i==0 || i==width-1 )
            {
                printf("%c", '*');
            }
            else
            {
                printf(" ");
            }
        }
        printf("\n");
    }

    return 0;
}

In your middle loop, you only print a single vertical bar before going to the next line.

You need to print the bar once, then add another loop to print the spaces, then print one more bar:

  for(j=1;j<=width;j++)
  {
     printf("\n");
     printf("%c",179);
     for (i=1;i<=length;i++) {
       printf(" ");
     }
     printf("%c",179);
  }
#include <stdio.h>
#include <stdlib.h>

int main()
{
int length, width,i,j;
   printf("Enter the length and width of the rectangle : ");
   scanf("%d%d",&length,&width);


printf("\n%c", 218);
for(i=1;i<=length;i++)
{
    printf("%c",196);

 }

   printf("%c",191);


    for(j=1;j<=width;j++)
 {
 printf("\n");
 printf("%c",179);
 for (i=1;i<=length;i++) {
   printf(" ");
 }
  printf("%c",179);
  }
    printf("\n");
    printf("%c", 192);

  for(i=1;i<=length;i++)
   { 
    printf("%c",196);

    }

 printf("%c", 217);

  return 0;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM