Click here to Skip to main content
15,444,824 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
I'm able to print all O in pyramid, but I don't know how to print X and O in it.

For example:

Input:
5


output:

    O
   OXO
  OXOXO
 OXOXOXO
OOOOOOOOO


What I have tried:

C++
#include 

int main() {
    int i,j,h ;
    scanf("%d",&h);

    for(i=1;i=h-(i-1)&& j<=h+(i-1))
                printf("O") ;
            else
                printf(" ") ;
        }
        printf("\n") ;

    }
        return 0;
}
Posted
Updated 1-Nov-21 6:59am
v2
Comments
CHill60 1-Nov-21 12:03pm    
There appears to be some code missing - where is the if to go with the else for example?
jeron1 1-Nov-21 12:06pm    
So the last line printed should not have the XOXO pattern?

You need a triple print output for the empty space. So a string " XO" may do the job when indexing from 0 to 2.

C++
print(int index) {
 switch( index ) {
 case 0:
  print(" ");
  break;
  // ...
}
}
 
Share this answer
 
Have a variable which you toggle from 'O' to 'X' each time you printf it: set it to 'O' at the start of each line, and make the last line a special case.

Hint: have a look at the C XOR instruction: C Bitwise Operators: AND, OR, XOR, Complement and Shift Operations[^] - there is a way to use that to toggle it.
 
Share this answer
 
Comments
Mike Hankey 1-Nov-21 12:43pm     CRLF
What about using the MOD (%) operator? Seems like just the ticket here!
OriginalGriff 1-Nov-21 12:50pm    
Use XOR and you need no test! :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900