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();
}
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:
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.
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.
Bookmarks