Skip to main content

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:

  1. If argument count is not 2, print a newline and exit.
  2. Walk through the string to find its length by incrementing i until str[i] is '\0'.
  3. Decrement i and print each character from the end back to the beginning.
  4. Print a trailing newline.

Key concept: Reverse iteration — finding the end of a string first, then looping backwards to process characters in reverse order.