I have this problem with given answer but don't understand why. May someone help explain? Thanx

if (x>5)
y=1;
else if (x<5)
{
if (x<3)
y=2;
else
y=3;
}
else
y=4;
-----------------
what is the value y if x=3?
answer was: y=3

This is a lot easier if you indent the code so you can see which else goes with which if:

if (x>5)
  y=1;
else 
  if (x<5) {
    if (x<3)
      y=2;
    else
      y=3;
    }
  else
    y=4;

for full ...

if (x=>5)
   y=1;
else
  if (x<5) {

or

if (x>5)
   y=1;
else
  if (x<=5) {

This was one of the problem in my quiz on paper. I still don't understand why y=3 was the answer. May you break them up like a math lay-out in your explanation? Thanx

if (x>5)        // false
  y=1;          // not executed
else            // executed (matching if is false)
  if (x<5) {    // true
    if (x<3)    // false
      y=2;      // not executed
    else        // executed (matching if is false)
      y=3;      // executed 
    }
  else          // not executed (matching if is true)
    y=4;        // not executed

Thank you JamesCherrill & mKorbel.

???? as I hate that semaphores

if (number > 5) {
            System.out.println("more then five");
        } else if (number == 5) {
            System.out.println("equals five");
        } else if (number == 4) {
            System.out.println("equals four");
        } else if (number == 3) {
            System.out.println("equals three");
        } else if (number == 2) {
            System.out.println("equals two");
        } else if (number == 1) {
            System.out.println("equals one");
        } else if (number == 0) {
            System.out.println("equals zero");
        } else if (number < 0) {
            System.out.println("less than zero");
        } else {
            System.out.println("Something wrong happends");
        }

@tracydo: if your question is now fully answered, please mark this thread as "solved".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.