My Assignment:
Create a program that will ask the user for a string and then pass the string to a function that would reverse it. The input string should be stored as a c-string (null terminated char array). The function to reverse the string should have the following prototype (declaration):
void reverse(char str[] );
The function should use two pointers to swap corresponding characters inside the string. One pointer should be initialized as the first character in the string and the other pointer as the last one. Then, through a series of iterations, the reverse() function should advance both pointers: one forward and the other backwards. After each advancement the pointers should be used to swap the characters. Remember that for c-strings you don't need to know the size of the array because strlen() function would provide the number of characters in the array. Please use comments on top of the function definition explaining what the function does and what are the parameters and return values.
The main() function should display the reversed string and ask for another input like in the following sample run:
Enter string to reverse: butterfly
Reversed string: ylfrettub
Do you want to insert another string (Y/N)? Y
Enter string to reverse: toyota
Reversed string: atoyot
Do you want to insert another string (Y/N)? N
Good bye!
This is what I have created so far, I can't figure out how to put the (Y/N) questions in this, PLEASE HELP!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include<stdio.h>
int string_length(char*);
void reverse(char*);
int main()
{
char string[100];
printf("Enter a string to reverse: \n");
gets(string);
reverse(string);
printf("Reversed string: \"%s\".\n", string);
return 0;
}
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = string_length(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
int string_length(char *pointer)
{
int c = 0;
while( *(pointer+c) != '\0' )
c++;
return c;
}
|