jeudi 16 avril 2020

Can't wrap my head around Letter Pyramid problem

// Letter Pyramid
// Written by Frank J. Mitropoulos

#include <iostream>
#include <string>


int main()
{
    std::string letters{};

    std::cout << "Enter a string of letters so I can create a Letter Pyramid from it: ";
    getline(std::cin, letters);

    size_t num_letters = letters.length();

    int position {0};

    // for each letter in the string
    for (char c: letters) {

        size_t num_spaces = num_letters - position;
        while (num_spaces > 0) {
            std::cout << " ";
            --num_spaces;
        }

        // Display in order up to the current character
        for (size_t j=0; j < position; j++) {
            std::cout << letters.at(j);
        }

        // Display the current 'center' character
        std::cout << c;

        // Display the remaining characters in reverse order
        for (int j=position-1; j >=0; --j) {
            // You can use this line to get rid of the size_t vs int warning if you want
            auto k = static_cast<size_t>(j);
            std::cout << letters.at(k);
        }

        std::cout << std::endl; // Don't forget the end line
        ++position;
    }

    return 0;
}

Hello I am learning C++ as a beginner and I cannot seem to grasp the logic of this program. So For Example if I entered ABC the output would be:

    A
   ABA
  ABCBA

how does num_spaces give me the spaces? Also the Display in order up to the current character. He created a for loop but if I am reading this correctly wouldn't j be 0 and position be 0 so how would 0 < 0? and what does letters.at(j) have to do with it. I am very confused with most of the program if someone can explain it to me that would be great!

Aucun commentaire:

Enregistrer un commentaire