asterisk patterns

my code is working but I cannot make it function the right way, my program should display the following pattern, given the value of n and m. example if n=5, and m=6,
the output should be:
*****
*___*
*___*
*___*
*___*
*****

but my wrong code outputs this:
*****
*
*
*
*
*
*
*
*
*
*
*
*
******

please help me to correct my code,
this is my wrong code


#include <iostream.h>
#include <conio.h>

int main()
{
int m,n,o;

cout<<"entr #";
cin>>n;
cout<<"entr #";
cin>>m;
for (n=1;n<=m;++n)
{cout<<"*";
}
for (m=2;m<=n;++m)
{
cout<<"\n";
cout<<"*";
}
for (n=2;n<=m;++n)
{cout<<"\n";
cout<<"*";}
for (m=3;m<=n;++m)
{cout<<"*";
}
getch();
}


please help me, thanks in advance.
Last edited on
Please use [code][/code] tags for code. Makes it so much easier to read. I'm also going to assume those underscores are supposed to be spaces (to output fixed-width font with spaces you can use the [tt[i][/i]][/tt] tags)

Anyway your biggest problem seems to be that you're using 'n' and 'm' for loop counters when they're really supposed to be the size of the box you're drawing. Your first loop:

1
2
3
for (n=1;n<=m;++n)
{cout<<"*";
}


This throws away whatever the user input as 'n' and replaces it with n=1 (which it then counts up, and by the time that loop is finished... n=m+1). You then throw away the value of 'm' in the next loop. Use another variable for a loop counter.

You also have logic errors:

1
2
3
4
5
for (m=2;m<=n;++m)
{
cout<<"\n";
cout<<"*";
}


This will output only one asterisk before going to a new line, which is not a desired result unless n=1.

It looks like you're trying to draw lines around the box. Like you're trying to draw the top, left, right, then bottom lines of the box. You can't really do this -- what you need to do is output full rows at one time. So if you need to output [tt]* *[/tt] (with 3 spaces... n=5) on one of the rows, then you'll need to output this row in full before outputting another row. And you'll need to include those spaces in your output).

Try approaching this one row at a time. It might help to output a solid box first:

****
****
****
****

Then move on to making the desired hollow box once you get a firmer understanding of the idea.
Topic archived. No new replies allowed.