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 will also try writing code by
hand to handle a robot situation.
Most of the programs that students have written so far include "event handlers"
that get triggered when certain events occur. In Lesson 5, they created a
"Counter" program that either incremented or decremented the "count" depending on which key was pressed.
In this lesson students will gain an understanding of the
"if-statement structures" that were provided in the template of the
"Counter" program. We will review the concept of "if-statements"
much closer so that students can construct their own "if-statement structure" for use in their programs.
- 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.
- Pseudocode: Expressions that are similar to a programming language, yet they do not follow the strict syntax rules of any programming language. Pseudocode is often used in the development process to easily examine the flow of the program.
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
- Understand the computer's decision making process which leads to the concept of "Algorithms"
The activities here get right to many common misconceptions
about how if-statements 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 address program flow and tracing execution. We'll review 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.
When vs. If
- Most of the programs you've written so far have event handlers that get triggered when certain events occur.
- In Lesson 5 we had an if-statement that started and ended something like this:
if event:keyCode = event:UP
counter = counter + 1
- The introduction of "if" introduces an English language issue for us moving forward.
Prompt: I'm going to read two sentences out loud 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:
- When the button is clicked add one to the score.
- If the button is clicked add one to the score.
Give students a minute to discuss with their partner and then ask which one people think is "right." Get a few opinions out, but don't stop here.
Let's try another one:
- When the score reaches 20, output "game over."
- If the score reaches 20, output "game over."
Give students some time to discuss with their partner before asking which one people think is "right."
Discuss: Points to raise -
- 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."
Today's activity focuses on if-statements. If the distinction between "when" and "if" is still a little fuzzy, that is okay.
For now, the key idea is that if-statements are a new entity that let us do things we could not do with event handlers -- writing code to make decisions about whether or not to run some other piece of code.
Big Picture: If-statements:
- 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 this conditional expression is 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 cannot 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."
For the activity 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. Use the "Annotated Pseudocode" worksheet and "Worked Example" worksheet for reference when writing your own pseudocode for your robot. The purpose of the Worked Example is to show that:
- 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.
You may want to review the worked example as a class, or you can have students read (individually or in pairs) and then follow up with a partner.
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.
Teacher’s Tip: Activity Template
We have included an enlarged template of the diagram below for those who may have difficulty using the template provided in the activity guide. If you have access to a Tactile Image Enhancer, the template could be copied onto the heat sensitive paper. This activity could alternatively be done on any platform that has 5 by 5 grid structure.
- Put groups together to review the ending state and position of the robot 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.
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.
Each "if structure" has its own "end". Keeping each if-statement at the same indentation level as its end is important for acheiving readability within the code, especially when we begin using "nested if-statements" as shown below:
if (Indentation Level 1)
if (Indentation Level 2)
doThis(Indentation Level 3)
else (Indentation Level 2)
doThat(Indentation Level 3)
end (Indentation Level 2)
else (Indentation Level 1)
doNothing(Indentation Level 2)
end (Indentation Level 1)
What was trickiest? If there were common problems that students had trouble with be sure to review those.
- 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?
- If-statements and conditional expressions are a 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 reviewed 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 - Solving Problems
What is an algorithm? 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.
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 consider them 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 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
Any programming language only provides so many commands. Algorithms are created by combining these instructions in three ways. In fact, using these three methods 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 repeat construct.
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
- "Algorithms" is one of the seven big ideas of AP Computer Science Principles.
- 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.
Programming is a creative activity. When you are planning a solution to a problem you are thinking about algorithms.
- How many different coding solutions were there for the last problem in the "Will It Crash" activity?
- Why are different solutions possible?
- 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.
- Computer Science Principles: 4.1.1(A, C)
- Computer Science Principles: 4.1.2(A, B, G)
- Computer Science Principles: 5.2.1(A, B, D)