Today, we have an exciting challenge that will enhance your understanding of strings in C programming. Our task is to write a function that prints a string in reverse, followed by a new line. It may sound tricky, but it’s an excellent opportunity to practice your skills. So, let’s get started!
Task Description:
The task at hand is to create a function called “print_rev” that takes a character pointer “s” as its parameter. This function will print the string in reverse order, followed by a new line using putchar function.
Prototype:
void print_rev(char *s);
Challenge:
Before we dive into the solution, I encourage you to attempt the challenge on your own. Take a moment to write the code for the “print_rev” function and give it a try. Once you’re done, come back here to compare your solution with the one provided.
Code Solution & Explanation:
#include <stdio.h>
void print_rev(char *s)
{
int len = 0;
int i;
while (s[len] != '#include <stdio.h>
void print_rev(char *s)
{
int len = 0;
int i;
while (s[len] != '\0')
{
len++;
}
for (i = len - 1; i >= 0; i--)
{
putchar(s[i]);
}
putchar('\n');
}
')
{
len++;
}
for (i = len - 1; i >= 0; i--)
{
putchar(s[i]);
}
putchar('\n');
}
In the “print_rev” function, we start by finding the length of the string using a while loop. We iterate through the characters of the string s until we encounter the null terminator character '\0'
. By counting the number of iterations, we determine the length of the string.
After obtaining the length, we use a for
loop to print the characters of the string in reverse order. We start from the last character (at index len - 1
) and decrement the index until we reach the first character (at index 0). Within the loop, we use “putchar” to print each character.
Finally, we include putchar('\n')
to print a new line after the reversed string.
Output & Usage:
Let’s test the print_rev function with a simple example:
int main(void)
{
char *str;
str = "Welcome to Rocodeify";
print_rev(str);
return (0);
}
Expected Output:
The output of the code above should be:

Conclusion:
Congratulations on completing the challenge! You have successfully written a function that prints a string in reverse order. Understanding how to manipulate strings in this way is an essential skill in programming.
If you encountered any difficulties or have questions, feel free to ask for help. Our coding community at ASK A QUESTION is a great place to seek assistance, share your solutions, and discuss related topics with fellow coders.
Keep practicing and exploring different string operations in C to strengthen your skills. The more you experiment, the better you’ll become at tackling programming challenges.
Happy coding, and see you in the next challenge!
If you found this post helpful or have any feedback, please leave a comment below.