Print a character n times without using loop, recursion or goto in C++

C++Server Side ProgrammingProgramming

In this section we will see how to print a character n times without using loops and recursion in C++. We can solve this problem by using string class constructors. There is a constructor where we are taking the character that will be printed multiple times, and the number of times it will be printed.

Example Code

#include <iostream>
using namespace std;
void print_char_n_times(char my_char, int count) {
   cout << string(count, my_char) << endl;
}
int main() {
   //print character B 10 times
   print_char_n_times('B', 10);
   //print character x 30 times
   print_char_n_times('x', 30);
}

Output

BBBBBBBBBB
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
raja
Published on 03-Apr-2019 14:15:08
Advertisements