08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4 ■ Programs with Selection Logic

Each of these can be either true or false. These are examples of a special kind of Boolean

expression called relational expressions. Such expressions simply check if one value is equal to,

not equal to, greater than, greater than or equal to, less than, and less than or equal to another

value. We write them using relational operators.

The C relational operators (with examples) are:

== equal to k == 999, a*a + b*b == c*c

!= not equal to s != 0, a != b + c

> greater than a > 100

>= greater than or equal to b*b >= 4.0*a*c

< less than n < 0

<= less than or equal to score <= 65

Boolean expressions are normally used to control the flow of program execution. For

example, we may have a variable (h, say) which starts off with a value of 0. We keep increasing it

by 1 and we want to know when its value reaches 100. We say we wish to know when the condition

h == 100 is true. A condition is the common name for a Boolean expression.

The real power of programming lies in the ability of a program to test a condition and decide

whether it is true or false. If it is true, the program can perform one set of actions; and if it is false,

it can perform another set or simply do nothing at all.

For example, suppose the variable score holds the score obtained by a student in a test, and the

student passes if her score is 50 or more and fails if it is less than 50. A program can be written to

test the condition

score >= 50

If it is true, the student passes; if it is false, the student fails. In C, this can be written as:

if (score >= 50) printf("Pass\n");

else printf("Fail\n");

When the computer gets to this statement, it compares the current value of score with 50. If the

value is greater than or equal to 50, we say that the condition score >= 50 is true. In this case the

program prints Pass. If the value of score is less than 50, we say that the condition score >= 50 is

false. In this case, the program prints Fail.

In this chapter, we will see how Boolean expressions are used in if and if...else statements

and, in the next chapter, we will see how they are used in while statements.

4.2.1 AND, &&

With the relational operators, we can create simple conditions. But sometimes, we need to ask if

one thing is true AND another thing is true. We may also need to know if one of two things is true.

For these situations, we need compound conditions. To create compound conditions, we use the

logical operators AND, OR, and NOT.

66

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!