>However, this one of my attempt, please give some suggestion.
The usual pattern is a loop for the rows and two loops inside of it, one for the leading spaces and one for the triangle body:
for i = 0 to N
for j = 0 to nspace
print ' '
for j = 0 to nbody
print 'X'
From there it's simply a matter of getting the expressions right for calculating nspace and nbody.
Or you can just turn in something that will shut your teacher up, like this:
#include <iostream>
int main()
{
for ( int i = 0; i < 32; i++ ) {
for ( int j = 0; j <= i; j++ )
std::cout.put ( ~i & j ? ' ' : '1' );
std::cout.put ( '\n' );
}
}
;)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,483
Solved Threads: 1,407
Skill Endorsements: 54
>The one that troubled me is how to write the "x" after the blank spaces. How can I do it ?
That's actually the easier part. You just need a second loop that prints x's and increments by two with each row.
>Can you make the code so it can be executed in MinGw ?
Not really. The code is already conforming to the C++ standard, so unless you're doing something wrong (the most likely case) trying to execute it, tweaks would be necessary to handle implementation quirks. For example, on Dev-C++ I would have to change it to this to keep the execution window open and force cout to flush just for good measure:
#include <iostream>
int main()
{
for ( int i = 0; i < 32; i++ ) {
for ( int j = 0; j <= i; j++ )
std::cout.put ( ~i & j ? ' ' : '1' );
std::cout.put ( '\n' );
}
std::cin.get();
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,483
Solved Threads: 1,407
Skill Endorsements: 54
Example #1:
number of lines in pyramid = 3
line number 1 has 2 prefix spaces followed by 1 *
line number 2 has 1 prefix spaces followed by 3 *
line number 3 has 0 prefix spaces followed by 5 *
Example #2:
number of lines in pyramid = 4
line number 1 has 3 prefix spaces followed by 1 *
line number 2 has 2 prefix spaces followed by 3 *
line number 3 has 1 prefix spaces followed by 5 *
line number 4 has 0 prefix spaces followed by 7 *
Patterns established in examples:
1) line number increases from 1 to number of lines in pyramid
2) the number of spaces to print on each line is the number of lines in pyramid minus the line number
3) the number of * to print on each line is one less than the line number times 2
Pseudocode:
outer loop controls line number
inner loop #1 prints spaces
inner loop #2 prints *
Lerner
Nearly a Posting Maven
2,406 posts since Jul 2005
Reputation Points: 739
Solved Threads: 405
Skill Endorsements: 9
__avd
Posting Genius (adatapost)
8,736 posts since Oct 2008
Reputation Points: 2,141
Solved Threads: 1,262
Skill Endorsements: 50