Skip to content
Home » C Programs » Reverse a String Using Pointers in C Algorithm

Reverse a String Using Pointers in C Algorithm

Simple program to reverse a string in c. The performance is “olleh” if the string is “hello.” This method needs two pointers, one pointing to the beginning of the string and the other pointing to the end of the string

String in C Program

Strings are one-dimensional arrays of characters that are terminated by the null character ‘0’. Thus, a null-terminated string contains the string’s characters followed by a null. The following declaration and initialization generate a string that contains the word “Hello.”

Pointer in C

A pointer is a variable whose value is the address of another variable, that is the memory location’s direct address. A pointer, like any variable or constant, must be declared before it can be used to store any variable address. 

A variable that stores the address of another variable is known as a pointer. In contrast to other variables that hold values of a specific type, a pointer variable holds the address of a variable. Pointer method is used in this program to execute reverse program to reverse a string in c

Pre Increment Operator in C

A pre-increment operator is used to increase a variable’s value before using it in an expression. The value is first incremented and then used within the expression in the Pre-Increment.

Pre Decrement Operator in C

The pre decrement operator is used to decrement a variable’s value by one before assigning it a value. After assigning a value to a variable, the post decrement operator is used to decrement the value by one. 

Program to Reverse a String in C

//program to reverse a string in c 
#include <stdio.h>
int main()
{
char str[100];
char rev[100];
char *sptr = str; 
char *rptr = rev; 
int i = -1;
printf("\n\nEnter the string");
scanf("%s", str);
while(*sptr)
{
sptr++;
i++; 
}
while(i >= 0)
{
sptr--; 
*rptr = *sptr; 
rptr++; 
i--; 
}
*rptr = '\0'; 
rptr = rev; 
while(*rptr)
{
*sptr = *rptr;
sptr++;
rptr++;
}
printf("\n\nReverse of the string is: %s ", str);
return 0;
}

Output of program to reverse a string in c:

Enter the string inlarn

Reverse of the string is: nralni