Reverse the word
Algorithm
- Start
- Initialize variables:
- sen → input string
- start = 0
- end = sen.length - 1 (points to last character)
- result = "" (to store final output)
- Loop from end of string to beginning:
- For i = end to 0
- Check condition:
- If sen[i] == " " (space found) OR i == 0 (start reached)
- Decide starting index of word:
- If i == 0 → start = i
- Else → start = i + 1
- Extract the word:
- Loop from j = start to end
- Add each character to result
- Add space after word:
- result += " "
- Update end:
- end = i - 1 (move to previous word)
- Repeat until loop ends
- Print result
- End
Program
let start = 0;
let sen = "YOU ARE HOW";
let len = sen.length - 1;
let end = len;
let result = "";
for (let i = end; i >= 0; i--) {
if (sen[i] == " " || i == 0) {
if (i == 0) {
start = i;
} else {
start = i + 1;
}
for (let j = start; j <= end; j++) {
result += sen[j];
}
result += " ";
end = i - 1;
}
}
console.log(result);
Output

Top comments (0)