Print a Character N Times Without Using Loop, Recursion or Goto in C++



In this article, we will see how to print a character n times without using loops and recursion in C++.

Input/Output Scenario

Let's see following input output scenario ?

Input : n = 10, c = 'i'
Output : iiiiiiiiii

Input : n = 5, character = 'j'
Output : jjjjj

Using String Constructor

Here, using the string constructor in C++ to print a character n times: It allows initialization of a string with multiple copies of a specific character by passing the number of times and the character itself as arguments.

Example

In this C++ example, we will display a character n times using the string constructor:

#include<bits/stdc++.h>
using namespace std;

void char_n_times(char ch, int n) {
   // char T print n times
   cout << string(n, ch) << endl;
}
int main() {
   int n = 5;
   char ch = 'T';

   char_n_times(ch, n);

   return 0;
}

Following is the output of the above code ?

TTTTT

Using Class Constructor

In C++, the class constructor is automatically called whenever an object of the class is created. So, we can take advantage of it by displaying a character inside the constructor. Then, by creating n objects of the class, the constructor will run n times, and effectively display the character n times.

Example

In this C++ example, we will display a character n times using the class constructor:

#include<bits/stdc++.h>
using namespace std;
class Display {
   public: Display() {
      cout << "A";
   }
};
int main() {
   int n = 10;

   Display obj[n];
   return 0;
}

Following is the output ?

AAAAAAAAAA
Updated on: 2025-05-16T16:58:12+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements