Introduction
In this coding challenge, we are given a function with two arguments: a string(str = 'abc') and a number(num = 3) . Our task is to solve this challenge and produce the stringabc repeated as many times as the number indicates(e.g., 'abcabcabc'). It is strictly prohibited to use the built-in methodrepeat()(commonly available in most programming languages) because using built-in methods would defeat the purpose of the coding challenge. It is unacceptable to use built-in methods during coding interviews. This challenge can be solved in any programming language, but in this article, we will use JavaScript to solve it. If you have any doubts about this, don't worry; they will be cleared once we go a bit further into it. Let’s start coding
Remember, there are countless ways to solve any coding challenge or problem in every programming language, I am going to show you one and simple.
Solution:
function repeatStringNumTimes(str, num) {
let finalStr = "";
for(let i = 0; i < num; i++) {
finalStr += str;
}
return finalStr;
}
console.log(repeatStringNumTimes("abc", 3));
// output: abcabcabc
Breaking Up Solution:
Let's break this down for clarity!
As you can see,repeatStringNumTimes is a function with two arguments,str andnum. It is a normal function. Hopefully, you have prior knowledge about functions, as I am not going into depth about them for now. As we already know,str is a variable where ourWords will be stored, whilenum is a variable where ourNumber will be stored.
Great! We have explored the function, and now it's time to solve it. First, we need to declare a new variable where we will later assign our string after successfully repeating it. I have declared finalStr as a variable and left it empty for now. You can see it below:
let finalStr = '';
Now, we are not far from starting the operation to repeat our string. We use afor loop for this purpose. Within the loop, we seti = 0 to start from0 andi < num to stop before num (when num = 3, our loop will start from 0 and stop on2, as the length is3, counting0,1,2). We can start our loop withi = 1 and stop oni <= num, but I prefer the basic structure of starting the loop withi = 0.
As you can see, the loop will take3 steps(0, 1, 2), so ourstr will beabcabcabc from thisabc. Finally, we will assign our repeated str tofinalStrusing the += sign. It's important to note that without using the+ operator, the current state of str('abcabcabc') will not be assigned; instead, we will get the previous state ofstr('abc').
At the end, we returnfinalStr since it is essential for the final output in every function.