DEV Community

Cover image for Reverse Words in a Sentence
Vidya
Vidya

Posted on

Reverse Words in a Sentence

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;  
  }
}
Enter fullscreen mode Exit fullscreen mode

output:

Algorithm:

  1. Start
  2. Initialize a string sentence = "how are you"
  3. Set: end = length of sentence - 1 word = "" (empty string)
  4. Loop from end to start of the string (i = end → 0)
  5. For each character: Check if space OR i == 0
  6. If condition is true: Determine start index: If i == 0 → start = i Else → start = i + 1
  7. Extract the word: Loop from start → end Add each character to word
  8. Print the word
  9. Reset: word = "" end = i - 1
  10. Continue loop until i = 0
  11. Stop

Top comments (0)