C Program to Reverse a Sentence

Manipulating strings and characters is a fundamental skill in the world of programming, and one common task is reversing sentences. Reversing a sentence involves rearranging the words in the sentence in the reverse order. In this article, we will write a C program to reverse a Sentence.

Reverse Sentence in C

Let’s write a C program to perform String reversal –


Reverse Sentence in C

How Above C Program Works for Reverse a string

  • The function named reverseSentence takes a pointer to a character array as an argument.
  • The function starts by calculating the length of the input sentence by using strlen(), to pointer start=0 and end=length-1.
  • A while loop is used to reverse an entire sentence. Characters at position pointed by start and end are swapped.
  • Another while loop is used to swap each word individually. The outer loop while(i<length) iterates through the sentences and the inner loop while (sentence[i] != ' ' && sentence[i] != '\0') is used to identify the end of each word. At the end, each word is reversed by swapping characters and the outer loop continues until the entire sentence is processed.

Happy Coding

See Also

3 thoughts on “C Program to Reverse a Sentence”

Leave a Comment