Reputation: 322
I want to create a hallow rectangle with a dynamic border, which means that if I input 3, then the border is going to be 3 columns thick. I've managed to do it with pre-given value, but I want the values to be inputted by the user.
#include <stdio.h>
int main()
{
int i, j, n, m;
printf("Rows: ");
scanf("%d", &n);
printf("Columns: ");
scanf("%d", &m);
for(i=1; i<=n; i++){
for(j=1; j<=m; j++){
if(i==1 || i==2 || i==3 || i==n-2 || i==n-1 || i==n || j==1 || j==2 || j== 3 || j==m-2 || j==m-1 || j==m){
printf("*");
}
else{
printf(" ");
}
}
printf("\n");
}
return 0;
}
Upvotes: 0
Views: 43
Reputation: 99144
Suppose you wanted to print a single row of 1000 spaces:
for(j=1; j<=1000; ++j){
printf(" ");
}
So far, so good. Now suppose you want the first three characters to be asterisks:
for(j=1; j<=1000; ++j){
if(j==1 || j==2 || j== 3){
printf("*");
}
else{
printf(" ");
}
}
That works. There are other ways, but that works.
Now suppose you want the first 200 characters to be asterisks:
for(j=1; j<=1000; ++j){
if(j==1 || j==2 || j== 3 || j==4 || ...
All right, this is clearly not the right approach. Good programmers dislike typing. Let's try one of the other ways:
for(j=1; j<=1000; ++j){
if(j<=200)
printf("*");
else
printf(" ");
That works. Here's another way, even better:
for(j=1; j<=200; ++j)
printf("*");
for(j=201; j<=1000; ++j)
printf(" ");
Now suppose you want the first 200 and last 200 characters to be asterisks:
for(j=1; j<=200; ++j)
printf("*");
for(j=201; j<=1000-200; ++j)
printf(" ");
for(j=1000-200+1; j<=1000; ++j)
printf("*");
That should be enough to show you how to rewrite your code for rectangular borders.
Upvotes: 1