Thread: Simple C programming question confused

  1. #1
    Registered User
    Join Date
    Jan 2016
    Posts
    24

    Simple C programming question confused

    Hi, I'm having trouble understanding the answer to this question. What is the value of x after this code?
    int x = 1;
    if (x == 1)

    x = x + 1;
    else

    x = x + 3;
    x = 3 * x;

    So if I am understanding this correctly, initially x=1, it goes through the if loop and checks if x is 1, if it is, then the new x is equal to 1+1=2. but i am confused on the else part. Can someone please explain to me what happens? Thank you.

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Your understanding of the "if()" part is correct. The "else" will not occur unless the "if()" condition is false (which it will not be in the given example).

    I would suggest you try compiling and running this code to see what the actual output will be, using different values for "x". See if the output is what you expect.

    Also note that "if()" is not a loop.

  3. #3
    Registered User
    Join Date
    Jan 2016
    Posts
    24
    ok so after the if statement the new x becomes 2? and then it goes through the if statement again. This time the if statement is false, so it goes to the else statement and x=2+3=5, and then the statement would be x=2*3=6?

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    As I said, the "if()" statement is not a loop, so in the code you posted, it is only executed once.

    Also be aware that the last line is not part of the "if-else", so that line is always executed.

    In fact, this is what the code should look like with proper indentation, to emphasize the flow of logic:

    Code:
    int x = 1;
    
    if (x == 1)
        x = x + 1;
    else
        x = x + 3;
    
    x = 3 * x;

  5. #5
    Registered User
    Join Date
    Jan 2016
    Posts
    24
    thank you for your clarification! i get it now, so since x=1 the if statement evaluates true then x=1+1=2. so it won't even go through the else statement. therefore, x=3*2=6 after these lines of code. thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple programming question
    By angelz528 in forum C Programming
    Replies: 2
    Last Post: 06-03-2015, 02:33 PM
  2. C programming -simple question
    By 0skull0 in forum C Programming
    Replies: 5
    Last Post: 04-03-2014, 07:26 AM
  3. Simple C programming question
    By Boxo in forum C Programming
    Replies: 3
    Last Post: 03-27-2010, 09:44 PM
  4. <( ' '<) Simple Programming Question?
    By strigen in forum C Programming
    Replies: 1
    Last Post: 03-05-2009, 03:17 PM
  5. Simple Qt Programming Question
    By Reisswolf in forum Linux Programming
    Replies: 1
    Last Post: 05-23-2006, 01:26 PM

Tags for this Thread