Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: C program - trouble with IF statement

  1. Jul 2, 2004 #1

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I feel silly asking this but I can't get my "If" statement to work correctly. This should print "a is NOT equal to b" but it prints "a is equal to b".
    Any help? Thanks!!!

    #include <stdio.h>
    int main(void)
    {
    int a = 10;
    int b = 15;

    if(a == b)
    printf("a is equal to b \n");
    else
    printf("a is NOT equal to b \n");

    return 0;
    }
     
  2. jcsd
  3. Jul 2, 2004 #2

    AKG

    User Avatar
    Science Advisor
    Homework Helper

    Try using more brace brackets

    #include <stdio.h>
    int main(void)
    {
    int a = 10;
    int b = 15;

    if(a == b)
    {printf("a is equal to b \n");}
    else
    {printf("a is NOT equal to b \n");}

    return 0;
    }
     
  4. Jul 2, 2004 #3

    robphy

    User Avatar
    Science Advisor
    Homework Helper
    Gold Member

    works for me:

    Code (Text):


    #include <stdio.h>

    int main(void)
    {
    int a = 10;
    int b = 15;

    if(a == b)
    printf("a is equal to b \n");
    else
    printf("a is NOT equal to b \n");

    return 0;
    }


    $ gcc _test.c

    $ ./a.exe
    a is NOT equal to b
     
     
  5. Jul 2, 2004 #4
    Another tip: Make sure you are have a == b and not a = b in the code.
     
  6. Jul 2, 2004 #5
    One more thing: Get a debugger. You can see what is happening when you step through the code using a debugger than using any other method.
     
  7. Jul 2, 2004 #6

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I do have double equals. I cut and pasted exactly what I am trying to run.

    Thanks.
     
  8. Jul 2, 2004 #7

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    bizarre! I create a new.c file and pasted the code back in and now the logic works fine!
    I guess it will remain a mystery!

    thanks for running that on your end, robphy.
     
  9. Jul 2, 2004 #8

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I'll keep that in mind - thanks!
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook