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, c = '\n'
Output :




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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP Program to print a character 
// n times without using loop,
// recursion or goto
#include<bits/stdc++.h>
using namespace std;
  
// print function
void printNTimes(char c, int n)
{
    // character c will be printed n times
    cout << string(n, c) << endl;
}
  
// driver code
int main()
{
    // no of times a character
    // need to be printed
    int n = 6;
    char c = 'G';
      
    // function calling
    printNTimes(c, n);
  
    return 0; 
}

chevron_right


Output:

GGGGGG


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.