DEV Community

Harini
Harini

Posted on

String Program

Reverse the word

Algorithm

  1. Start
  2. Initialize variables:
    • sen → input string
    • start = 0
    • end = sen.length - 1 (points to last character)
    • result = "" (to store final output)
  3. Loop from end of string to beginning:
    • For i = end to 0
  4. Check condition:
    • If sen[i] == " " (space found) OR i == 0 (start reached)
  5. Decide starting index of word:
    • If i == 0 → start = i
    • Else → start = i + 1
  6. Extract the word:
    • Loop from j = start to end
    • Add each character to result
  7. Add space after word:
    • result += " "
  8. Update end:
    • end = i - 1 (move to previous word)
  9. Repeat until loop ends
  10. Print result
  11. 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);   
Enter fullscreen mode Exit fullscreen mode

Output

Top comments (0)