Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In programming there is a structure that allows you to branch your code off to d

ID: 3679766 • Letter: I

Question

In programming there is a structure that allows you to branch your code off to different directions based on a certain condition. This has many names: decision statement, conditional, if-then-else. The format also has several varieties to allow you logic flexibility. For example, you could use if-then for a single branch, if-then-else to allow you to branch in 2 different directions, and also if-then-elseif to branch into other conditions. The use of these all depend on what you are trying to do in your logic. Lets start with the if-then and if-then-else. Give your own example and explanation of how they work.

Explanation / Answer

The if-then statement is the most basic of all the control flow statements and tells your program to execute a certain section of code only if a particular condition is holds true.
For example, the Car class which allow the brakes to decrease the speed only if the car is already in motion. One possible implementation of the applyBrakes method could be as follows:

2. The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the Car is not in motion. In this case, the action is to simply print an error message stating that the Car has already stopped.