C program to print a line in reverse order using pointer comparison

      This C program reverses the contents of a string by swapping the first character with the last character and so on until it reverses all the characters in the input string.This is how the program reverse order of all the characters in a string.

c program to reverse order of all the characters in the input string



Source Code :

#include<stdio.h>
#include<string.h>
int main()
{
	char a[50];
	void reverse(char *);
	printf("\n Enter the string:");
	gets(a);          //Step 1
	reverse(a);       //Step 2
	printf("\nAfter reversing the string is :\n");
	puts(a);          //Step 6
	return 0;
}
void reverse(char *string)
{
	char *lp = string;   //Step 3
	char *rp = &string[strlen(string)-1]; //Step 4
	char tmp;
	while(lp < rp)     //Step 5
	{
		tmp = *lp;
		*lp = *rp;
		*rp = tmp;
		lp++;
		rp--;
	}
}


edit-code-image

Sample Test cases :

1.  Enter the string:topoint is a good source for programming questions
    After reversing the string is :
    snoitseuq gnimmargorp rof ecruos doog a si tniopot


2.  Enter the string:hii
    After reversing the string is :
    iih

Explanation:

Step 1: The string is read from the user using gets() function.

Step 2: The reverse() function is called from the main program.

Step 3: The leftmost character in the input string is assigned to ‘lp’ pointer.

Step 4: The rightmost character in the input string is assigned to ‘rp’ pointer.

Step 5: This while loop comapres two pointers and swaps them until lp < rp. Step 6: The reversed string is displayed on the output screen using puts() function.

More Insights:

1. More about pointer comparision.

More Content :Explore More