Design a function to reverse the given string in c
C String Reversal Function - Code Example and Tutorial
"Design a function to reverse the given string"
means that you are being asked to create a program or function that takes a string as input and returns the same string with its characters in reverse order.
For example, if the input string is "hello",
the output of your function should be "olleh"
.
The function should take a string as an argument and use code to reverse the order of the characters in the string. Once the reversal is complete, the function should return the reversed string as output.
To design a function to reverse the given string in C, we can use the following steps:
- Declare a function called reverse() that takes a string as input and returns a reversed string.
- Initialize a variable to store the reversed string.
- Iterate over the input string from the end to the beginning and copy each character to the reversed string.
- Return the reversed string.
C code example for the reverse() function:
#include <string.h>
char *reverse(char *str) {
char *reversed_str = malloc(strlen(str) + 1);
int i = strlen(str) - 1;
int j = 0;
while (i >= 0) {
reversed_str[j] = str[i];
i--;
j++;
}
reversed_str[j] = '\0';
return reversed_str;
}
The reverse() function takes a string pointer as input and returns a pointer to the reversed string. The function first allocates memory for the reversed string using the malloc() function. Then, it iterates over the input string from the end to the beginning and copies each character to the reversed string. Finally, it returns a pointer to the reversed string.
Example of how to use the reverse() function:
int main() {
char str[] = "hello";
char *reversed_str = reverse(str);
printf("The reversed string is: %s\n", reversed_str);
free(reversed_str);
return 0;
}
Output:
The reversed string is: olleh