Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

trying to reverse string without string functions but not working in c

#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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading