Skip to content

Commit 4974a50

Browse files
Merge pull request #106 from sarthakw7/sarth
C Program to Reverse a String using Pointer
2 parents 58bd991 + b1fc605 commit 4974a50

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

C/reverse_string.c

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include <stdio.h>
2+
3+
int main()
4+
{
5+
char str[100];
6+
char rev[100];
7+
char *sptr = str; //base address of string
8+
char *rptr = rev; //base address of reverse
9+
10+
int i = -1;
11+
12+
printf("Enter a String: \n");
13+
scanf("%s", str);
14+
15+
// store the ending address of str in sptr
16+
while (*sptr)
17+
{
18+
sptr++;
19+
i++;
20+
}
21+
22+
// store the string str in rev in reverse order
23+
while (i >= 0)
24+
{
25+
sptr--;
26+
*rptr = *sptr;
27+
rptr++;
28+
i--;
29+
}
30+
31+
*rptr = '\0';
32+
rptr = rev; // restoring the base address of the reverse string
33+
34+
// storing the reverse string in the original string
35+
while (*rptr)
36+
{
37+
*sptr = *rptr;
38+
sptr++;
39+
rptr++;
40+
}
41+
42+
// priting the reverse string
43+
printf("Reverse of the string is :\n%s", str);
44+
return 0;
45+
}

0 commit comments

Comments
 (0)