rev_print — Reverse Print a String
Allowed functions: write
Write a program that takes a string, and displays the string in reverse followed by a newline.
If the number of parameters is not 1, the program displays a newline.
Examples
$> ./rev_print "zaz" | cat -e
zaz$
$> ./rev_print "dub0 a POIL" | cat -e
LIOP a 0bud$
$> ./rev_print | cat -e
$
Solution
Download rev_print.c#include <unistd.h>
int main(int c, char **v) {
if (c != 2) {
write(1, "\n", 1);
return 0;
}
int i = 0;
char *str = v[1];
while (str[i]) {
i++;
}
while (i > 0) {
i--;
write(1, &str[i], 1);
}
write(1, "\n", 1);
return 0;
}
How It Works
Goal: Print a string in reverse order followed by a newline.
Approach: First find the string length, then iterate backwards printing each character.
Step by step:
- If argument count is not 2, print a newline and exit.
- Walk through the string to find its length by incrementing
iuntilstr[i]is'\0'. - Decrement
iand print each character from the end back to the beginning. - Print a trailing newline.
Key concept: Reverse iteration — finding the end of a string first, then looping backwards to process characters in reverse order.