Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_4.13_reverse_string.c
1240 views
1
/* a recursive version of revese(s); the string reverse function */
2
3
#include<stdio.h>
4
#include<string.h>
5
6
#define MAXLINE 100
7
8
int mgetline(char line[],int maxline);
9
void reverse(char s[]);
10
11
int main(void)
12
{
13
char s[MAXLINE];
14
15
mgetline(s,MAXLINE);
16
17
reverse(s);
18
19
printf("%s",s);
20
21
return 0;
22
}
23
24
int mgetline(char s[],int lim)
25
{
26
int i,c;
27
28
for(i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n';++i)
29
s[i] = c;
30
31
if(c=='\n')
32
s[i++]='\n';
33
34
s[i]='\0';
35
}
36
37
void reverse(char s[])
38
{
39
void reverser(char s[],int i,int len);
40
41
reverser(s,0,strlen(s));
42
}
43
44
/* reverser: reverse string s in place; recursive */
45
46
void reverser(char s[],int i,int len)
47
{
48
int c,j;
49
50
j = len - (i + 1);
51
52
if( i < j )
53
{
54
c = s[i];
55
s[i] = s[j];
56
s[j] = c;
57
58
reverser(s,++i,len);
59
}
60
}
61
62
63