Back

Activity 1.11: Booleans and Comparison

divider

Activity 1.11

Booleans and Comparison

Key Concepts

Comparisons Produce Values

Storing a Comparison

Assignment vs. Equality

A Boolean From Outside

A Comparison Asks a Question

And a question has an answer.

A Comparison Asks a Question

Console.WriteLine(7 > 3);
Console.WriteLine(7 < 3);
Terminal window
True
False

You typed true yourself in Activity 1.5. Now C# is producing it.

The Six Comparisons

> and <
greater than, less than
>= and <=
greater or equal, less or equal
==
is equal to
!=
is not equal to

Store the Answer, Not the Data

int score = 85;
bool passed = score >= 60;
Console.WriteLine($"Score: {score}");
Console.WriteLine($"Passed: {passed}");
Terminal window
Score: 85
Passed: True

Store the Answer, Not the Data

passed does not hold 85. It holds the answer to a question about 85.

Naming these well matters. passed, isHot, hasKey — a boolean's name should read like a yes-or-no question.

One Equals Sign, or Two?

int a = 5;
a = 7; // assignment: put 7 into a
Console.WriteLine(a == 7); // comparison: is a equal to 7?
Terminal window
True

One Equals Sign, or Two?

  • = puts a value into a variable
  • == asks whether two things are equal

They look similar and do completely unrelated jobs.

C# Will Not Let You Confuse Them

bool check = temperature = 50;

One equals sign, where a question was meant.

C# Will Not Let You Confuse Them

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

A bool holds only true or false. temperature = 50 produces a number, so it does not fit.

You met CS0029 in Activity 1.8. Same error, different types.

A Boolean From Outside the Program

Every boolean so far came out of a comparison you wrote. Input can hand you one directly.

A Boolean From Outside the Program

Console.Write("In open water? (true/false) ");
bool openWater = bool.Parse(Console.ReadLine());
Console.WriteLine($"Open water: {openWater}");
Terminal window
In open water? (true/false) true [Enter]
Open water: True

int.Parse for whole numbers. double.Parse for decimals. bool.Parse for true and false.

And It Fails the Same Way

Terminal window
In open water? (true/false) yes [Enter]
Unhandled exception. System.FormatException: String 'yes' was not recognized as a valid Boolean.
at System.Boolean.Parse(String value)
at Program.<Main>$(String[] args) in 1-11-weather.cs:line 29

Only true and false are accepted, in any capitalization. yes is not a Boolean.

The same FormatException as Activity 1.9. Every member of the Parse family fails like this.

Parse Before You Compare

string windSpeed = Console.ReadLine();
bool highWind = windSpeed >= 40;

The wind speed was never converted.

Parse Before You Compare

Terminal window
1-11-weather.cs(21,17): error CS0019: Operator '>=' cannot be applied to operands of type 'string' and 'int'
The build failed. Fix the build errors and run again.

C# will not compare text to a number at all.

In some languages this quietly returns a wrong answer. Here it does not build.

Today's Objectives

  • Writing comparisons with all six operators
  • Storing a comparison's result in a bool
  • Naming boolean variables as questions
  • Telling assignment and equality apart
  • Reading a boolean from input with bool.Parse

Key Terms

Comparison operator
A symbol that compares two values and produces a boolean.
Boolean expression
A piece of code that evaluates to true or false.
Assignment
Putting a value into a variable, written with a single =.
Equality
Asking whether two values match, written with ==.

'F' → Fullscreen

divider

Build

Everything today goes in a new program named 1-11-weather.

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: Compare Directly

  • Write the code below and run it.
  • Both comparisons sit inside the interpolation braces. That is allowed — a comparison is a value like any other, so it can go anywhere a value can.
  • Change the temperature to a negative number and run it again. Write down which of the two lines changed and which did not.
  • Both lines still print. A comparison produces a value; it does not stop anything.
1-11-weather
int temperature = 31;
Console.WriteLine($"Temperature: {temperature}");
Console.WriteLine($"Above freezing: {temperature > 0}");
Console.WriteLine($"Below boiling: {temperature < 100}");

Task 2: Store the Answers

  • Add a humidity reading and three named boolean variables.
  • Note the names: each one reads like a yes-or-no question about the data.
  • Each is declared bool — the fourth type from Activity 1.5. You typed those by hand. These are produced by the comparison on the right of the =.
  • isExactlyFreezing uses two equals signs. One would mean something completely different, and Task 4 shows you exactly what.
1-11-weather
int temperature = 31;
int humidity = 82;
Console.WriteLine($"Temperature: {temperature}");
Console.WriteLine($"Above freezing: {temperature > 0}");
Console.WriteLine($"Below boiling: {temperature < 100}");
Console.WriteLine();
bool isHot = temperature >= 30;
bool isHumid = humidity >= 70;
bool isExactlyFreezing = temperature == 0;
Console.WriteLine($"Hot: {isHot}");
Console.WriteLine($"Humid: {isHumid}");
Console.WriteLine($"Exactly freezing: {isExactlyFreezing}");

Task 3: Plan, Then Compare Some Input

  • The comments describe a wind-speed check. Write the code under them.
  • Convert the wind speed before you compare it. Task 4 shows what happens if you forget.
  • “NOT exactly zero” is one comparison, not two. Look back at the six operators.
  • The open-water answer is already true or false, so it needs bool.Parse rather than int.Parse. The user has to type true or false, which is why the prompt says so.
1-11-weather
int temperature = 31;
int humidity = 82;
Console.WriteLine($"Temperature: {temperature}");
Console.WriteLine($"Above freezing: {temperature > 0}");
Console.WriteLine($"Below boiling: {temperature < 100}");
Console.WriteLine();
bool isHot = temperature >= 30;
bool isHumid = humidity >= 70;
bool isExactlyFreezing = temperature == 0;
Console.WriteLine($"Hot: {isHot}");
Console.WriteLine($"Humid: {isHumid}");
Console.WriteLine($"Exactly freezing: {isExactlyFreezing}");
Console.WriteLine();
// Ask the user for a wind speed and convert it to a whole number
// Store whether the wind is at or above 40
// Store whether the wind is NOT exactly zero
// Display both results with labels
// Ask whether the boat is in open water
// That answer is already true or false, so use bool.Parse
// Display that answer with a label

Task 4: Break It on Purpose

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

  1. Run it normally, and type yes when it asks about open water.
  2. Change isExactlyFreezing to use a single equals sign. Try to run it.
  3. Store the wind speed as a string instead: change int to string and remove the int.Parse(...) wrapper, keeping Console.ReadLine(). Try to run it.

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

Two of these never ran at all. One ran, then stopped. Say which is which, and how you can tell from the screen.


Challenge (Optional): The Comparison C# Made You Ask For

  • Task 4's third break refused to compare text to a number. But text can be put in order — C# just will not do it by accident.
  • Add this line and run it: Console.WriteLine(string.Compare("9", "100") > 0);
  • Write a comment explaining what that answered, and why comparing "9" and "100" as text gives that result when comparing 9 and 100 as numbers would not.
divider

Same Idea, Exam Notation

C#
int score = 85;
bool passed = score >= 60;
bool perfect = score == 100;
bool failed = score != 100;
Exam Notation
score ← 85
passed ← score ≥ 60
perfect ← score = 100
failed ← score ≠ 100

This is the panel where the two notations disagree most. Read the middle row carefully.

MeaningC#Exam notation
Put a value into a variable=←
Is equal to===
Is not equal to!=≠
Greater or equal>=≥
Less or equal<=≤

A single = means assignment in C# and equality on the exam. The same character, two opposite jobs, depending on which notation you are reading.

Because the exam uses ← for assignment, there is no ambiguity within the notation — the confusion only happens when you switch between the two. When you see score = 100 on an exam question, it is asking a question, not setting a value.

There is no bool.Parse on the exam. The reference sheet has exactly one way to get input, INPUT(), and it is not typed — it just returns whatever the user gave.

So a yes-or-no question on an exam looks like answer ← INPUT() followed by a comparison, with nothing converted. Converting input is something C# requires and the exam notation does not have.

divider

Checkpoint

Your finished program should run like this.

Example Output
Temperature: 31
Above freezing: True
Below boiling: True
Hot: True
Humid: True
Exactly freezing: False
Wind speed? 12 [Enter]
High wind: False
Wind is moving: True
In open water? (true/false) true [Enter]
Open water: True
  • Every boolean prints True or False, with a capital letter.
  • The three Task 2 booleans are stored in variables; the two Task 1 comparisons are not.
  • A wind speed of 12 gives False for high wind and True for moving.
  • You have the negative-temperature result from Task 1 written down.
  • All three Task 4 results are written down, with error codes or exception names and their line numbers.
divider

Reflection

Answer the following questions before submitting your work.

  1. passed stores the answer to a question rather than a number. Why is that more useful than storing the score again?
  2. Explain the difference between = and == in C#, as if to someone who has never programmed. Then describe a mistake you could make by forgetting that a single = means “is equal to” on the exam.
  3. Two of Task 4's three breaks were refused before the program ran. One was not. Which one, and why is that the more dangerous kind?
divider

Submit

Submit five things to the dropbox:

  1. Your 1-11-weather program file.
  2. A copy of one full run with a wind speed of 12 and open water true.
  3. Your Task 1 negative-temperature result.
  4. Your three Task 4 results, with error codes or exception names and line numbers, and which one ran before it stopped.
  5. Your three reflection answers.

Activity Complete