Thread: if statement with 2 conditions

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Apr 2015
    Posts
    4

    if statement with 2 conditions

    Hi all,
    I am currently trying to learn C and would appreciate any help...

    Can anyone please explain why the following code will not work?
    The if statement if (yn!='y' || yn!='n') always becomes true!

    Code:
    #include<stdio.h>
    
    main()
    {
        char yn;
        while(yn!='e') {
            printf("enter y/n? ");
            scanf(" %c", &yn);
                if (yn=='e') {
                    printf("goodbye\n");
                    break;
                }        
    
                if (yn!='y' || yn!='n') {
                    printf("error, enter y or n!\n");
                }
        }
    return 0;
    }
    I did manage to replicate the code with nested if's but after much reading it's better to write more concise code. Correct me if I am wrong?

    Code:
    #include<stdio.h>
    
    main()
    {
        char yn;
        while(yn!='e') {
            printf("enter y/n? ");
            scanf(" %c", &yn);
                if (yn=='e') {
                    printf("goodbye\n");
                    break;
                }            
    
                if (yn!='y') {
                    if (yn!='n') {
                        printf("error, enter y or n!\n");
                    }
                }
        }
    return 0;
    }
    Last edited by robando; 04-12-2015 at 02:27 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help - If statement with multiple conditions
    By trintiin in forum C Programming
    Replies: 3
    Last Post: 02-27-2013, 01:49 AM
  2. if and while conditions
    By firehydrant in forum C Programming
    Replies: 12
    Last Post: 03-05-2011, 03:07 AM
  3. multiple conditions - if statement
    By dibble in forum C Programming
    Replies: 8
    Last Post: 03-28-2009, 12:41 PM
  4. IF statement - to conditions
    By cornacum in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 08:39 PM
  5. If statement conditions
    By Brewer in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:55 AM