-
March 9th, 2009, 10:59 AM
#1
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.
-
March 9th, 2009, 11:32 AM
#2
Re: asterisk patterns
First, you need to use a different variable in the for loops (o looks usable, but I like to use i,j,k). Replace all the index variables in the for loop with o. Next, I've been told it's bad practice to use <= in for loops, so decrement the initialization expressions and replace the <= with <. Then try again. After these corrections, the first for loop should look something like this:
Code:
for(o=0;o<m;o++)
{
cout<<"*";
}
-
March 9th, 2009, 01:06 PM
#3
Re: asterisk patterns
Originally Posted by calc0000
Next, I've been told it's bad practice to use <= in for loops, so decrement the initialization expressions and replace the <= with <.
The reasoning here is that if you loop from 0 to n-1, specifying the end as "< n" makes clear two things: That n is the number of loops in total, and that the loop counter (if still valid) will have value n after the loop assuming no break statements are hit. It's just a way of making code slightly more self-documented.
-
March 9th, 2009, 01:09 PM
#4
Re: asterisk patterns
Originally Posted by Lindley
The reasoning here is that if you loop from 0 to n-1, specifying the end as "< n" makes clear two things: That n is the number of loops in total, and that the loop counter (if still valid) will have value n after the loop assuming no break statements are hit. It's just a way of making code slightly more self-documented.
Also, more times than not, you're looping over an array, and the array's upper bound is one less than its size.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|