UPI Study › Courses › Programming in C › Free lessons › Lesson 4.2 Free with a free account
Relational Operators: Testing Relationships Between Values
Programming in C · Chapter 4: Conditional Logic, Decision Structures, and Practical ApplicationsSection 4.2 · lesson 20 of 787 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Logical Operators and Short-Circuit Evaluation →← Workshop: Variables, Data Types, and Formatted OutputNext lesson: Logical Operators and Short-Circuit Evaluation →
In this lesson
Compare values with C's six relational operators and avoid classic traps.
- Use C's six relational operators and explain why each returns 1 or 0
- Predict comparisons that mix arithmetic or character codes
- Compare doubles with fabs and a tolerance instead of ==
- Recognize the = versus == slip and chained comparison bugs
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (964 words). Read along, or search it.
Opening Question
Is 250 at Least 300
A prize machine at the Starlight Arcade has a sign: need three hundred points to win. Maya has two hundred fifty. Somewhere inside, a program asks one tiny question. Is two fifty at least three hundred? The answer isn't maybe, and it isn't a number of points. It's a flat yes or no. This lesson is about those questions, and about one typing slip that has fooled programmers for decades.
Six Operators
Every Comparison Gives 1 or 0
A relational operator compares two values and says how they relate. C has six of them. Less than, greater than, less than or equal, and greater than or equal. Then two equals signs, for is equal to, and an exclamation mark with an equals sign, for is not equal to. The two-character operators have no space inside, and the equals sign always comes second. Here they are in a program, with Maya's score of 250 and the target of 300. Each result is printed with %d, which prints a whole number. That's exactly what a comparison gives: 1 for true, 0 for false. Build and run it. Less than gives one, and greater than gives zero. Less or equal, one. Greater or equal, zero. Equal, zero, and not equal, one. Two patterns to notice. Equal and not equal are always opposites. And for any two numbers, exactly one of less, equal, and greater is true.
Comparisons as Numbers
Storing and Adding Results
Many languages have a special true-or-false value. Classic C doesn't. A comparison produces a plain int, so you can store it like any other number. Enough is tickets at least fifty, so it's one. Perfect is tickets equal to a hundred, so it's zero. And adding them gives one. In tickets plus ten greater than seventy, C does the arithmetic first, getting seventy-four, and compares second. Relational operators rank below plus and minus. And letters compare by their codes. Capital A is sixty-five, and capital B is sixty-six. But lowercase a is ninety-seven, so it is not less than capital B. A tip: name a stored comparison like a yes-or-no question, such as enough, is empty, or has ticket. Then the line reads almost like English.
Quick Check
Seven Against Seven and Lowercase b
Quick check, with three new comparisons in one line. Seven against seven, twice, and then a lowercase b against a capital B. What does it print? Pause and predict. Build and run it. It prints zero, one, one. Seven is not less than seven, but it is less than or equal to seven. And lowercase b has a bigger code than any capital letter, so b greater than capital B is one.
Comparing Decimals
Using fabs With a Tolerance
Whole numbers are exact, so double equals is safe for them. Decimals are not. A double stores numbers in binary. A value as simple as zero point one has no exact binary form, just as one third has no exact decimal form. So add zero point one and zero point two, and compare the sum with zero point three. Printing seventeen decimals shows the tiny errors. The sum lands a hair above, and the stored zero point three a hair below. So double equals says zero. The fix asks how far apart they are. The fabs function, from math dot h, gives the distance without a minus sign. If that distance is under a tiny tolerance, they're close enough, and the test says one. One millionth is plenty for money, but fit the tolerance to your numbers.
Classic Slip
One Equals Sign in an if
Now the famous slip. One equals sign changes a variable. Two equals signs ask about it. They're one keystroke apart. Sam, the arcade's tester, wanted to ask whether the machine is out of tokens. But he typed only one equals sign. The if statement comes fully in lesson 4.4. For now, read it as: run the next block only when the test is true, meaning not zero. Compile with warnings on, and clang speaks up: using the result of an assignment as a condition without parentheses. Its note says exactly what to do: use double equals, to turn this into an equality comparison. GCC gives a similar warning, in different words. Run it anyway, and it says tokens left, zero, though the machine held ten. The single equals stored zero, and that value, zero, counts as false. Add the second equals sign and rebuild. Now it asks the question, and tokens stays ten. Treat that warning as a bug until proven otherwise.
Math Habit Trap
Chained Comparisons Mislead
One more trap, this time from math class. To check a score is between zero and a hundred, you might chain two comparisons. C reads it from the left. Zero less than or equal to one fifty gives one. And one is always less than or equal to a hundred. So the test answers one, even for a score of one hundred fifty. Clang warns that comparisons like this don't have their mathematical meaning. Asking between takes two separate questions, joined with the AND operator. That's lesson four point three.
Quick Check
Zero Lives Becomes Five
Quick check. In this new program, a player starts with zero lives, and the test has a single equals sign with a five. Which message appears? Pause and predict. Run it. It prints play on, lives five. The single equals stores five in lives, and the value of that assignment is five. Five isn't zero, so it counts as true, and the first block runs. Clang warns here too, exactly as before. So a slipped equals sign can go either way. With zero, the block never runs. With anything else, it always does.
Key Takeaways
Six Operators, Ints and Tolerance
To sum up. C has six relational operators, and each one gives an int: one for true, zero for false. Arithmetic happens before comparison, and letters compare by their codes. Compare doubles with a tolerance, using fabs, never with double equals. And one equals sign changes, two equals signs ask. Compile with warnings on, and take that warning seriously.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Relational Operators: Testing Relationships Between Values
What are the relational operators in C?
What is the difference between = and == in C?
How do you compare two doubles for equality in C?
Why does 0 <= score <= 100 not check a range in C?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →