#include /* The C library has a built in function for finding the ** length of a string (strlen()). This is declared in ** string.h. We could also have used the function ** presented elsewhere in this tutorial. */ #include /* ** There are a number of ways of solving this problem ** - a couple are presented below */ void reverse_string_and_print(char string[]) { int i, len; char c; len = strlen(string); /* We iterate from the first character to the middle. ** We swap each character with the the one at the ** other end (note last char is at posn len-1). ** If len is odd, the middle position will have ** nothing done to it (which is what we want). */ for(i=0; i < len/2; i++) { c = string[i]; string[i] = string[len-1-i]; string[len-1-i] = c; } printf("%s\n", string); } /* ** In the following function we don't actually reverse the ** string, we just use a for loop to iterate over each ** character in the string starting from the end and ** working our way back to the beginning */ void print_string_in_reverse(char string[]) { int i; for(i=strlen(string)-1; i >= 0; i--) { printf("%c", string[i]); } printf("\n"); } /* ** This function removes the trailing newline from a ** string (if present). We check (a) that the ** string is not empty and (b) if the last ** character (at position length-1) is a newline. If ** so, we turn it into a null character. */ void remove_trailing_newline(char string[]) { int len; len = strlen(string); if(len > 0 && string[len-1] == '\n') { string [len-1] = '\0'; } } int main() { char string1[80]; /* Prompt user and get string */ printf("Enter string: "); fgets(string1, 80, stdin); remove_trailing_newline(string1); printf("String in reverse:\n"); reverse_string_and_print(string1); printf("Reversed again...:\n"); print_string_in_reverse(string1); return 0; } /* Remember that when you pass an array to a function it is NOT passed ** by value, i.e. any changes to the array are reflected in the original ** version also. (This is not the case for "scalar" variables, e.g. ** integers and characters). */