Transcript Document

+
CPS125
CONDITIONAL STATEMENTS
RELATIONAL/EQUALITY OPERATORS

THE IF STATEMENT

LOGICAL OPERATIONS – AND, OR, NOT

PRECEDENCE FOR C OPERATORS, MATHEMATICAL, RELATIONAL,
LOGICAL

TYPE CASTING

C SWITCH

CONDITIONAL OPERATOR
2
Control Structures
3
 Control structures combine individual instructions into a single logical unit
with one entry point at the top and one exit point at the bottom.

3 kinds of control structures:

Sequence (default control structure)

Selection (branches)

Repetition (loops)
Conditions

A condition is an expression that is either
true or false.

Ex: CPS125_Grade=98;

CPS125_Grade < 0 will be false

CPS125_Grade >90 will be true

Comparison (relational) operators are:

< > <= >= == !=
4
5
Relational Operations



Relationship between 2 variables, expressions
Returns a numerical value depending on the result
The value returned for TRUE is 1, 0 otherwise
Relational Operators in C
Symbol
Purpose
>
Greater than
>=
Greater than or equal to
<
Less than
<=
Less than or equal to
6
Equality Operations

Equality between 2 variables, expressions

The value returned for TURE is 1, 0 otherwise
Equity Operators in C
Symbol
Purpose
==
Equal to
!=
Not equal to
Common Mistakes When Writing a C
Program

Missing #include…

Missing variable declaration

Wrong variable declaration

Missing semicolon

Incorrect assignment

Using the name of the variable instead of its address

Incorrect nested if

Wrong looping condition

Misusing pointers

Missing Braces

Using incorrect format specifier
7
Note on = and == 
=
denotes assignment
result of operation in right hand side
is assigned to the variable mentioned in
left hand side.
x = 5;
/* returns 5 to x*/
==
denoted equal to
is relational operators
returns either 1 or 0.
x == 6; /* returns 0 */
8
9
Logical Operators

A logical expression contains one or more comparison and/or
logical operators.

The logical operators are:

&&: the and operator, true only when all operands are true.

||: the or operator, false only when all operands are false.

!: the not operator, false when the operand is true, true when the
operand is false.
10
Logical Operations – AND, OR, NOT

Logical AND
(&&)
( expression1 ) && ( expression2 )
This operation is TRUE only if expression1 is TRUE and expression2 is TRUE.
Works based on the AND truth table as follows:
Logical AND Truth Table
Expression1
Expression2
AND
0
0
0
0
1
0
1
0
0
1
1
1
11
Logical OR Operation

Logical OR
(||)
(expression1) || (expression2)
This operation is FALSE only if expression1 is FALSE and expression2 is FALSE.
Works based on the OR truth table as follows:
Logical OR Truth Table
Expression1
Expression2
OR
0
0
0
0
1
1
1
0
1
1
1
1
12
Logical NOT Operation

Logical NOT
(!)
! (expression1)
This operation will negate the logical value of the expression.
Works based on the NOT truth table as follows:
Logical NOT Truth Table
Expression1
NOT
0
1
1
0
Precedence C
Operators/Mathematical/Relational, Logical
High
Operation
!
Logical Not
*, /
Multiplication and Division
+, -
Addition and Subtraction
<, <=, >=, >
==, !=
Low
Purpose
Less, Less or Equal, Greater
or Equal, Greater
Equal, Not Equal
&&
Logical AND
||
Logical OR
13
+ Expressions

-Identify variables

You could have A+-Z%B if they are non zero and integer.

You could not have the expression :ab-cd+3bx

After each operation we must have an operand: x+xy-z

Look at the ( )well. A+(b+c)-(a-d)

Do not use reserved words: void ,char.

You could use soft rules: A standard identifier is a name used by C
but is not a reserved word. printf, scanf are examples of standard
identifiers.

Be careful we must use functions in C for math .
14
Fast evaluation of logical expressions
• The trick is to divide the expression in sub expressions between the || and
evaluate the easiest first. As soon as you find a TRUE, the whole thing is true.

When there is no || operator. Divide the expression in parts between
the && operators. If one part is false, the expression is false.
NOTE:

0 means FALSE.

1 means TRUE.

ANY NONZERO VALUE IS TREATED AS TRUE.
15
+
+ Expressions

-x- y*z……..-x then y*z then –x-result of the second step.

(x<y || x<z) && x>0.0 …first &&

You can also use parentheses to clarify the meaning of the expression.

If x,min,max are type double ,the C compiler interprets the expression

x+y<min+max correctly as: (x+y)<(min+max)
17
English Conditions as C Expressions
18
English Condition
Logical Expression
Evaluation
X and Y are greater
than z
X> z && Y>z
1 && 1 is 1 (true)
X is equal to 1.0 or 3.0
X==1.0 || X== 3.0
0 || 1 is 1 (true)
x is in the range z to y,
inclusive
z<=x && x<= y
1 && 1 is 1 (true)
x is outside the range
z to y
!(z<=x && x<= y)
z>x || x> y
!(1 && 1) is 0 (false)
0 || 0 is 0 (false)
Comparing characters
•
'9' >= '0' ?

'a' < 'e' ?

'B' <= 'A' ?

'Z' == 'z' ?

Is a letter lower-case?
letter >= 'a' && letter <= 'z'

Does the variable ch contains a letter?
(ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
19
Character Comparisons
20
Expression
Value
‘9’>=‘0’
1 (true)
‘a’< ‘e’
1 (true)
‘B’<= ‘A’
0(false)
‘Z’== ‘z’
0(false)
‘a’<= ‘A’
System dependent
‘a’<= ch && ch <= ‘z’
1 (true) if ch is a lowercase letter
+ Logical Assignments

Assum that a value 1 for senior_citizen indicates that the person is a
senior citizen (65 years old or over).you can use the assignment
statement

senior_citizen =1; /*set senior status*/

To set senior_citizen to true.

A more likely scenario is to set the value of senior_citizen based on the
value scanned into age.

scanf(“%d”,&age); /*read the person’s age*/

senior_citizen=(age>=65); /*set senior status*/

In the assignment above , the condition in parentheses evaluates first. its
value is 1 (true) if the value scanned into age is 65 or greater.
Consequently, the value of senior_citizen is true when age satisfies the
condition and false otherwise.
21
+ Logical Assignments

The logical operators &&,||,and ! Can be applied to senior_citizen.

The expression ! senior_citizen is 1 (true) if the value of age is less
than 65.

senior_citizen &&gender==‘M’

Is 1(true )if senior_citizen is 1(true)and the character in gender is
M.

The statement below assigns the value 1(true) to even (type int) if n
is an even number:

even= (n%2==0)

Because all even numbers are divisible by 2,the remainder of n
divided by 2 (n%2 in C)is when n is an even number.

The expression in parentheses compare the remainder to 0,so its
value is 1 (true) when the remainder is 0 and its value is 0(false)
when the remainder is nonzero.
22
Math Formula….C Expression
Mathematical Formula
C Expression
b2 - 4ac
b*b – 4*a*c
a+ b- c
a + b -c
a+ b/ c+d
(a+ b) /(c+ d)
1/1+ x2
1/(1+x*x)
ax-(b+c)
a* -(b+c)
23
Condition complements

The opposite (or complement) of (x == 0) is !(x==0) or (x != 0).

The opposite of (x > 3) is !(x > 3) or (x <=3).

The opposite of (a == 10 && b > 5) is !(a ==10 && b > 5) or (a != 10 || b <=5)

De Morgan's Theorem:

The complement of exp1 && exp2 is comp_exp1||comp_exp2.

The complement of exp1||exp2 is comp_exp1 && comp_exp2.
24
The if Statement
o
How to use if statement for Decision-making capabilities
o
How to use relational operators
General Syntax:
if
(condition(s)){
/* body of if statement appears here!*/
}
Description:
If the condition or conditions are true then the body of the if statement is executed.
Note: Never put a ; after the condition.
25
Simplest form of if statement
o
body of if only includes ONE statement
o
don’t need braces, { }, to mark the body of the if. However, we can use them if
we want.
o
Don’t forget the semicolon at the end of the single statement.
if
(condition)
statement1;
statement2;
Description:
o
Conditional statement.
o
If the condition is TRUE then statement1 is executed.
o
If the condition is FALSE then statement1 is not executed.
o
Statement2 is NOT part of the IF statement and will always be executed
regardless of the status of the condition.
26
/* PROGRAM #7 */
/* USE OF IF STATEMENT */
#include <stdio.h>
main( ){
float MyGPA;
float MinGPA=2.0;
/* Input the GPA */
printf("Pls enter your GPA: ");
scanf("%f",&MyGPA);
/* Test the value of GPA and print the result */
if (MyGPA > MinGPA)
1st printf
printf("Your status might be clear.\n");
printf("Your GPA is %f.\n", MyGPA);
}
2nd printf
27
Execute1:
28
Execute2:
Note:

The body of the if is not marked by braces, therefore, we assume that it
contains only one statement that is the 1st printf statement in this example,
and the 2nd printf statement is actually outside the if body.
29
IF With A Compound Statement
o
Two/more statements are enclosed within braces { }.
o
Body of if includes more than one statement
o
Must use braces, { }, to mark the body of the if.
General Syntax:
if (condition(s)){
statement_1;
statement_2;
…
}
statement_N;
Description:
o
Conditional statement.
o
If the condition is TRUE then all the statements within the barces are executed.
o
Otherwise those statements are not being executed.
o
Statement_N is NOT part of the IF statement and will always be executed regardless of
the status of the condition.
30
+
IF … ELSE …
o
Very similar to the IF statement seen before.
o
Enhances the decision-making capability.
General Syntax:
if
(condition)
statement1;
else
statement2;
o
if the condition is TRUE then statement1 is executed.
o
Otherwise statement2 is executed.
NOTE:

if and else are C keywords, then is not.
31
+
/* Even vs. Odd */

#include <stdio.h>

int main (void) {

int number, even;

/* ask user for number */

printf ("Enter an integer number: ");

scanf ("%d", &number);

/* determine if number is even and put in variable */

even = (number % 2 == 0);

/* display report */

if (even)
printf ("%d is an even number.\n", number);


else
printf ("%d is an odd number. \n", number);



return (0);
}
32
/* PROGRAM #8 */
33
/* COMPOUND STATEMENT */
/* are you getting A+ in CPS125? */
#include <stdio.h>
/* need <stdlib.h> for exit( ), see Appendix */
#include <stdlib.h>
main( ){
float Grade125, GPA;
printf("Please enter your grade in CPS125: "); /* Input the grade */
scanf("%f", &Grade125);
/* Test if the grade is A+ and print the result */
if (Grade125 >= 90.0){
printf("You’re getting A+ in this course!\n");
/* Input the GPA */
printf("Please enter your GPA: ");
scanf("%f", &GPA);
printf("Your GPA is %f & you’re getting A+ in this course!\n",GPA); }
exit(0);
}
Result1:
Note on exit(0):

Is used to return the control to the OS.
34
Result2:
35