Professional Documents
Culture Documents
Programming: Statements & Relational Operators
Programming: Statements & Relational Operators
Programming: Statements & Relational Operators
If Statements &
Relational
Operators
COMP102 Prog Fundamentals I: If Statements & Relational Operators /Slide 2
Conditional Statements
Two constructs
if statement
– if
– if-else
– if-else-if
switch statement
COMP102 Prog Fundamentals I: If Statements & Relational Operators /Slide 3
If statement
Nested if
In case the body of the if statement lies in
entirity inside another if statemt the structure
is called nest if.
if(condition/s)
{
if(condition)
{
// body of internal if
}
}
COMP102 Prog Fundamentals I: If Statements & Relational Operators /Slide 6
Syntax
if(condition)
false
action condition
Choice (if)
if (it's raining){
<take umbrella>
<wear raincoat>
}
COMP102 Prog Fundamentals I: If Statements & Relational Operators /Slide 8
Absolute Value
// program to read number & print its absolute value
#include <iostream>
using namespace std;
int main(){
int value;
cout << "Enter integer: ";
cin >> value;
if(value < 0)
value = -value;
cout << "The absolute value is " << value << endl;
return 0;
}
COMP102 Prog Fundamentals I: If Statements & Relational Operators /Slide 9
Relational Operators
Relational operators are used to compare two values to
form a condition.
Math C++ Plain English
= == equals [example: if(a==b) ]
[ (a=b) means put the value of b into a ]
< < less than
<= less than or equal to
> > greater than
>= greater than or equal to
!= not equal to
COMP102 Prog Fundamentals I: If Statements & Relational Operators /Slide 10
Conditions
Examples:
10 > 20
20 * j == 10 + i
COMP102 Prog Fundamentals I: If Statements & Relational Operators /Slide 11
Operator Precedence
Which comes first?
Answer: * / %
+ -
< <= >= >
== !=
=
COMP102 Prog Fundamentals I: If Statements & Relational Operators /Slide 12
Operand !Operand
true false
false true
COMP102 Prog Fundamentals I: If Statements & Relational Operators /Slide 16
A Boolean Type
Examples
5 != 6 || 7 <= 3
(5 !=6) || (7 <= 3)