Exercise 4-13 (Recursive reverse)

Chapter_4     Exercise_4-12 Exercise_4-14







Exercise 4-13     K&R, p. 88


Exercise 4-13. Write a recursive version of the function reverse(s), which reverses the string s in place (see the Index entry reverse).




reverse.c         download


#include <stdio.h> // for printf(), scanf()
#include <string.h> // for strlen()

#define SIZE 100 // array size

void reverse(char s[], int i, int j); // reverse a string from s[i] to s[j]

int main()
{
char array[SIZE];
int len; // array length

printf("Type a string:\t");
scanf("%s", array);

len = strlen(array);
reverse(array, 0, len-1);
printf("Reversed:\t%s\n", array);

return 0;
}

void reverse(char s[], int i, int j) // reverse a string from s[i] to s[j]
{
int temp;

if (i < j)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
reverse(s, i, j);
}
}
/*
gcc reverse.c -o reverse
./reverse
Type a string: a
Reversed: a

./reverse
Type a string: ab
Reversed: ba

./reverse
Type a string: abc
Reversed: cba

./reverse
Type a string: 123456
Reversed: 654321
*/









Chapter_4     Exercise_4-12 BACK_TO_TOP Exercise_4-14



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo