Print a character n times without using loop, recursion or goto in C++
Given a character c and a number n, print the character c, n times. We are not allowed to use loop, recursion, and goto. Examples :
Input : n = 10, c = ‘a’
Output : aaaaaaaaaa
Input : n = 6, character = ‘@’
Output : @@@@@@
In C++, there is a way to initialize a string with a value. It can be used to print a character as many times as we want. While declaring a string, it can be initialized by using the feature provided by C++. It takes 2 arguments. First is the number of times we want to print a particular character and the other is the character itself.
Below is the implementation which illustrates this.
CPP
#include<bits/stdc++.h>
using namespace std;
void printNTimes( char c, int n)
{
cout << string(n, c) << endl;
}
int main()
{
int n = 6;
char c = 'G' ;
printNTimes(c, n);
return 0;
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Another Method: As we know that every time an object of a class is created the constructor of that class is called we can use it to our advantage and print the character inside the constructor, and create N objects of that class.
CPP
#include<bits/stdc++.h>
using namespace std;
class Geeks{
public :
Geeks(){
cout<< "@ " ;
}
};
int main(){
int N =6;
Geeks obj[N];
return 0;
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
05 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...