How to print text diagonally from left to right recursively in C++

1 Answer

0 votes
#include <iostream>
#include <string>

void print_text_diagonally_recursively(const std::string& text, int spaces = 0) {
    if (text.empty()) {
        return; // base case
    }

    // print indentation
    std::cout << std::string(spaces, ' ');

    // print first character
    std::cout << text[0] << "\n";

    // recursive call with next character
    print_text_diagonally_recursively(text.substr(1), spaces + 1);
}

int main() {
    std::string text = "Hello World";
    
    print_text_diagonally_recursively(text);
}


/*
run:
 
H
 e
  l
   l
    o
      
      W
       o
        r
         l
          d
 
*/

 



answered Apr 7 by avibootz

Related questions

...