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


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

Updated on: 30-Jul-2019

812 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements