Week 4 Arithmetic, Relational Operators and Conditional Statements
Week 4 Arithmetic, Relational Operators and Conditional Statements
[Week 4]
1
Students Learning Objectives (Week Four)
Arithmetic operators
Relational operators
Logical operators
Conditional statements (if, else if, else)
Switch case statements
2
C++ operators
3
C++ Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Although the + operator is often used to add together two values, like in the example
above, it can also be used to add together a variable and a value, or a variable and
another variable:
4
C++ Operators
5
Arithmetic Operators
6
A variable is a memory location x 0.6
used to store a value (0.6)
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4
0.4
The right side is an expression. Once the
expression is evaluated, the result is placed in
(assigned to) the variable on the left side (i.e.,
0.936
x).
Precedence of Arithmetic Operators
• The operators *, / and % have priority over + and -.
• This means that * and / are executed before + and - regardless of the position they occupy in the
expression.
Example:
5 + 7 * 2 returns as a result 19
• In other words, 7 * 2 is calculated first and then the result is added to 5. To change the
Example:
(5 + 7) * 2 returns as a result 24
• Remark that the symmetrical (unary minus -A) has priority over *, /, %, + and -.
9
Precedence of Arithmetic Operators
10
the division operator /
In C++, the division operator / is used to divide two numbers. The behavior of
the division operation depends on the types of the operands:
1.Integer Division: If both operands are integers, the division operation
performs integer division, where the fractional part is discarded. For example:
int a = 5;
int b = 2;
int result = a / b; // result will be 2
In this case, although the exact result of 5 divided by 2 is 2.5, since we’re
performing integer division, the fractional part (.5) is discarded and the result
is 2.
11
the division operator / (Cont.)
float a = 5.0;
int b = 2;
float result = a / b; // result will be 2.5
12
the division operator / (Cont.)
3.Division by Zero: In C++, division by zero is undefined for integer types and
produces NaN (Not a Number) for floating-point types. For example:
int a = 5;
int b = 0;
int result = a / b; // Undefined behavior
double c = 5.0;
double d = 0.0;
double result2 = c / d; // Produces NaN
• In these cases, dividing by zero leads to undefined behavior for integers and
produces NaN for floating-point numbers.
• Remember to always use the correct types for your variables when performing
division in C++ to get the expected results.
13
the Modulus Operator (%)
14
Increment (++) and Decrement (--) Operators
Increment (++) and Decrement (--) Operators: These operators are used to
increase or decrease the value of a variable by 1.
• They can be used in both postfix (i++, i–) and prefix (++i, --i) forms.
• The difference between these two forms is that:
• the postfix form returns the value before it was modified,
• while the prefix form returns the value after it was modified.
int i = 5;
cout << i++ << endl; // prints 5
cout << i << endl; // prints 6
15
Assignment Operators
A list of all assignment operators:
16
Assignment Statements
x = 3.9 * x * ( 1 - x )
Checkpoint 1
Write a program that takes two numbers as input and prints their
sum.
#include<iostream>
using namespace std;
int main() {
int num1, num2, sum;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
sum = num1 + num2;
cout << "The sum is " << sum;
return 0;
}
18
Checkpoint 2
Write a program that calculates the area of a circle. The radius
should be given by the user. Area=3.14* radius * radius
#include<iostream>
using namespace std;
int main()
{
float radius, area;
cout << "Enter radius of the circle: ";
cin >> radius;
area = 3.14 * radius * radius;
cout << "Area of the circle is " << area;
return 0;
} 19
Checkpoint 3
What is the output of the following code?
int a = 2, b = 3, c = 4;
cout << a + b * c; int a = 10, b = 20, c = 30; cout << (a + b) / c;
a) 14 b) 20 c) 24 d) None of the above a) 0 b) 1 c) 2 d) None of the above
21
Comparison Operators
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
22
Comparison Operators
A list of all comparison operators:
23
Logical Operators
• As with comparison operators, you can also test for true (1) or false (0) values
with logical operators.
• Logical operators are used to determine the logic between variables or values:
24
Logical Operators (Examples)
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (x > 3 && x < 10); // returns true (1) because 5 is greater than 3 AND 5 is less than 10
return 0;
}
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (x > 3 || x < 4); // returns true (1) because one of the conditions are true (5 is greater than 3, but 5 is not less than 4)
return 0;
}
25
Logical Operators
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (!(x > 3 && x < 10)); // returns false (0) because ! (not) is used to reverse the result
return 0;
}
26
Checkpoint 4
What is the output of the following code?
int a = 10, b = 20; cout << (a == b);
a) 1 b) 0 c) Error d) None of the above int a = 10, b = 20; cout << (a > b || a != b);
a) 1 b) 0 c) Error d) None of the above
int a = 10, b = 20; cout << (a != b);
a) 1 b) 0 c) Error d) None of the above
int a = 10, b = 20; cout << !(a == b);
a) 1 b) 0 c) Error d) None of the above
27
C++ Conditions and If Statements
You already know that C++ supports the usual logical conditions from mathematics:
•Less than: a < b
•Less than or equal to: a <= b
•Greater than: a > b
•Greater than or equal to: a >= b
•Equal to a == b
•Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
C++ has the following conditional statements:
•Use if to specify a block of code to be executed, if a specified condition is true
•Use else to specify a block of code to be executed, if the same condition is false
•Use else if to specify a new condition to test, if the first condition is false
•Use switch to specify many alternative blocks of code to be executed
28
The if Statement
Use the if statement to specify a block of C++ code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the
condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition
is true, print some text:
Example
if (20 > 18) {
cout << "20 is greater than 18";
}
29
The if Statement
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y (using
the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that
"x is greater than y".
30
C++ Else
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}// Outputs "Good evening."
31
C++ Else
Example explained
In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on
to the else condition and print to the screen "Good evening". If the time was less than 18, the program
would print "Good day".
32
C++ Else If
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}// Outputs "Good evening." 33
C++ Else If
Example explained
In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in
the else if statement, is also false, so we move on to the else condition
since condition1 and condition2 is both false - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
34
C++ Short Hand If Else
35
Checkpoint 5
What is the output of the following code?
int a = 10, b = 20, c = 30;
if (a > b)
{
if (b > c)
cout << "a and b are greater than c";
else
cout << "c is greater than a and b"; c is greater than a and
} b
else
{
if (b < c)
cout << "c is greater than a and b";
else
cout << "b is greater than a and c";
}
36
Checkpoint 6
What is the output of the following code?
int x = 5, y = 10, z = 15;
if (x > y)
{
if (y > z)
std::cout << "x > y > z";
else
std::cout << "x > y and y < z"; x<y<z
}
else if (y > z)
std::cout << "x < y > z";
else
std::cout << "x < y < z";
37
Checkpoint 7
What is the output of the following code?
int a = 10, b = 20;
if (a == b)
std::cout << "a equals b";
else if (a != b)
{
if (a > b)
b is greater than a
std::cout << "a is greater than b";
else
std::cout << "b is greater than a";
}
38
Checkpoint 6
What is the output of the following code?
int num = 0;
if (num > 0)
std::cout << "Positive number";
else if (num < 0)
std::cout << "Negative number";
else Zero
std::cout << "Zero";
39
Checkpoint 7
What is the output of the following code?
int x = 5, y = 10;
if (x == y)
std::cout << "x equals y";
else if (x != y)
{
if (x > y)
x is less than y
std::cout << "x is greater than y";
else if (x < y)
std::cout << "x is less than y";
}
40
C++ Switch
Use the switch statement to select one of many code blocks to be executed.
The switch statement in C++ is a control flow statement that allows
the value of a variable or expression to change the control flow of
program execution via search and map mechanism. Syntax
Here’s how it works: switch(expression)
1.The switch statement evaluates the expression inside the {
parentheses. case x:
2.The value of this expression is then compared with the values of // code block
each case in the structure. break;
case y:
3.If there’s a match, the block of code associated with that case is
// code block
executed. break;
4.The break keyword is used to prevent the code from running into default:
the next case automatically (a behavior known as fall-through). // code block
5.If none of the case values match and a default statement is }
provided, then the code block under default will be executed.
41
C++ Switch
The example below uses the weekday number to calculate the weekday name:
Example
42
C++ Switch- The break Keyword
• When C++ reaches a break keyword, it breaks out of the switch block.
• This will stop the execution of more code and case testing inside the block.
• When a match is found, and the job is done, it's time for a break. There is
no need for more testing.
A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.
43
C++ Switch- fall-through
• In a switch statement in C++, once a Here’s an example to illustrate this:
case is matched, the corresponding int x = 1;
block of code is executed. switch (x) {
• If a break statement is not present case 1:
after that case, the program will cout << "Case 1\n"; // This will be executed
continue executing the next case’s case 2:
code, regardless of whether the next cout << "Case 2\n"; // This will also be executed because of fall-through
case matches or not. This is known break;
as fall-through. default:
• The switch statement doesn’t re- cout << "Default case\n";
check or test other cases once it has }
found a matching case. In this example, even though x is 1 and does not equal 2,
• It simply moves down the code “Case 2” will still be printed because there’s
executing everything until it no break statement after “Case 1”. The program doesn’t
encounters a break statement or check if x equals 2 after executing the first case; it just
reaches the end of the switch block. continues on to the next line of code. If you want to avoid
this fall-through behavior, you should include
a break statement after each case.
44
C++ Switch- The default Keyword
The default keyword specifies some code to run if there is no case match:
Example
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"
45
Checkpoint 8
What will happen if we miss the break statement after a true case of
a switch statement?
a) Compiler will generate an error
b) switch will not execute
c) Remaining cases will match
d) Default statement will not execute
46
Checkpoint 9
What is the output of the following code?
int option = 1;
switch (option) {
case 1:
std::cout << "A";
case 2:
std::cout << "B";
case 3:
ABC
std::cout << "C";
break;
default:
std::cout << "D";
}
47
Checkpoint 10
What is the output of the following code?
int option = 4;
switch (option) {
case 1:
std::cout << "A";
break;
case 2: D
std::cout << "B";
break;
case 3:
std::cout << "C";
break;
default:
std::cout << "D";
}
48
Checkpoint 11
What is the output of the following code?
int option = 2;
switch (option) {
case 1:
std::cout << "A";
break;
case 2: BCD
std::cout << "B";
case 3:
std::cout << "C";
default:
std::cout << "D";
}
49
Checkpoint 12
What is the output of the following code?
int option = 3;
switch (option) {
case 1:
std::cout << "A";
break;
case 2:
std::cout << "B";
CD
break;
case 3:
std::cout << "C";
default:
std::cout << "D";
}
50
Thank You…
51