Home > Blockchain >  How to print a X with two letters inside a square
How to print a X with two letters inside a square

Time:02-10

I am trying to make the this shape but stuck at here. I tried with counters more than one but failed again.

P p p p p p Q
p P p p p Q q
p p P p Q q q
p p p Q q q q
p p Q q Q q q
p Q q q q Q q
Q q q q q q Q
int main()
{  
    int loopLimit = 7;
    int upperCharacter = 0;
    
    do {
        int loopCounter = 0;

        do {
            if (loopCounter == upperCharacter) std::cout << "P ";
            else std::cout << "p ";
            loopCounter = loopCounter   1;
        } while (loopCounter < loopLimit);

        upperCharacter = upperCharacter   1;
        loopLimit = loopLimit - 1;
        std::cout << "\n";
    } while (loopLimit > 0);
}

My code currently outputs:

P p p p p p p 
p P p p p p 
p p P p p 
p p p P 
p p p 
p p 
p 

CodePudding user response:

With How do I ask and answer homework questions? in mind,
I propose to try the following, in order to avoid that you program yourself into a corner.

Use two nested loops (I'd prefer for but if you are more confident with do while stay with that) to output a square of all the same letters. Do not change those loops afterwards.

Then use an if-else to select between two letters.
Then use an if-elseif-else to select between three.
Then four.

I believe the trick you are supposed to learn here is making conditions. Complex structures of interdependent loops is an alternative, but my guess is that it would make things harder for you.

I think a suitable sequence of letters to get right here would be:

  • p
  • Q on full first diagonal
  • q
  • P on full other diagonal, but check first diagonal afterwards
  • Q on the other half of the second diagonal

Note that getting the order of the conditions right is important, e.g. for the point of diagonal crossing.

CodePudding user response:

A pen and a paper solved this question.

Here's the solution:

for (int satirSayaci = 1; satirSayaci < 8; satirSayaci  ) {
        for (int karakterSayaci = 1; karakterSayaci < 8; karakterSayaci  )
        {
            if (karakterSayaci >= 8 - satirSayaci) {
                if (karakterSayaci == 8 - satirSayaci || karakterSayaci == satirSayaci) std::cout << "X ";
                else std::cout << "x ";
            } else {
                if (karakterSayaci == satirSayaci) std::cout << "P ";
                else std::cout << "p ";
            }
        }

        // Yeni bir satir yazdir
        std::cout << std::endl;
    }
  • Related