Some questions people had in class #19

 

What are the boundaries of if nest statements?

 

In an if-else statement:

if (test > x) {

// statements in if  T

if (test < y) {

            // statements in T then T

} // end boundary for inner if-then

else {

            // statements in T then F

} // end boundary for inner else

}  // end boundary for outer if-then

else {

// statements in else

if (test < z) {

            // statements in F then T

} // end boundary for inner if-then

else {

            // statements in F then F

} // end boundary for inner else

} // end boundary for outer else – and for whole statement

If there are no {}’s for a given branch, then the branch has exactly one statement inside.

 

 

How do you write nested if’s very good?

 

You need to identify all of the different situations (scenarios) that must be handled. Then, you need to determine how your program can determine which one is which. In many situations, what order you handle the different scenarios doesn’t matter, but in some cases it does. You can mentally test your plan by “playing computer” – acting as if you know nothing about the solution and just follow the instructions and see what happens. Use scratch paper if necessary to keep things in your head.  

 

How often are nested ifs used in programming?

 

Very often. Probably not in every program, but in a lot.

 

Does each nested if have to be indented? And if so, will you run out of space to do this on a program?

 

You should indent each unless it is really a multi-branch at the same time “logically” (as opposed to logically a branch, then a branch …  Occasionally space gets to be an issue. This may mean that you code is too complex. Perhaps you can divide the code up into different methods.

 

 

How many levels of nesting can you keep track of?

 

The computer really doesn’t have a limit. The limits come from the programmer’s ability to keep things straight if things get really complicated.

 

What is the difference between if’s and switches?

 

The syntax is significantly different. We will cover switch on Friday. The switch statement directly handles the multi-branch at one place, whereas an if is just a two way branch – which must be worked with to make a multi-way branch if that is what is needed. Another difference, switch tests can only be for = =, whereas if’s can use any operators to build any test (as long as the test returns a boolean result).

 

Could nested if’s be used for sorting out numbers or letters in order?

 

To do this practically, where there are more than a few values, you really need to be driven by a loop – which will repeatedly do some if’s.

 

Is nested if’s more efficient than regular if statements?

 

If it saves retesting with a more complicated test , when the info being tested should already be known from the previous test.