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.
Table of Contents
Reverse Sentence in C
Let’s write a C program to perform String reversal –
#include <stdio.h>
#include <string.h>
void reverseSentence(char *sentence)
{
int length = strlen(sentence);
int start = 0;
int end = length - 1;
// Reversing entire sentence
while (start < end)
{
char temp = sentence[start];
sentence[start] = sentence[end];
sentence[end] = temp;
start++;
end--;
}
// Reversing each word individually
int i = 0;
while (i < length)
{
int j = i;
while (sentence[i] != ' ' && sentence[i] != '\0')
{
i++;
}
end = i - 1;
while (j < end)
{
char temp = sentence[j];
sentence[j] = sentence[end];
sentence[end] = temp;
j++;
end--;
}
i++;
}
}
void main()
{
char string[] = "This is C Program";
printf("Original sentence = %s\n", string);
reverseSentence(string);
printf("Reverse sentence = %s\n", string);
}
Output
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 loopwhile (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
3 thoughts on “C Program to Reverse a Sentence”