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

C++Server Side ProgrammingProgramming

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
raja
Published on 25-Jul-2019 13:26:28
Advertisements