Write a C program to find reverse of a given string using loop. How to find reverse of any given string using loop in C programming. Logic to find reverse of a string without using strrev() function in C. C program to reverse a string using strrev() string function.
Example
Input
Output
Reverse string: olleH
Required knowledge
Basic C programming, For loop, String
Must know – Program to find reverse of an array
Logic to find reverse of a string
There are numerous ways to find reverse of a string. Here in this lesson I am going to explain few of them. First let us see the easiest method to find reverse of a string. Below is the step by step descriptive logic to find reverse of a string.
- Input a string from user, store it in some variable say str.
- Declare another array that will store reverse of the string, say char reverse[SIZE].
- Find length of the string and store it in some variable say len.
- Initialize two variables that will keep track of original and reverse string. Here we will access original string from last and reverse array from first. Hence, initialize strIndex = len – 1 and revIndex = 0.
- Run a loop from len – 1 to 0 in decremented style. The loop structure should look like while(strIndex >= 0).
- Inside the loop copy current character from original string to reverse string. Say reverse[revIndex] = str[strIndex];.
- After copying, increment revIndex and decrement strIndex.
Read more – Program to reverse order of words in a given string
Program to find reverse of a string
Once you got the above approach, you can easily transform the program in pointers context. Let us re-write the above program more efficiently using pointers.
Program to find reverse of a string using pointers
The above program is little geeky. However, in real life it is recommended to use built-in library function strrev() to find reverse of any string. strrev() is a string library function defined under string.h header file.
Program to find reverse of a string using strrev() function
Read more – Program to find reverse a number
Output
Enter any string: Codeforwin Original string = Codeforwin Reverse string = niwrofedoC
Happy coding
Recommended posts
- String programming exercises index.
- C program to convert uppercase string to lowercase string.
- C program to convert lowercase string to uppercase string
- C program to find reverse of a string.
- C program to check whether a string is palindrome or not.
- C program to find total number of vowels and consonants in a string.
- C program to find total number of words in a string.