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: 2019-07-30T22:30:25+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements