I would suggest that you reverse the string in place and then print it with "%s" format specifier. That way you save multiple calls to printf.
I would suggest that you reverse the string in place and then print it with "%s" format specifier. That way you save multiple calls to printf.
Thank you so much for your suggestion. I have made some changes to my code taking your suggestion:
Code://This is a small program to reverse the string provided by user #include<stdio.h> #include<string.h> int main() { char string[256], revstr[256]; int len, i; printf("Enter a string:\n"); fgets(string, 256-1, stdin); len = (strlen(string) - 1); printf("You entered %s \nlength %d:\n", string, len); i = len; printf("Reverse string:"); for(; len >= 0; len--) revstr[i-len] = string[len]; revstr[i+1] = '\0'; printf("Reversed string is: %s\n", revstr); exit(0); }
You could reverse the string by swapping characters up to half way through the string with the corresponding characters on the other half of the string. Just a different way of doing it:
Code:#include <stdio.h> #include <string.h> void Reverse(char* string) { int len = strlen(string)-1; int mid = len / 2; int pos; char tmp; for(pos=0; pos<mid; pos++) { tmp = string[pos]; string[pos] = string[len-pos]; string[len-pos] = tmp; } } int main() { char string[256]; fgets(string, 256, stdin); string[strlen(string)-1]='\0'; printf("Normal: %s\n", string); Reverse(string); printf("Reversed: %s\n", string); Reverse(string); printf("Back again: %s\n", string); getchar(); return 0; }