Aim: Write a program to reverse a string using pointers in c
#include <stdio.h> #include <string.h> int main() { char str[100]; int len, i; char *begin, *end, ch; printf("Enter a string: "); gets(str); len = strlen(str); begin = str; end = str; for (i = 0; i < len - 1; i++) end++; for (i = 0; i < len / 2; i++) { ch = *end; *end = *begin; *begin = ch; begin++; end--; } printf("Reverse of the string is: %s", str); return 0; }
Another Approach
#include <stdio.h> #include <string.h> int main() { char *s, str[10]; int len, i; printf("Enter a string: "); gets(str); s=str; len = strlen(str); printf("The reverse of the string is: "); for (i = len; i >= 0; i--) { printf("%c", *(s + i)); } return 0; }
Seems like this code will be more satisfactory to students.
void main()
{
char *s;
int len, I;
printf(“\nENTER A STRING: “);
gets(s);
len = strlen(s);
printf(“\nTHE REVERSE OF THE STRING IS:”);
for (i = len; i >= 0; i–)
{
printf(“%c”, *(s + I));
}
getch();
}
//Actually I dkn if these comments are valid or not… anyways I liked this source of learning so will give yoy reviews and comments as I could…
Hi Gaseer, Thank you for your valuable contribution. We really appreciate you taking the time to share your feedback.