C++ program to concatenate a string given number of times?


Here we will see how we can concatenate a string n number of times. The value of n is given by the user. This problem is very simple. In C++ we can use + operator for concatenation. Please go through the code to get the idea.

Algorithm

concatStrNTimes(str, n)

begin
   res := empty string
   for i in range 1 to n, do
      res := concatenate res and res
   done
   return res
end

Example

 Live Demo

#include<iostream>
using namespace std;
main() {
   string myStr, res = "";
   int n;
   cout << "Enter String: ";
   cin >> myStr;
   cout << "Enter number of times it will be concatenated: ";
   cin >> n;
   for(int i= 0; i < n; i++) {
      res += myStr;
   }
   cout << "Result: " << res;
}

Output

Enter String: Hello
Enter number of times it will be concatenated: 5
Result: HelloHelloHelloHelloHello

Updated on: 30-Jul-2019

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements