Thread: Reading the program/output question

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    34

    Reading the program/output question

    Code:
    int main()
    {
       int x = 5;
       double d = 3.5;
       double y = 2;
    
    while (x > 3)
      {
          printf(“%d\n”, x);
          d += (x % 2);
          x = x – 1;
     }
    
    /* a */
    
       x = d > d ? x : (d / x);
    
       if (x < 1)
         y = x + 3;
       else if (x == 1)
         y = y – x;
    
       if (x == 1)
         y = y * y;
    
    
    /* b */
    return 0;
    }
    Please explain why:

    a) what is the value of x at the spot marked a? - I see it as 4. why is it really 3?
    b) what is the output of the program ?
    5
    4 - why 4?
    c) what is the value of d at the spot marked a? - 4 because it's d +=?
    d) what is the value of x at the spot marked b? why 1
    e) what is the value of y at the spot marked b? why 1
    Last edited by benrogers; 01-26-2011 at 03:38 PM.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    a) Because 4 is bigger than 3. You can't stop the loop if the loop condition is still true.

    c) The answer can't possibly be 4 -- you've got a half-integer to start with (3.5), you're adding integers to it, therefore you will always have a half-integer value for d.

  3. #3
    Registered User
    Join Date
    Jan 2011
    Posts
    34
    c) 4.5 is the answer.

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Your best bet for something like this is to make a table with one column for each variable, and one row per instruction:
    Code:
     x |  d  |  y
    ---+-----+-----
     5 | 3.5 |  2      <-- Initial values, start of program
     5 | 3.5 |  2      <-- x > 3, enter loop
     5 | 3.5 |  2      <-- program prints x (5)
     5 | 4.5 |  2      <-- x % 2 = 5 % 2 = 1, d += 1
    ...
    It's tedious, but a great way to figure out what the computer is doing when it runs your code.

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Code:
       x = d > d ? x : (d / x);
    Under what possible condition can d be greater than d?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question bout my work
    By SirTalksAlots in forum C Programming
    Replies: 4
    Last Post: 07-18-2010, 03:23 PM
  2. Replies: 7
    Last Post: 02-02-2009, 07:27 AM
  3. Question about reading from files
    By green11420 in forum C++ Programming
    Replies: 12
    Last Post: 04-22-2008, 11:02 AM
  4. Replies: 2
    Last Post: 01-28-2008, 03:07 AM
  5. reading data from vector question
    By Rubiks14 in forum C++ Programming
    Replies: 4
    Last Post: 02-26-2006, 10:40 PM