0

I am looking for a c++ or c# code for a pyramid scheme (i level: x, second level x x...and so on). thx

2
  • Try writing some code and see what happens - you'll quickly get an idea of what information you need.
    – Skizz
    Jun 23, 2011 at 8:00
  • 7
    Aren't pyramid schemes illegal in most countries? Jun 23, 2011 at 8:21

2 Answers 2

4

Here is some pseudo-code that you can to translate into any imperative language of your choice:

for each i from 1 to max
    for each k from 1 to i
        print x
    newline
0

It sounds like you want this formatted a little bit. It also sounds like this is a high school, beginning of semester assignment, and you may be cheating yourself out of discovering whatever language you're using. But let's say you're not, and you want formatting.

FredOverflow gives the right pseudocode algo for printing:

x
xx
xxx
...

but if you want it to be centered then you need to consider how many spaces to add first.

If your pyramid is n tall, then the bottom is n wide. Row n-1 contains n-1 x's, but needs even spacing, and you can't just add 0.5 spaces to each side, at least with text (unless this is in a GUI and you're using some DrawText(x,y,text) method). Instead, consider that if you put a space between each x, you'll always have an odd # of characters on a line, allowing pyramidal spacing, like so:

  x
 x x
x x x

Thus you can do:

for (i = 1; i<= n; i++) {
  for (j = 0; j < n-i; j++) {
    printf(" ");
  }
  for (k = 0; k < i; i++) {
    printf("x ");
  }
  printf("\n");
}

Or rewrite to suit your needs / be more efficient. There are options here, and you should try doing it another way to see what the differences teach you. Specifically, though, pay attention to the math used in your recursion loops. It's easy, especially when starting out, to have off-by-1 math errors in loops. Heck, I hope I didn't make one just now!

Not the answer you're looking for? Browse other questions tagged or ask your own question.