Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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