Back

Activity 1.12: Making Decisions

divider

Activity 1.12

Making Decisions

Key Concepts

Running Code Only Sometimes

The Other Path

A Condition Must Be a Question

Selection

Every Program You Have Written Ran Every Line

Top to bottom, every single time. Nothing was ever skipped, and nothing was ever chosen.

Today that changes, and it is the biggest step the course has taken so far.

Every Program You Have Written Ran Every Line

Activity 1.11 gave you comparisons that produce true and false. You stored them and printed them, and that was all they did.

Those booleans were built to be used here. This is what they were for.

if Makes a Block Optional

int temperature = 31;
if (temperature > 30)
{
Console.WriteLine("Heat warning.");
}
Console.WriteLine("Report complete.");

if Makes a Block Optional

temperature is 31
Heat warning.
Report complete.
temperature is 18
Report complete.

Same program, two different outputs. The last line ran both times — only the block inside the braces was skipped.

Three Things to Read in That Shape

  • The condition in the parentheses has to be something that is already true or false
  • The braces mark exactly which lines are optional
  • Everything outside the braces runs no matter what

Miss the third one and you will spend an hour wondering why a line you thought was part of the decision keeps printing.

else Supplies the Other Path

int age = 12;
if (age >= 13)
{
Console.WriteLine("Access granted.");
}
else
{
Console.WriteLine("Access denied.");
}

else Supplies the Other Path

Terminal window
Access denied.

Exactly one of the two blocks runs. Never both. Never neither.

else has no condition of its own, because it does not need one. It means “in every other case.”

A bool Is Already a Condition

bool isRaining = true;
if (isRaining)
{
Console.WriteLine("Take an umbrella.");
}

A bool Is Already a Condition

Terminal window
Take an umbrella.

No comparison needed. isRaining is already true or false, which is the whole of what a condition has to be.

Writing if (isRaining == true) asks whether true equals true. It works, and it is noise. This is why naming booleans as questions pays off.

C# Will Not Guess What You Meant

int fuelPercent = 12;
if (fuelPercent)
{
Console.WriteLine("Fuel!");
}

A fuel level is a number, not a question.

C# Will Not Guess What You Meant

Terminal window
1-12-launch.cs(3,5): error CS0029: Cannot implicitly convert type 'int' to 'bool'
The build failed. Fix the build errors and run again.

Some languages treat any non-zero number as “true enough” and run the block. C# refuses to build. A condition must be a bool and nothing else.

CS0029 again — the same error from Activity 1.8 and Activity 1.11, arriving in a third place.

The One C# Lets Through

bool isLaunchReady = false;
if (isLaunchReady = true)
{
Console.WriteLine("Cleared for launch.");
}
else
{
Console.WriteLine("Hold.");
}
Console.WriteLine($"Ready: {isLaunchReady}");

One equals sign, inside a condition, on a variable that starts out false.

The One C# Lets Through

Terminal window
1-12-launch.cs(3,5): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?
Cleared for launch.
Ready: True

That is a warning, not an error, and the program ran. It printed the launch clearance for a vehicle that was not ready.

isLaunchReady = true put true into the variable and then handed that true to the if. The condition could not have come out any other way — and the variable is now permanently changed.

Read CS0665 Out Loud Once

“Assignment in conditional expression is always constant; did you mean to use == instead of = ?”

The compiler worked out what you probably meant and told you so. It still built the program, because assigning inside a condition is legal C#.

Activity 1.11 said = and == do unrelated jobs. This is the place where getting them backwards costs you a wrong answer instead of a build error.

You Have Just Learned Selection

Choosing between paths is called selection, and it is one of the three building blocks every algorithm is made of.

You already had sequencing — one statement after another, which is every program you wrote before today. Selection is the second. The third arrives in Activity 1.17.

The exam expects you to name all three and say what each one lets a program do.

Today's Objectives

  • Running a block of code only when a condition holds
  • Supplying the alternative path with else
  • Using a bool variable directly as a condition
  • Explaining why a condition in C# must be a bool
  • Naming selection as an algorithm building block

Key Terms

Selection
Choosing which code to run based on a condition.
Condition
The boolean expression that decides which path is taken.
Block
The group of statements inside a pair of braces.
Sequencing
Running statements one after another, in order.

'F' → Fullscreen

divider

Build

Everything today goes in a new program named 1-12-launch.

How to read the code blocks. Each task's code block shows your whole program, from line 1, as it should look when that task is finished.

You never start a new file and you never delete your work. The green lines marked with a + are the ones you add or change for that task — everything else is already in your file. Do not type the + sign.

Where a block shows only comments, you write that code yourself. The comments stay in your file.


Task 1: One Optional Line

  • Write the code below and run it. The warning should appear.
  • Change fuelPercent to 80 and run it again. The warning should vanish — but Check complete has to print both times. If it does not, your last line is inside the braces.
  • Set it back to 12 before you continue.
  • Note the indentation: the brace lines up under the if, and the line it controls is indented four spaces. C# does not require this. Your reader does.
1-12-launch
int fuelPercent = 12;
Console.WriteLine($"Fuel: {fuelPercent}");
if (fuelPercent < 20)
{
Console.WriteLine("WARNING: fuel low.");
}
Console.WriteLine("Check complete.");

Task 2: Two Decisions, Both With Alternatives

  • Add an else to the fuel check, then a second decision for the crew count.
  • Run all four combinations by editing the two numbers: low fuel with a full crew, low fuel with a small crew, good fuel with a full crew, good fuel with a small crew.
  • Write down the four outputs. Two decisions with two paths each is four possible runs, and you should be able to produce every one of them on purpose.
  • Set the numbers back to 12 and 7 before you continue.
1-12-launch
int fuelPercent = 12;
int crewCount = 7;
Console.WriteLine($"Fuel: {fuelPercent}");
if (fuelPercent < 20)
{
Console.WriteLine("WARNING: fuel low.");
}
else
{
Console.WriteLine("Fuel level nominal.");
}
Console.WriteLine($"Crew: {crewCount}");
if (crewCount >= 5)
{
Console.WriteLine("Full crew aboard.");
}
else
{
Console.WriteLine("Running short-handed.");
}
Console.WriteLine("Check complete.");

Task 3: Plan, Then Decide on Input

  • The three comments describe a cargo check. Write the code under them, leaving the comments where they are.
  • Convert the input before you compare it. Activity 1.11 showed you what happens if you forget — C# will not compare text to a number at all.
  • The approval message has to show the mass. The refusal does not need to.
  • Test both paths before you submit — once with a mass over 500, once under. A branch you never ran is a branch you have not checked.
1-12-launch
int fuelPercent = 12;
int crewCount = 7;
Console.WriteLine($"Fuel: {fuelPercent}");
if (fuelPercent < 20)
{
Console.WriteLine("WARNING: fuel low.");
}
else
{
Console.WriteLine("Fuel level nominal.");
}
Console.WriteLine($"Crew: {crewCount}");
if (crewCount >= 5)
{
Console.WriteLine("Full crew aboard.");
}
else
{
Console.WriteLine("Running short-handed.");
}
Console.WriteLine("Check complete.");
Console.WriteLine();
// Ask the user for a cargo mass and convert it to a whole number
// If the mass is over 500, refuse the launch
// Otherwise approve it, and show the mass in the message

Task 4: Break It on Purpose

Three more runs of your finished program. Write down exactly what happens each time, copied from the screen, and change each one back before you try the next.

  1. Change the cargo comparison to just the variable: if (cargoMass). Try to run it.
  2. Put the comparison back. Now add a line above the cargo check that declares bool isHeavy = false;, and change the check to if (isHeavy = true). Run it and enter a mass of 100.
  3. Change that one equals sign to two — if (isHeavy == true) — and run it again with a mass of 100. Then run it once more with a mass of 9000 and write down what it says.

For each one, record the error code — something like CS0029 — or the warning code, and the line number it names.

One of these never ran. The other two both ran, and neither of them ever looked at the cargo mass. Number 2 refuses every load. Number 3 approves every load — which is why 100 kg looked fine and 9000 kg did not.

Say how a person reading only the 100 kg output could have caught number 2, and why the same person would have had no way at all to catch number 3.


Challenge (Optional): The Boundary

  • Your cargo check uses “over 500.” Run it with exactly 500 and write down which path it took.
  • Change the comparison from > to >= and run it with exactly 500 again.
  • Write a comment saying which version you think is right for a cargo limit, and why. There is a defensible answer either way — what matters is that you picked one on purpose rather than finding out later which one you happened to type.
divider

Same Idea, Exam Notation

C#
if (score >= 60)
{
Console.WriteLine("Pass");
}
else
{
Console.WriteLine("Fail");
}
Exam Notation
IF(score ≥ 60)
{
DISPLAY("Pass")
}
ELSE
{
DISPLAY("Fail")
}

Look at the shape before you read the words. The braces sit in the same places in both, and else is on a line of its own in both. That is not a coincidence — this course writes C# the way the reference sheet writes pseudocode, so you are learning one layout instead of two.

Only two things actually differ:

  • IF and ELSE are capitalized.
  • There is no space before the parenthesis — IF(condition), not IF (condition).

The condition itself uses the operators from Activity 1.11: ≥ rather than >=, and a single = where C# needs ==.

What is missing from the reference sheet matters too. There is no ELSE IF anywhere in the exam notation.

C# has one, and you will meet it next activity. Activity 1.13 is about what the exam notation does instead — and about why the shape it forces you into is worth seeing before you reach for the shortcut.

divider

Aside: Where Does a Block End?

Today is the first time your code has had a block in it, so it is worth knowing that every language has to answer one question: where does this block stop? Nothing about the answer is obvious, and the people who designed these languages did not agree.

C# — brace on its own line
if (score >= 60)
{
Console.WriteLine("Pass");
}
else
{
Console.WriteLine("Fail");
}
C# — brace on the same line
if (score >= 60) {
Console.WriteLine("Pass");
} else {
Console.WriteLine("Fail");
}
Python — indentation
if score >= 60:
print("Pass")
else:
print("Fail")
Lua — the word end
if score >= 60 then
print("Pass")
else
print("Fail")
end

All four programs do exactly the same thing. The first two are the same language, and only the position of one character changed. Python throws the braces away and uses the indentation you were going to write anyway. Lua, and Ruby, and old versions of BASIC, spell the end of a block as a word.

This course writes the first one, with the brace on its own line. Two separate reasons point the same way here, which is not usually how style arguments go: it is what the exam reference sheet does, and it is also the ordinary convention for C# itself — Visual Studio formats your code that way by default, and Microsoft's own documentation is written in it.

You will still meet the second one constantly, just not in C#. It is the dominant style in JavaScript, Java, C, and C++, so a great deal of the code you find online looks like that. Read it without flinching. To the compiler the two are identical; a machine reading your code does not care where the newlines are.

Worth knowing why anyone argues about it. Braces on their own lines put every opening and closing brace in the same column, so a missing one is easy to spot — which is exactly the error you are most likely to make this week. Braces on the same line fit more code on a screen. Python's answer ends the argument and starts a different one, because now an invisible character — a space — changes what your program does.

divider

Checkpoint

Your finished program should run like this.

Example Output
Fuel: 12
WARNING: fuel low.
Crew: 7
Full crew aboard.
Check complete.
Cargo mass? 620 [Enter]
LAUNCH REFUSED: cargo too heavy.
  • Check complete prints on every run, whatever the fuel level is.
  • You can produce a run where the fuel line says nominal, the crew line says short-handed, and the launch is approved. If any one of those cannot happen, that branch has a problem.
  • You have all four Task 2 combinations written down.
  • You have run the cargo check with a mass over 500 and under it.
  • All three Task 4 results are written down, with their error or warning codes and line numbers, including the 9000 kg run.
  • You have said which break never ran, and explained why the two that did run were both broken even though one of them printed the right answer for 100 kg.
divider

Reflection

Answer the following questions before submitting your work.

  1. With if and else, exactly one of the two blocks runs. What would it mean for a program if both could run?
  2. Task 4 produced one refusal to build and one program that ran and gave a wrong answer. Which of those two would you rather have in a program that controls a real launch, and why?
  3. You now know two of the three algorithm building blocks. Name them, and describe what each one lets a program do.
divider

Submit

Submit four things to the dropbox:

  1. Your 1-12-launch program file.
  2. Your four Task 2 outputs, and one full run of the finished program with a cargo mass over 500.
  3. Your three Task 4 results, with error or warning codes and line numbers, the 9000 kg run, and your explanation of why both of the breaks that ran were broken.
  4. Your three reflection answers.

Activity Complete