C Help - Nested Loops

Associate
Joined
14 Jun 2009
Posts
1,568
Hi,

I'm new to C and struggling quite a bit with the following.

I need to draw the following:
yZwBV.jpg

I've managed to draw a 5 x 4 grid of *'s using the following:

PHP:
#include <stdio.h>
int main(void)
{
  int row;
  for (row = 0 ; row < 4 ; row++)
    {
      int column;
      for (column = 0 ; column < 5 ; column++)
	{
	  printf("*");
	}
      printf("\n");
    }
  return 0;
}

I know I almost certainly need another nested loop somewhere but I really have no idea where to start if i'm honest :(

Any help is appreciated.
 
You don't need another loop. You could change the printf("*") line to include an if, and only print a "*" if it's one of the edges (i.e. col is 0 or 4 or row is 0 or 3), and print a space otherwise.
 
+1 Swanster.

Please indent your braces for your second for loop o.O

Had a go:

please bare in mind I've never used C, only C# and C++, so if my syntax is incorrect, apologies.

Code:
#include <stdio.h> 
int main(void) 
{ 
	int row; 
	for (row = 0 ; row < 4 ; row++) 
	{ 
		int column; 
		for (column = 0 ; column < 5 ; column++) 
		{ 
			if (row == 1 || row == 2)
			{
				if(column == 1 || column == 2 || column == 3)
				{
					printf(" ");
				}
				else
				{
					printf("*");
				}
			}
			else
			{
			printf("*"); 
			}
		} 
	printf("\n"); 
	} 
return 0; 
}

Could have used < and > on the second if, but cba to change it now.
 
Last edited:
Back
Top Bottom