On to the next exercise...
Understanding the problem
Create a function that takes a user’s string input and reverses the string. For example. reverseString(’hello there’)
returns 'ereht olleh’
Plan
- Does program have a UI? What will it look like? What functionality will the interface have? Sketch this out on paper. The program does not have a UI. It’ll run in the console.
- What are the inputs? Will the user enter data or will you get input from somewhere else? The user will input a string when prompted
- What’s the desired output? The reverse of the string that the user inputed
Pseudocode
Declare a function `reverseString` that takes the parameter `string`
Create a loop that splices out each character of the string, starting from the last character
Concatenate each character at every loop and store this in a variable called `stringReversed`
Return `stringReversed`
prompt the user to enter a string and store it in a variable called `string`
Call the function `reverseString(string)`
Divide and Conquer
Declare a function reverseString
that takes the parameter string
const reverseString = function(string) {}
Create a loop that splices out each character of the string, starting from the last character
for (i = string.length - 1; i >= 0; i--) {}
We set the first loop to begin at the last character of the string. string.length
gives the number of characters in a string, but the actual index of the last character is string.length
. We run the loop until the last character which is at index 0.
Concatenate each character at every loop and store this in a variable called stringReversed
let stringReversed = '';
stringReversed += string[i];
Return stringReversed
return stringReversed;
Prompt the user to enter a string and store it in a variable called string
string = prompt('Enter a word or short sentence below');
Call the function reverseString(string)
reverseString(string);
Putting it all together
const reverseString = function(string) {
let stringReversed = '';
for (let i = string.length -1; i >= 0; i--) {
stringReversed += string[i];
}
return stringReversed;
};
string = prompt('Enter any word or short sentence below');
reverseString (string);
Top comments (0)