#include <stdio.h>
#include <string.h>
void main(void)
{
char in[15], rev[15];
printf("Enter a word (upto 15 letters): ");
gets(in);
for (int i = 0, j = 15; i < strlen(in); i++, j--)
{
rev[i] = in[j];
}
puts(rev);
}
Shows no error, just not working.
What am I doing wrong?
>Solution :
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
The function gets is unsafe and is not supported by the C Standard. Instead use either scanf or fgets.
The function strlen is a standard C string function. So according to the requirement you may not use it.
You are not reversing a string. You are trying to copy a string in the reverse order into another string.
The program can look the following way
#include <stdio.h>
int main(void)
{
enum { N = 15 };
char in[N] = "", rev[N];
printf("Enter a word (upto %d letters): ", N - 1 );
scanf( " %14s", in );
size_t n = 0;
while ( in[n] ) ++n;
rev[n] = '\0';
for ( size_t i = 0; i < n; i++ )
{
rev[n - i - 1] = in[i];
}
puts( rev );
}