Fetching latest headlines…
Reverse Words in a Sentence
NORTH AMERICA
πŸ‡ΊπŸ‡Έ United Statesβ€’May 8, 2026

Reverse Words in a Sentence

7 views0 likes0 comments
Originally published byDev.to

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:

  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

Comments (0)

Sign in to join the discussion

Be the first to comment!