Thread: Basic C programming explanations?

  1. #1
    Registered User
    Join Date
    Sep 2013
    Posts
    13

    Basic C programming explanations?

    Hello I had some questions for a quiz that I got wrong cause I was confused on them. Would anyone please be kind enough to tell me why each code outputs what it does?

    1.
    Code:
    int a=13, b=5;
    if (3 < a < 10) 
    printf("A");
    b = 2*a; 
    printf("%d", b);
    

    shouldn't this just output 26 since 13 isn't less than 10?

    2.
    Code:
    
    
    Code:
    int a=8;
    if (a = 5) { 
    printf("A"); 
    } 
    else 
    printf("B"); 
    printf("%d", a);
    

    shouldn't this just output B due to 8 not being equal to 5?
    3.
    Code:
    
    
    Code:
    int a=3, b=8;
    if (a > 3)  
    if (b < 5)  
    printf("A"); 
    else  
    printf("B"); 
    printf("C");
    

    why doesn't this output both b and c?






  2. #2
    11DE784A SirPrattlepod's Avatar
    Join Date
    Aug 2013
    Posts
    485
    Code:
    int a=13, b=5;
    if (3 < a < 10) 
    printf("A");
    b = 2*a; 
    printf("%d", b);
    


    the expression 3 < a < 10 is equivalent to (3 < a) < 10 and therefore if a is 13, then (3 < 13) < 10 ==> 1 < 10 ==> 1 (true) so the if statement true. The output would be A26

    Code:
    int a=8;
    if (a = 5) { 
    printf("A"); 
    } 
    else 
    printf("B"); 
    printf("%d", a);
    


    Consider:
    Code:
    if (a = 5) { // This is assigning 5 to a, and similar to the previous explanation if(5) evaluates to true so the output would be
    Code:
    A5
    


    Code:
    int a=3, b=8;
    if (a > 3)  
    if (b < 5)  
    printf("A"); 
    else  
    printf("B"); 
    printf("C");
    


    fixing indentation:
    Code:
    int a=3, b=8;
    if (a > 3)  
        if (b < 5)  
            printf("A"); 
        else  
           printf("B"); 
    printf("C");
    


    Now it can clearly be seen that only "C" will be printed because the first conditional is false


    Last edited by SirPrattlepod; 09-18-2013 at 09:05 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with my basic c programming
    By chris199236 in forum C Programming
    Replies: 15
    Last Post: 09-25-2012, 09:23 PM
  2. Replies: 9
    Last Post: 06-21-2012, 05:17 PM
  3. Need explanations...
    By adnilsah017 in forum C Programming
    Replies: 2
    Last Post: 06-06-2011, 03:34 AM
  4. c++ definitions and explanations help
    By yosimba2000 in forum C++ Programming
    Replies: 10
    Last Post: 06-27-2010, 03:28 AM
  5. basic C-programming Q
    By slyonedoofy in forum C Programming
    Replies: 2
    Last Post: 10-30-2002, 09:54 PM

Tags for this Thread