Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jun 2008
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    C loop, giving me trouble !! Can anyone help..?

    i have this code to test for palindromes, it functions perfectly well on the first test, but as the program continues to check for more after the first word it keeps printing not palindrome, once it wasnt the first word typed, run it pls, and you'll c what im talking about. Can anyone help me fix it..?


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

    int isPalindrome( char *s);
    int main (void)
    {
    int i=0;
    int ch;
    char s[100];
    while (1){
    while ((ch = getchar()) != ('\n')){
    if (isalpha(ch)){
    ch=toupper(ch);
    s[i]=ch;
    i++;
    }
    }
    s[i]='\0';
    if (isPalindrome(s) ==1){
    printf("is palindrome\n");
    }
    else{
    printf("not palindrome\n");
    }
    system("Pause");
    return 0;
    }
    thanks,
    -------------------------------------------
    Girly Lay outs vegetarian diet

  • #2
    Gox
    Gox is offline
    Regular Coder Gox's Avatar
    Join Date
    May 2006
    Location
    Ontario, Canada
    Posts
    392
    Thanks
    2
    Thanked 20 Times in 20 Posts
    From a quick look at your code my guess is there might be an issue with the value for "i" for subsequent loops.

    It looks like your code is doing the following:
    i = 0
    read char 'a'
    s[i] = a
    i = 1
    read char 'b'
    s[i] = b
    i = 2
    read char '\n'
    s[i] = '\0'
    "not a palindrome"
    -----------
    Loop,
    read char 'c'
    s[i] = c
    i = 3
    read char '\n'
    s[i] = '\0'
    etc..
    -----

    Do you see the issue? When you're reading the first word using my above example S would look like: s[0] = a, s[1] = b, s[2] = \0, and i = 2.
    Then when we loop you don't reset i back to 0 so your s[] gets overwritten to the following: s[0] = a, s[1] = b, s[2] = c, s[3] = \0, i = 3.

    Try setting i = 0 when you start reading a new word and see if that helps:
    while(1){
    i = 0;
    while{
    ....

    I haven't run your code, so this is merely a guess. But I'd take a look at that and see if it helps.

    Gox


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •