You can use the selection structures in this chapter interchangeably for many ci
ID: 3542332 • Letter: Y
Question
You can use the selection structures in this chapter interchangeably for many circumstances. There are a few occasions when one is clearly preferable to another based on input data. Some of these situations were touched on in the switch statement discussion. Review these, give an overview of all of the selection structures discussed in the chapter, and then discuss how to determine which structure to use when there is no clear indication. How much of the choice should be based on personal preference and how much on conventional practices? Are there performance issues as well?
THE SELECTION STRUCTURES IN "THIS CHAPTER" ARE
WHILE
FOR
DO...WHILE
Explanation / Answer
while loops are executed when the initial condition is true. It woud continue looping until the condition becomes false or break is use.
int x=20;
while(x>1){
x--;
}
do while loops are similar to a while loop with the exception that the loop would always be executed once before checking to see if the initial condition is true.
int x=20;
do{
x--;
}while(x>1);
for loop are usually preffered since they work concise code version of a while loop. First statement usually declares a local variable and set its initial value. Second statement is the condition that the loop would continue looping until the statement becomes false. Lastly, the third statement is the statement that usually changes the local variable
for(int x=20;x>1;x--){
}
In general, the while loop is used when you have an exisiting initialized variable which would be checked with the condtion statement before execution. If the variable is not initialized or it is preferred to always enter loop at least once, the do-while loop is preffered. This is seen in "menu" applications where the menu is at least displayed once before a choice is entered. For loops are preffered by conventional practice when there is a finite 'count' of times to loop.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.