In this C++ tutorial, you shall learn how to repeat a given string for N times using a For loop, with example programs.

Repeat string for N times in C++

To repeat a string for N times in C++, you can use a For loop to iterate from 0 to N-1, and then in each iteration inside the For loop, append the input string to the repeated string.

1. Repeat string “Hello” for 5 times using For loop in C++

In the following program, we take a string in inputString and an integer in n. We have to repeat the string for n number of times.

  1. Take an empty string in repeatedString
  2. Use a C++ For loop to iterate from 0 upto n, and append the inputString to the repeatedString.
  3. After the For loop, repeatedString contains the resulting string of inputString repeated for n times.

main.cpp

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string inputString = "Hello";
    int n = 5; // Number of times to repeat the string

    string repeatedString = "";
    for (int i = 0; i < n; ++i) {
        repeatedString += inputString;
    }

    cout << repeatedString << endl;

    return 0;
}

Output

HelloHelloHelloHelloHello

Conclusion

In this C++ Tutorial, we learned how to repeat a given input string for N number of times using a For loop, with examples.