JavaScript Program:
let sentence = "how are you";
let end = sentence.length - 1;
let word = "";
let start;
for (let i = end; i >= 0; i--) {
if (sentence[i] === " " || i === 0) {
let start;
if (i === 0) {
start = i;
} else {
start = i + 1;
}
for (let j = start; j <= end; j++) {
word = word + sentence[j];
}
console.log(word);
word = "";
end = i - 1;
}
}
output:
Algorithm:
- Start
- Initialize a string sentence = "how are you"
- Set: end = length of sentence - 1 word = "" (empty string)
- Loop from end to start of the string (i = end → 0)
- For each character: Check if space OR i == 0
- If condition is true: Determine start index: If i == 0 → start = i Else → start = i + 1
- Extract the word: Loop from start → end Add each character to word
- Print the word
- Reset: word = "" end = i - 1
- Continue loop until i = 0
- Stop

Top comments (0)