DEV Community

Cover image for Algorithm to repeat a string num time
Cesare
Cesare

Posted on

2 2

Algorithm to repeat a string num time

Problem:

Repeat a string numerous times.

This function input:

repeatStringNumTimes("abc", 3);

gives us this output:

abcabc

One of the way to achieve this:

Step 1

create a local variable equal to an empty string in order to have an empty container where to store all the string we are going to create:

let accumString = ""

Step 2

Create an iteration through a while loop

while ( num > 0 ) --> attention is a potential infinite loop

Step 3

Under the while loop condition fill up the variable using the addition assignment operator +=

accumString += str

Step 4

to avoid the infinite loop just created associate to num the decrement operator -- to stop the loop when num is 0.

note: the while loop is completed and we can close the curly bracket.

Step 5

Outside of the while loop but still inside the function insert the return statement to stop the function and return the value of the function.

Step 6

Now call the function repeatStringNumTimes("abc", 3) with inside a random string and integer.

the output will be: abcabc

The whole function just created below:

function repeatStringNumTimes(str, num) {

let accumString = "";
while ( num > 0 ){
accumString += str;
num--;
}

return accumString;
  }

repeatStringNumTimes("abc", 3);
Enter fullscreen mode Exit fullscreen mode

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo πŸ“Šβœ¨

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay