C Exercises: Reverse a given string using an inline function
10. Reverse String Inline Variants
Write a C program to reverse a given string using an inline function.
Sample Solution:
C Code:
#include <stdio.h>
#include <string.h>
// inline function to reverse a given string
inline void reverse_string(char * str) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
int main() {
char str[100];
printf("Input a string: ");
fgets(str, 100, stdin);
str[strcspn(str, "\n")] = '\0'; // remove newline character from input
printf("Before reverse: %s\n", str);
reverse_string(str);
printf("After reverse: %s\n", str);
return 0;
}
Sample Output:
Input a string: Wikipedia Before reverse: Wikipedia After reverse: aidepikiW Input a string: C language Before reverse: C language After reverse: egaugnal C
Explanation:
In the above program, we define an inline function reverse_string() that takes a char pointer as input and reverses the string in its place. In the main() function, we get a string input from the user using the fgets() function. We remove the newline character from the input with strcspn() function. Use the printf() function to print the string before and after reversing, and return 0 to indicate the successful execution of the program.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C program to reverse a string using pointer arithmetic inside an inline function.
- Write a C program to reverse each word of a sentence using an inline function.
- Write a C program to reverse only the vowels in a string using an inline function.
- Write a C program to reverse a string and then check if it forms a palindrome using an inline function.
Go to:
PREV : Even/Odd Check Inline Variants.
NEXT : Variadic Sum Inline Variants.
C Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.