printing a pattern

for an assignment i have to use nested for loops to print this:
*
***
*****
*******
*********
***********
*************

this is the code i have:
#include<iostream>
using namespace std;
int main()
{
for(int i=1; i<=7; i++)
{
for(int j=1; i<=13; i++)
{
if (j>=i&&j>=10-i)
cout<<static_cast<char>(6);
else
cout<<" ";
}
cout<<endl;
}
return 0;
}

note:the symbol is supposed to be a spade,but i used a star for example.
the code isnt close to right,any help is appreciated.
There are 7 lines of output. So I understand your outer for loop.
On the 1st line of output there is 1 star. On the 2nd there are 3. On the 3rd there are 5. So it seems like the Nth line of output contains 2N - 1 stars. You just need to change the terminating condition on your inner for loop and get rid of the if() check.

Im still having trouble with this code

the new code with the recent suggestion:
#include<iostream>
using namespace std;
int main()
{
for(int i=1; i<=7; i++)
{
for(int j=1; j<=13; j++)
{
if (j<=i&&j>=2i-1)
cout<<static_cast<char>(6);
else
cout<<" ";
}
cout<<endl;
}
return 0;
}

any help is still appreciated
Last edited on
Hint: your inner for loop's terminating condition should be a function of i.

The purpose of your inner for loop is to print some number of stars on a line.
The number of stars it needs to print is 2N - 1, where N is the line number.
In your code, i is the line number.

Change the body of your innermost for loop to

 
cout << "*";


am i any closer with this:
#include<iostream>
using namespace std;
int main()
{
for(int i=1; i<=7; i++)
{
for(int j=1; j<=13; 2i-1)
{
if (j>=i&&j<=1)
cout<<static_cast<char>(6);
else
cout<<" ";
}
cout<<endl;
}
return 0;
}


note:im supposed to print out a pyramid of spades its just that i used * for the purpose of illustarting the pyramid
Somewhat. the 2i-1 is the terminating condition on the for loop, not the increment.

 
for( int j = 1; j <= 2 * i - 1; ++j )


Try that. And you need to get rid of the if-else statement and replace it with what I suggested above (you can replace the * with static_cast<char>(6) to get your spade).
Last edited on
ok,changed the code again:
#include<iostream>
using namespace std;
int main()
{
for(int i=1; i<=7; i++)
{
for(int j=1; j<=2*i-1; ++j)
{
cout<<static_cast<char>(6);
}
cout<<endl;
}
return 0;
}

but i still get just a solid row of 13 spades.anybody know what im doing wrong.
nevermind,i got it
...
Topic archived. No new replies allowed.