-1

Everything is working in my code but as soon as user inputs "BYE" my program is not ending i don't know why while loop is not responding to that code

#include "stdio.h"
#include <string.h>

int main(void)
{
    char ch[20];

    while (ch != "bye")
    {
        scanf("%s", ch);

        int i;
        int n = strlen(ch);
        int c = 0;


        for (i = 0; i < n / 2; i++)
        {
            if (ch[i] == ch[n - i - 1])
                c++;
        }
        if (c == i)
        {
            printf("1");
        }
        else
        {
            printf("0");
        }
    }
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • `while (ch != "bye")` compares the addresses of the array `ch` and the string literal, which will never be the same. Use `while (strcmp(ch, "bye") != 0)`. – mch Oct 08 '21 at 12:04
  • `strcmp` ... look it up... your code compares two pointers – Support Ukraine Oct 08 '21 at 12:04

1 Answers1

0

For starters the array ch was not initialized that is initially it does not contain a string

char ch[20];

Secondly in the condition of the while loop

while (ch != "bye")

there are compared two addresses: the address of the first element of the array ch and the address of the first element of the string literal "bye". As the array and the string literal occupy different extents of memory the addresses always will be unequal. So as a result you have an infinite loop that does not contain a break statement.

If you want to compare strings then you need to use the standard string function strcmp as for example

if ( strcmp( ch, "bye" ) == 0 )
{
    //...
}

In this case the array ch shall already contain a string.

So instead of the while statement it is better to use do-while statement or an infinite while statement that will be interrupted through the break statement if strcmp will return 0.

For example

while ( 1 )
{
    char ch[20];

    scanf("%19s", ch );

    if ( strcmp( ch, "bye" ) == 0 ) break;
    
    size_t n = strlen(ch);

    size_t i = 0;
    while ( i < n / 2 && ch[i] == ch[n - i - 1] ) ++i;
 
    if ( i == n / 2 )
    {
        printf("1");
    }
    else
    {
        printf("0");      }
    }  
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335