exc/k&r/04-funcs-and-prog-struct/04-13.c

29 lines
605 B
C

#include <stdio.h>
int reverse(char string[], int i);
/* reverses command line argument */
int main(int argc, char *argv[])
{
if (argc < 2)
return 1;
printf("length : %d\n", reverse(argv[1], 0));
printf("reversed : %s\n", argv[1]);
return 0;
}
/* reverse: reverses string from index i, returns length
* recursive implementation */
int reverse(char s[], int i)
{
if (s[i] == '\0') { /* base case */
return 0;
}
int j = reverse(s, i+1);
if (j > i) { /* swap elements */
char c;
c = s[i], s[i] = s[j], s[j] = c;
}
return j+1;
}