Algorithm to generate a character diamond

Asked

Viewed 677 times

-2

I’m trying to make a C program to generate a diamond as exemplified in the image below:

Exemplo de resultado esperado

I couldn’t get an algorithm to generate the characters and spaces needed on each line.

What a reasonable way to solve this?

1 answer

5


I won’t give you the code, but I’ll give you an idea about the algorithm.

First, you will need to convert from letter to number, which I will call n, so that A is 0, B is 1, etc. I put A as 0 and not as 1 because I think it will be easier. This is important to be able to count how many lines and how many spaces you will need.

To do this, you use the ASCII table, where A is the number 65. Therefore, to make this conversion, simply subtract 65 from the chosen character.

Then we have to draw the diamond, line by line. We will divide the task into two, because we have the upper half and the lower half of the diamond. In the upper half we have n lines, and therefore use a loop for iterating from 0 to n is the best idea.

For each line, we also have two halves (and therefore two other loops for). The left half has n all these characters, with the exception of just one of them, will be blank spaces. To find the exception, suppose you are using as counter a variable called j, you would use n-j. The character to be printed is the opposite of the number conversion made from the j, then just use j+65 in it.

For the right half of the line, you iterate n-1 back-to-front times what you did in the left half.

Made the top half of the diamond, to make the bottom half you use a strategy similar to the right half of each row, repeats what is in the top half loop, but iterating n-1 back-to-front times.

  • My difficulty is only in knowing how many spaces to give on each line, for example: A - 2 spaces A 2 spaces B B - 1 spaces B 2 spaces B

  • @Luccasgabriel On the upper left, before the letter on the i-th line (counting from 0) are n-i spaces preceding the letter. If you iterate the right part of the line and the bottom part of the diamond backwards, it will already reflect automatically.

  • 3

    Thanks I managed following your logic after 1 hour kkkkkk

  • 2

    @Luccasgabriel, "... after 1 hour" - well played: 1 hour you will see that it was worth it!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.