• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Program problem

mOeeOm

Platinum Member
21. For what exact range of values of variable x does the following code segment
display the letter `C'?
(a) 0 < x < 100
(b) x <= 0
(c) 100 <= x <= 200
(d) x > 200
(e) 100 < x <= 200

A question from a sample midterm I have, this question is confusing me. The code is attached for this one.

So if x < 200 it will print A, but if its below 100 it will print B, so it has to be between 100 and 200 so the answer is e to print C?

Edit: Another question

22. The e®ect of the following program segment can best be described as .
if (x > y)
z = x;
if (x == y)
z = 0;
if (x < y)
z = y;
(a) The smaller of x and y is stored in z.
(b) The larger of x and y is stored in z unless x and y are equal, in which case
z is assigned zero.
(c) The larger of x and y is stored in z.
(d) The larger of x and y is stored in z unless x and y are not equal, in which
case z is assigned zero.
(e) none of the above

if x is greater than y, then x is stored in z, so the answer is c?

Thanks for any help.
 
OK, question 1. You are close, but incorrect. You might find it easier to understand if you put some brackets in:

if (x <= 200) {

if (x < 100) {

if (x <= 0) {
printf("A\n");
}
else {
printf("B\n");
}

}
else {
printf("C\n");
}

}
else {
printf("D\n");
}

Now work through to get to printf("C\n");

x<=200 so we enter the first 'if' branch. x>=100 so we don't enter the second 'if', instead go to the appropriate else statement, which is printf("C\n"); The end.

Therefore for 100<=x<=200 the program will print 'C'.


Question 2.

if x is greater than y, then x is stored in z, so the answer is c?

You would be correct if you were only considering the first line, but you must look at the whole program segment. Read it out loud or write it down again, possibly with brackets and formatting. Pick values for x and y then run through it on paper and post what you come up with.

I'm not going to give you the whole answer for this one as it's quite the easy question. You should be able to do this.


/Edit: Ok, it removed all my spaces in the code, but you get the idea.
 
Back
Top