<p>I think of a factory where you decide upon requirements which type of object to build:</p>

<pre><code>LuquidsContainer produceByRequirement(String requirement1,String requirement2){
   if("can be closed".equals(requirement1){
      if("keeps temperature".equals(requirement2){
         return new ThermosCan();
      } else {
         return new Bottle();
      }
   } else {
      if("individual use".equals(requirement2){
         return new Glass();
      } else {
         return new Flagon();
      }
   }
}
</code></pre>

CC BY-SA 3.0
2017-07-10T11:40:37.940Z
2017-07-10T11:40:37.940Z
Timothy Truckle
<p>I suppose that a traffic light is a very good example and easy to understand by your target audience.</p>

<pre><code>if (light is green) 
    go
else if (light is yellow) 
    stop and go
else [if (light is red)] 
    stop 
</code></pre>

CC BY-SA 3.0
2017-07-08T19:51:26.690Z
I live in Portugal... Here, this is the meaning of the lights... and we do not have red and yellow at the same time... The braquets mean that what is inside is optional. In the last else you could have an else if (...) or simply the else since there are no aditional options
Nuno Gil Fonseca
CC BY-SA 3.0
2017-07-10T17:25:01.260Z
The website I checked said that Portugal has a red and yellow state. Red, red and yellow, green, yellow, back to red. Is this not the case. Note that my pupils said that this was not true [here in england], but I showed them a video, then set them home work to stare at traffic lights. They said that they were surprised.
ctrl-alt-delor
CC BY-SA 3.0
2017-07-10T18:08:12.920Z
@richard :) Never saw that "red and yellow" scenario... These are the commom traffic lights around here: http://codigo.pt/sinais-de-transito/sinais-luminosos/ (Sorry but it is in portuguese).
Nuno Gil Fonseca
CC BY-SA 3.0
2017-07-08T17:34:32.157Z
2017-07-08T19:53:34.057Z
2017-07-08T19:53:34.057Z
Nuno Gil Fonseca
<p>One of the early examples I usually use is a quadratic equation solver using the quadratic formula. Since many languages don't like that old square root of a negative number thing it's a nice place for a conditional. </p>

CC BY-SA 3.0
2017-07-07T16:12:35.443Z
What would you do if you are about to pass a negative number to a square root function? Do you call it with a positive and assign the result to the imaginary part of the tuple, I think this will be beyond most of my pupils.
ctrl-alt-delor
CC BY-SA 3.0
2017-07-07T16:59:02.213Z
@richard For Year 7 students, you tell them "no solutions". They probably won't be familiar with complex numbers at that stage, unless they're way ahead of their class (they're usually taught in Year 12/13 Further Maths, not to a Year 7 class)
Aurora0001
CC BY-SA 3.0
2017-07-07T16:07:59.910Z
2017-07-07T16:07:59.910Z
Mike Zamansky
<p>There are endless examples that illustrate selection. As you know, most useful programs have at least one selection statement. I've found that some students struggle with the concept, so I start small and pick examples that resonate with students, for example:</p>

<pre><code>    if (hungry)
        System.out.println("Eat a sandwich.");

    if (age &gt; 17)
        System.out.println("You can vote.");
    else
        System.out.println("You cannot vote.");
</code></pre>

<p>For a <em>switch</em> statement, I like to show some type of menu:</p>

<pre><code>    switch(choice) {
    case 0:
        System.out.println("Balance Inquiry.");
        break;
    case 1:
        System.out.println("Transfer");
        break;
    case 2:
        System.out.println("Withdrawal");
        break;  
    case 3:
        System.out.println("Deposit");
        break;          
    default:
        System.out.println("Quit");
        break;          
    }
</code></pre>

CC BY-SA 3.0
2017-07-07T16:19:23.317Z
`choices=("Balance Inquiry.","Transfer","Withdrawal","Deposit","Quit"); print(choices[choice])` [I would not expect my year 7s do do this, but it pains me to give them bad examples], but +1 for the first example, with the `if`s.
ctrl-alt-delor
CC BY-SA 3.0
2017-07-07T16:45:36.457Z
You can easily modify that example: String[] iceCreamChoices = new String[]{"chocolate", "vanilla", "strawberry", "tutti frutti"};
Edwin Torres
CC BY-SA 3.0
2017-07-07T18:12:09.193Z
Please use brackets in if-statements.  For learners the distinction between statements and blocks can be difficult and is a source for subtle bugs even for experienced programmers.
Thorbjørn Ravn Andersen
CC BY-SA 3.0
2017-07-07T16:08:20.900Z
2017-07-07T16:08:20.900Z
Edwin Torres
<p>If you want something very elementary: Write a program that determines the age of a person, where the person's date of birth and the current date are given. For simplicity assume that both dates have already been split into three integer variables.</p>

<p>(The age is the difference of the years minus 1, if the current date comes before the birthday in the calendar, otherwise it's the difference of the years.).</p>

CC BY-SA 3.0
2017-07-10T17:21:34.477Z
I would do it all in liner maths, just adding, subtraction, multiplying, dividing, and rounding. No need for selection. You complicate the problem, when you start thinking that a year has an end. Time is continues.
ctrl-alt-delor
CC BY-SA 3.0
2017-07-11T11:44:03.673Z
@richard Do you mean something like
`int(((10000*y2 + 100*m2 + d2) - (10000*y1 + 100*m1 + d1)) / 10000)`?
That's a hack.
Even though it avoids the conditional, I don't think that this is easier
to understand for an 11 year old.
Uwe
CC BY-SA 3.0
2017-07-07T16:10:31.953Z
2017-07-07T16:10:31.953Z
Uwe
<p>I am an experienced programmer that has just started teaching. I am struggling to see how to introduce selection to my programming classes. None of the examples that I have seen so far are good.</p>

<p>I am struggling to find examples other than the ones below. (These are more advanced than I need.)</p>

<ul>
<li><p>Termination condition for recursion (We don't do recursion until upper years of school, exams do not need it).</p></li>
<li><p>Input validation (Again the exams say don't worry about checking input (I think this is a mistake, as it leads to cowboy programmers)).</p></li>
</ul>

<p>Both of these are only in the syllabus from UK year 12. I am teaching from UK year 7.</p>

<p>Can you help with good examples, and exercises that my younger pupils can use?</p>

<hr>

<p>year 7 is age 11-12
year 12 is age 16-17</p>

CC BY-SA 3.0
2017-07-07T16:09:28.650Z
We always need more good people in this field.  I'm glad you made the switch :)
Ben I.
CC BY-SA 4.0
2021-01-12T07:53:27.403Z
Looking back at this, I don't see why I ✓ed the answer I did. It is not bad, however it is not compelling. It seems to me that ½ of uses of selection both in industry and in education are switching on state that is known at the time the program was written. And most educational examples are contrived: Yes they are simple. Yes they explain selection simply. However they don't explain why, or when to use it. My thoughts are that it is needed for checking inputs. This year, that is what I have been teaching: select on input (not validation, just decide what to do).
ctrl-alt-delor
<branching>
Uses of selection in programming (if, switch etc)
# Uses of selection in programming (if, switch etc)

(Asked by: username_0 on 2017-07-07)

I am an experienced programmer that has just started teaching. I am struggling to see how to introduce selection to my programming classes. None of the examples that I have seen so far are good.

I am struggling to find examples other than the ones below. (These are more advanced than I need.)

* Termination condition for recursion (We don't do recursion until upper years of school, exams do not need it).
* Input validation (Again the exams say don't worry about checking input (I think this is a mistake, as it leads to cowboy programmers)).

Both of these are only in the syllabus from UK year 12. I am teaching from UK year 7.

Can you help with good examples, and exercises that my younger pupils can use?

---

year 7 is age 11-12
year 12 is age 16-17

**Tags:** branching

> **Comments:**
> **username_1**: We always need more good people in this field.  I'm glad you made the switch :)  
> **username_0**: Looking back at this, I don't see why I ✓ed the answer I did. It is not bad, however it is not compelling. It seems to me that ½ of uses of selection both in industry and in education are switching on state that is known at the time the program was written. And most educational examples are contrived: Yes they are simple. Yes they explain selection simply. However they don't explain why, or when to use it. My thoughts are that it is needed for checking inputs. This year, that is what I have been teaching: select on input (not validation, just decide what to do).  

---

## 5 answers

### Answer by username_6 on 2017-07-07. Score: 3 | Accepted answer

There are endless examples that illustrate selection. As you know, most useful programs have at least one selection statement. I've found that some students struggle with the concept, so I start small and pick examples that resonate with students, for example:
    if (hungry)
        System.out.println("Eat a sandwich.");

    if (age > 17)
        System.out.println("You can vote.");
    else
        System.out.println("You cannot vote.");

For a switch statement, I like to show some type of menu:
    switch(choice) {
    case 0:
        System.out.println("Balance Inquiry.");
        break;
    case 1:
        System.out.println("Transfer");
        break;
    case 2:
        System.out.println("Withdrawal");
        break;  
    case 3:
        System.out.println("Deposit");
        break;          
    default:
        System.out.println("Quit");
        break;          
    }

> **Comments:**
> **username_0**: `choices=("Balance Inquiry.","Transfer","Withdrawal","Deposit","Quit"); print(choices[choice])` [I would not expect my year 7s do do this, but it pains me to give them bad examples], but +1 for the first example, with the `if`s.  
> **username_6**: You can easily modify that example: String[] iceCreamChoices = new String[]{"chocolate", "vanilla", "strawberry", "tutti frutti"};  
> **username_7**: Please use brackets in if-statements.  For learners the distinction between statements and blocks can be difficult and is a source for subtle bugs even for experienced programmers.  

---

### Answer by username_8 on 2017-07-07. Score: 2

If you want something very elementary: Write a program that determines the age of a person, where the person's date of birth and the current date are given. For simplicity assume that both dates have already been split into three integer variables.

(The age is the difference of the years minus 1, if the current date comes before the birthday in the calendar, otherwise it's the difference of the years.).

> **Comments:**
> **username_0**: I would do it all in liner maths, just adding, subtraction, multiplying, dividing, and rounding. No need for selection. You complicate the problem, when you start thinking that a year has an end. Time is continues.  
> **username_8**: @richard Do you mean something like `int(((10000*y2 + 100*m2 + d2) - (10000*y1 + 100*m1 + d1)) / 10000)`? That's a hack. Even though it avoids the conditional, I don't think that this is easier to understand for an 11 year old.  

---

### Answer by username_2 on 2017-07-10. Score: 1

I think of a factory where you decide upon requirements which type of object to build:
LuquidsContainer produceByRequirement(String requirement1,String requirement2){
   if("can be closed".equals(requirement1){
      if("keeps temperature".equals(requirement2){
         return new ThermosCan();
      } else {
         return new Bottle();
      }
   } else {
      if("individual use".equals(requirement2){
         return new Glass();
      } else {
         return new Flagon();
      }
   }
}


---

### Answer by username_3 on 2017-07-08. Score: 1

I suppose that a traffic light is a very good example and easy to understand by your target audience.
if (light is green) 
    go
else if (light is yellow) 
    stop and go
else [if (light is red)] 
    stop

> **Comments:**
> **username_3**: I live in Portugal... Here, this is the meaning of the lights... and we do not have red and yellow at the same time... The braquets mean that what is inside is optional. In the last else you could have an else if (...) or simply the else since there are no aditional options  
> **username_0**: The website I checked said that Portugal has a red and yellow state. Red, red and yellow, green, yellow, back to red. Is this not the case. Note that my pupils said that this was not true [here in england], but I showed them a video, then set them home work to stare at traffic lights. They said that they were surprised.  
> **username_3**: @richard :) Never saw that "red and yellow" scenario... These are the commom traffic lights around here: http://codigo.pt/sinais-de-transito/sinais-luminosos/ (Sorry but it is in portuguese).  

---

### Answer by username_4 on 2017-07-07. Score: 0

One of the early examples I usually use is a quadratic equation solver using the quadratic formula. Since many languages don't like that old square root of a negative number thing it's a nice place for a conditional.

> **Comments:**
> **username_0**: What would you do if you are about to pass a negative number to a square root function? Do you call it with a positive and assign the result to the imaginary part of the tuple, I think this will be beyond most of my pupils.  
> **username_5**: @richard For Year 7 students, you tell them "no solutions". They probably won't be familiar with complex numbers at that stage, unless they're way ahead of their class (they're usually taught in Year 12/13 Further Maths, not to a Year 7 class)  

---

