Lesson 7: If-statements Unplugged

Overview

We take a whole lesson to learn about if statements, what they are, the terminology around them, and what they have to do with "selection" in programs. Students trace simple robot programs on paper to develop a sense of how to read and reason about code with if statements in it. Students also try their hand at writing code by hand to handle a robot situation.

Purpose

The activities here get right to many commons misonceptions about how if-statments work and how programs execute. Students may have a simple common-sense intuition about how if-statements work, but there are several ways you can get your wires crossed when considering how programs actually execute. There are two main issues: 1) how the flow of program execution works, and 2) How complex logical statements are composed and evaluated. In this lesson we just address program flow and tracing execution. We'll look at more complex logical expressions later. Even though Boolean expressions show up in this lesson, we try to avoid using that term until the next lesson. For this lesson it's a condition that is simply true or false.

Agenda

Getting Started (5 mins)

If-statements Unplugged (40 mins)

Wrap Up (20 mins)

View on Code Studio

Objectives

Students will be able to:

  • Reason about if-statements by tracing pseudocode programs by hand
  • Write a short program in pseudocode that uses if statements
  • Explain the purpose of if-statements in programs

Preparation

  • Decide whether or not to print the "Will it Crash?" Activity Guide for students (it's ~6 pages, but nice to have on paper. There are digital alternatives, though)
  • Decide how students will review the first two code studio pages - see teaching tips.
  • Budget time: the main activity is working through the problems in the "will it crash?" activity - keep in mind that the last problem ask students to write code which may take time as well.

Links

Heads Up! Please make a copy of any documents you plan to share with students.

For the Teacher

For the Students

Vocabulary

  • Conditionals - Statements that only run under certain conditions.
  • If-Statement - The common programming structure that implements "conditional statements".
  • Selection - A generic term for a type of programming statement (usually an if-statement) that uses a Boolean condition to determine, or select, whether or not to run a certain block of statements.

Teaching Guide

Getting Started (5 mins)

Discussion Goal

Distinguish between events (“when”) and conditional statements (“if”). In everyday conversation, it is common to interchange the words “when” and “if,” as in “If the user presses the button, execute this function.”

In programming event-driven apps, “when” should refer to an event and “if” should refer to a program executing some conditional logic – deciding whether to run some code, based on a boolean condition.

When v. If

  • Most of the programs you've written so far have event handlers that get triggered when certain events occur.
  • But in the last program - the version of "Apple Grab" - we had a very simple if statement that said something like:
  if(count==20){ 
    setScreen("gameOver"); 
  }
  • The introduction of "if" introduces an English language issue for us moving forward. Here is an exmaple:

Prompt:

I'm going to read out loud two sentences that describe a program. With a partner discuss what the difference is between them, and decide which one is "right". Here are the two sentences:

  1. When the button is clicked add one to the score.
  2. If the button is clicked add one to the score.

Give pairs a minute to discuss and then ask which one people think is "right." Get a few opinions out, but don't stop here.

Let's try another one:

  1. When the score reaches 20, set the screen to "game over."
  2. If the score reaches 20, set the screen to "game over."

Give pairs a minute to discuss and then ask which one people think is "right".

Teaching Tip

Don't get too hung up on word-parsing "when" v. "if". This distinction is nuanced and in the long run is actually not hugely important. But it can be a distraction early on because of ambiguities in common English language usage - which is why we draw attention to it here.

As students gain more experience with if statements, the difference between events and if statements will likely become more clear and obvious.

For now, the key idea is that "if" statements are new entity that let us do things we could not do with event handlers.

Discuss

Points to raise during discussion:

  • There is no right answer. In English both pairs of sentences mean basically the same thing.
  • However in programming, using the words "if" and "when" map to some expectations about how the underlying code is written.
  • Here is the difference:

    • "When" is used in reference to an event -- When something happens respond in such and such a way.

    • "If" is used in reference to a decision about whether or not to execute a certain piece of code -- If something is true, then do this, otherwise do that.

  • When describing the behavior of a program events and decisions might get mixed together. For example:

    • "When the button is clicked, if the score is 20 go to 'game over', otherwise add one to the score".

Transitional Remarks

Today's activity focuses soley on if statements.

If the distinction between "when" and "if" is still a little fuzzy, that's okay.

For now, the key idea is that if statements are new entity that let us do things we could not do with event handlers -- writing code to make decsions about whether or not to run some other piece of code.

If-statements Unplugged (40 mins)

"Will it crash?" Activity

Distribute: Will it Crash? - Activity Guide

  • Put students in partners
  • Review the rules and do the first example together (if necessary)
  • Partners should work together to trace and reason about the code.

Compare results

  • Put groups together to review the ending state and position of robots for each scenario.
  • If there are disagreements about the end state, have pairs work it out and re-trace the examples.
  • If there are common problems, save them, and review in the wrap-up

Teaching Tip

The last problem asks students to write some code by hand, and requires some time and thought. You might consider giving it for homework.

Write code for the last problem and exchange

  • Partners can work on writing the code together
  • When done, have groups exchange code and trace the other team's work to verify correctness or reveal problems.

Wrap Up (20 mins)

What was trickiest?

If there were common problems that students had trouble with be sure to review those.

Prompt:

  • Were you tripped up by any of the problems? Which ones? Why?
  • What's the difference between a seqeunce or series of if statements versus an if-else statement?

Discussion

Points to raise during discussion:

  • If-statments and conditional expressions are huge part of programming and we're going to spend some time digging in with them.
  • There are two main issues to concern yourself with when it comes to if-statements and today we've looked a lot at one of them, namely, program flow and order of execution.
  • For example, one very common misconception, or place where people get tripped up is, in the difference between a sequence of if-statements, and using an if-else statement.

Algorithms and Creativity

Review: Together read the summary of algorithms found in the last level of this lesson. Note this is a longer explanation of algorithms.

Remarks

It's likely that solutions to the last problem varied considerably. Point this out as a positive.

  • Programming is a creative activity.
  • When you are planning a solution to the problem, you are thinking about algorithms

Prompt:

  • How many different coding solutions to the last problem were there?
  • Why are different solutions possible?

Discussion

Points to raise during discussion:

  • There are multiple correct solutions
  • This is because there are multiple ways to think about the problem
  • There are also multiple algorithms for solving it
  • Even if you used the same algorithm, the code might be different.
  • All of this demonstrates that programming is a creative activity.

Remarks

Next we'll look at writing if statements in JavaScript, and also dive into understanding conditional expressions a little more deeply

  • Big Picture: if-statements
  • 2
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Teaching Tip

Review this as a class and: point out the key idea have students read the annotations in the pseudocode documentation.

The important part here is to familiarize students with AP Pseudocode for if-statements and the robot commands.

Some of the terminology can be reviewed later by students.

Student Instructions

Big-Picture: If-statements

Word Soup: If-statements, Conditionals, Selection

  • If-statements exist so that your program can adapt, respond, or make choices about whether or not to execute certain portions of code based on some condition that you check while the program is executing.

  • Because it involves checking conditions, these statements are sometimes called conditional statements, or sometimes just conditionals.

  • A conditional statement (if-statement) requires a conditional expression, something that is either true or false and it's what an if-statement uses to decide whether or not to execute a certain portion of code.

  • A generic term used by the AP CSP Framework for this is Selection. As in: your program can select whether or not to run certain blocks of code.

Key Idea: If-statements are how programs adapt and respond to conditions on the ground.

The whole point is to be able to handle cases where you can't know ahead of time whether or when certain conditions will exist in your program. So you have to write code to say something like: "Okay, at this point in the program, if such and such is true, then do this, otherwise do that."

Practice with the AP Pseudocode

For the activities that follow, we're going to get our feet wet with if-statements using the AP CS Principles pseudocode language. To start we're going to use the IF/ELSE structures, but to keep things simple we'll only use the Robot conditional expression CAN_MOVE (direction) - which evaluates to true or false.

Below is the official documentation for Selection and Robot statements along with some extra commentary.

View as a separate document: Annotated Pseudocode - If-statements and Robot

  • Worked Example: if-statements and Robot
  • 3
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Teaching Tip

Again, this page is largely meant as reference.

You don't need to belabor the points here, as students will get much more practice with the "Will it crash?" activity.

Remind students that this is here if they need to refer back to it when doing the next activity.

You have a few options for how to review this worked example:

  • You may want to review this worked example as an entire class, projecting it on the screen.
  • Have students read, individually, or in pairs, then follow up with a partner, or review questions.
  • You may want to print - though it is a long-ish document to print, especially since the "will it crash" handout is long as well.

Don't miss the problem at the very end of the document. Students should try it and you can review as a class to verify that they understand.

Student Instructions

A Worked Example

The following shows a step-by-step, line-by-line execution of a 10-line program with if-statements that uses the AP pseudocode for if-statements and the robot.

The purpose of the example is to show:

  • Code executes one line at a time from top to bottom.
  • Each if-statement condition is checked in the order of execution
  • The conditions of later if-statements may be affected by what did, or didn't happen, in earlier lines of code.

View the above as a separate document: Worked Example - If-Statements and Robot

Before clicking continue:

  • Make sure you understand each step of the example
  • Have tried out the last one on your own? and compared results with a classmate?
  • Algorithms in Programming
  • 4
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

How to use this level

This level has a lot of text. Ways you might use it / incorporate it into your class:

  • Assign as reading for students the day before
  • Have students stop at this level during the normal progression and read as a group - discuss key points.
  • Read and summarize for your students
  • Make note of it as a reference for students that explains "algorithms"
  • Use in conjunction with a preview of the AP Create Performance Task

Student Instructions

Algorithms - Solving Problems

What is an algorithm?

Definition

An algorithm is a precise sequence of instructions for a process that completes a task. Algorithms can be executed by a computer and are implemented using programming languages.

By asobuno (Own work) [CC BY-SA 3.0], via Wikimedia Commons By Clem Rutter, Rochester, Kent. (self) [GFDL or CC BY 3.0], via Wikimedia Commons

Automating Physical Tasks

Physical Tasks in Daily Life

Daily life is filled with tasks. Most mornings, for example, you'll need to get dressed, pack your things, and then travel from one place to another. Your day at work or school will be filled with tasks to complete. Even keeping up with friends, relaxing, or going to bed includes some tasks if you look closely.

Automating Tasks

We want to complete most tasks quickly, easily, and reliably. One important way we do this is by identifying step-by-step processes that we know work well. The steps to tie your shoes or the steps of a recipe are examples of processes we use to help us effectively take care of everyday tasks.

Processes to complete tasks are powerful because not only can humans use them, so can machines. Automation is the use of machines to complete some task with little to no human intervention, and from agriculture to manufacturing to transportation, it has transformed our society, economy, and daily lives.

Automation Requires Algorithms

At the heart of automation is a well-defined step-by-step process that the machine is completing. A machine to weave cloth, for example, is built to make stitches in a precise way in a precise number of rows using a precise number of threads. In other words, automating a tasks means first identifying the process or algorithm your machine will complete. Often a human could use that same algorithm to complete a task, but the machine will typically do so more quickly, easily, and reliably.

Algorithms and Information Tasks

Information Tasks and Tools

Many tasks don't require physical work, but they do require thinking. For example, you might need to keep track of money, remember birthdays, or schedule activities. At their core these problems have to do with how we organize and make sense of information. Tools like calendars, clocks, and financial records help us complete these information tasks.

Automating Information Tasks

Just like physical tasks, many information tasks can be completed using algorithms. For example when you learn the steps to add or multiply two numbers, you're really just using an algorithm for addition or multiplication. The recognition that information tasks could be described algorithmically led to the desire to automate these tasks as well, and eventually, to the creation of the computer.

Algorithms, Programming, and Computer Science

The Everything Machine

Through history machines to automate information tasks usually did only one thing. A machine could track stars in the sky, or add numbers, but couldn't do both. By comparison, a single modern computer can add numbers, show video, communicate over the Internet, and play music. This is clearly a very different type of machine!

Everything is Numbers

Many important ideas led to the design of the modern computer. First was the realization that most information can be represented as numbers. In fact, you learned in Units 1 and 2 that text, images, sound and many other pieces of information you can dream up can be represented in some way as binary numbers. This means information problems can be represented in a standardized way.

Simple Commands

The next important realization is that information processes can be broken down into a common set of very simple commands. For example those steps might be adding or subtracting two numbers, moving information from one place to the next, or comparing two numbers. Even complex information processes like sorting a list of 1,000,000 names or determining if a picture has a cat in it can be represented on some level as a sequence of these simple commands.

People Write Algorithms for Computers

Together these two ideas allow information tasks to be standardized to a degree that a single machine (a computer) could be designed to complete many of them. In order for this to work a computer is first designed to do this small set of low level commands. Next, and most importantly, the computer is designed to let a human being write out their own sequence of commands to control the machine to complete the task at hand. Said another way, a computer is a machine that's designed for a human to write algorithms for it to run!

Algorithms and Creativity

Sequence, Selection, Iteration

Any programming language only provides so many commands. Algorithms are created by combining these instructions in three ways. In fact, using these three you can describe ANY algorithm completed by a computer. Those three ways are:

  • Sequence: This is placing commands in an order. When you write a program that runs line by line you are defining the order in which a computer should run the fundamental commands that it understands.

  • Selection: This is when a computer chooses to run one of two or more sections of code. When you use an if-statement you are making use of selection.

  • Iteration: This is when a computer repeats a section of code. For example you can do this by using a loop.

Algorithms, Programming, and Creativity

Even with the limited commands a computer understands and the limited ways you can combine them, there are actually many, conceivably infinite, ways to write a program to complete a task. Some may be more efficient or easier to understand than others, but there is typically no single "right" algorithm to complete a task. There also isn't an "algorithm for writing algorithms". You need to investigate and understand the problem you are trying to solve, and then get creative with how you'll combine the tools the programming language provides you. Computer science is a creative discipline because computers literally require human creativity to do anything at all!

Algorithms, Unit 5, and the AP Exam

Algorithms and AP Computer Science Principles

(1) Algorithms is one of the seven big ideas of AP Computer Science Principles.

(2) For the AP Create Performance Task you need to...

[identify] a code segment that contains an algorithm you developed...[and]...explain how the algorithm helps achieve the purpose of your program.


Standards Alignment

View full course alignment

Computer Science Principles

4.1 - Algorithms are precise sequences of instructions for processes that can be executed by a computer and are implemented using programming languages.
4.1.1 - Develop an algorithm for implementation in a program. [P2]
  • 4.1.1A - Sequencing, selection, and iteration are building blocks of algorithms.
  • 4.1.1C - Selection uses a Boolean condition to determine which of two parts of an algorithm is used.
4.1.2 - Express an algorithm in a language. [P5]
  • 4.1.2A - Languages for algorithms include natural language, pseudocode, and visual and textual programming languages.
  • 4.1.2B - Natural language and pseudocode describe algorithms so that humans can understand them.
  • 4.1.2G - Every algorithm can be constructed using only sequencing, selection, and iteration.
5.2 - People write programs to execute algorithms.
5.2.1 - Explain how programs implement algorithms. [P3]
  • 5.2.1A - Algorithms are implemented using program instructions that are processed during program execution.
  • 5.2.1B - Program instructions are executed sequentially.
  • 5.2.1D - An understanding of instruction processing and program execution is useful for programming.

CSTA K-12 Computer Science Standards (2017)

AP - Algorithms & Programming
  • 3A-AP-15 - Justify the selection of specific control structures when tradeoffs involve implementation, readability, and program performance and explain the benefits and drawbacks of choices made.