Here is a simple C language program to reverse the string using function and array:
#include <stdio.h>
#include <string.h>
void reverse_string(char []);
int main()
{
char str[100];
printf("Enter a string: ");
gets(str);
reverse_string(str);
printf("Reversed string is: %s\n", str);
return 0;
}
void reverse_string(char s[])
{
int i, j, len;
char temp;
len = strlen(s);
for (i = 0, j = len - 1; i < j; i++, j--)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
In this program, we first declare an array str
of size 100 to store the input string. We then prompt the user to enter a string and use the gets()
function to read the input string.
We then call the reverse_string()
function, which takes the string as an argument and reverses it. The function uses two pointers i
and j
, initialized to the beginning and end of the string, respectively. We then swap the characters at these two pointers and move them towards the center of the string until they meet.
Finally, we print the reversed string using the printf()
function.
Note that the gets()
function is not recommended for reading input strings due to the risk of buffer overflow. It is recommended to use the fgets()
function instead. Additionally, this program assumes that the input string is null-terminated. If the string is not null-terminated, the program may not work correctly.