Skip to main content

Chapter 4c - More Practice

πŸ‘€ Check

Exercise: Create the following
  • If signal is 1 it prints: Stop your vehicle
  • If signal is 2 it prints Slow down and bring the vehicle to a stop
  • If signal is 3 it prints: Keep driving

πŸ™‹β€β™€οΈ Sample expected program:


(i) What happens if any number other than 1, 2 and 3 is entered? Action in the else block will be executed.


(ii) Is there a way to ensure that an action (to drive / slow down / stop) is taken only if numbers 3, 2, or 1 are entered?


(iii) How can you notify the user if an invald input is entered?



Complete the following code.​

To replacate the behaviour shown in program on the top.`

Automatic Water Sprinkler​

Smart Sprinkler: You want to design a smart sprinkler that decides when to water the yard so as to minimize the use of water. Here are some conditions that determine whether or not your yard needs to be watered:

  • If the temperature is over 90 degrees and it has not rained today

  • If the temperature is between 70 and 90 degrees and it has not rained in the last 2 days.

  • If the temperature is below 70 degrees and it has not rained in the last 3 days.

Take user input for today's temperature, days since it last rained. Based on the user's inputs, your program for the smart sprinkler should output whether or not the smart sprinkler should water the yard today.


πŸ™‹β€β™€οΈ Sample expected program:


Complete the program using the following template.


Try it: traffic light​

Quiz

Traffic light logic

1 / 2

if (signal == 1) { A(); } else if (signal == 2) { B(); } else if (signal == 3) { C(); } else { D(); } β€” what runs when signal is 5?

Pick an answer to see if you are right.


Chapter summary​

Key takeaways
  1. An if / else if / else chain is a great fit whenever a program has to react differently to a small, fixed set of situations (a signal number, a weather condition).
  2. Put a trailing else on chains that read outside input β€” it is your safety net for values you did not explicitly plan for.
  3. Combining boolean conditions with && (and) and || (or) lets one branch cover a rule that depends on more than one fact at once (temperature and days since rain).
  4. Test the edges of your conditions (the boundary between two branches) β€” that is where off-by-one mistakes hide.

Exercises​

Activity: Sprinkler decision

Read the temperature (int) and days since it last rained (int). Print Water the yard if: temp > 90 and days >= 1, OR temp is between 70 and 90 (inclusive) and days >= 2, OR temp < 70 and days >= 3. Otherwise print Skip watering.