📜  在C++中不使用循环,递归或goto来打印字符n次

📅  最后修改于: 2021-05-30 12:40:35             🧑  作者: Mango

给定一个字符c和一个数字n,将字符c打印n次。我们不允许使用循环,递归和goto。

例子 :

Input : n = 10, c = 'a'
Output : aaaaaaaaaa

Input  : n = 6, c = '\n'
Output :

Input  : n = 6, character = '@'
output : @@@@@@

在C++中,有一种用值初始化字符串的方法。它可以根据需要多次打印字符。声明字符串,可以使用C++提供的功能对其进行初始化。它需要2个参数。首先是我们要打印特定字符的次数,其次是字符本身。

下面是说明这一点的实现。

// CPP Program to print a character 
// n times without using loop,
// recursion or goto
#include
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; 
}

输出:

GGGGGG

另一种方法:众所周知,每次创建类的对象时,都可以调用该类的构造函数,从而利用我们的优势并在构造函数中打印字符,并创建该类的N个对象。

#include
using namespace std;
  
class Geeks{
  
    public:
        Geeks(){
            cout<<"@ ";
        }
         
};
  
int main(){
    int N =6;
  
    Geeks obj[N];
    return 0;
}

输出:

@ @ @ @ @ @
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”