Avocado Recipes Workshop Here is where your presentation begins to Celebrate National Avocado Day Ts. Mahani Binti Zakaria Rohani Binti Abu Bakar OPERATOR IN PROGRAMMING
OPERATOR IN PROGRAMMING EDITOR TS. MAHANI BINTI ZAKARIA ROHANI BINTI ABU BAKAR
Disclaimer Publisher POLITEKNIK SULTAN ABDUL HALIM MU’ADZAM SHAH (POLIMAS) All rights reserved: POLITEKNIK SULTAN ABDUL HALIM MU’ADZAM SHAH (POLIMAS) . All rights reserved. No part of this publication may be reproduced, stored, transmitted in any form or by any electronic, mechanical, photocopying, recording, or otherwise without prior permission of author/s or publisher. The authors also do not guarantee that the content is suitable for the reader, but all the content is through the author's own experience and expertise. First Published: JULY 2022 e ISBN: 978-967-0055-06-0 COPYWRITING Ts. Mahani binti Zakaria Rohani binti Abu Bakar Publisher: POLITEKNIK SULTAN ABDUL HALIM MU’ADZAM SHAH (POLIMAS) 06000 JITRA, KEDAH. Tel : 04-9146100 Fax : 04-9174232 / 04-9146323
In the name of ALLAH S.W.T, the most gracious and the most merciful, first and foremost. We would like to extend our deepest praise to ALLAH S.W.T who has given us the patient, strength, determination and courage to implement this e-book project. Our appreciation and thanks is also dedicated to our family, Head of Department and Head of Programme for their helpful insights, cooperation and stimulating comments. We would also like to express our apology for any mistake and shortcoming in writing this e-book. To end with, we are truly delighted, for this e-book would bring benefits to others. May Allah bless our efforts. Ts. Mahani binti Zakaria Rohani binti Abu Bakar Acknowledgments
One of the most important uses of a computer is its ability to calculate. You can use operators to manipulate data types. An operator is a symbol or sign that if placed on two operands (data) can produce a result, an operator is a symbol used to compose an expression involving one or more operands. For example in mathematics where a plus sign ('+') if placed between two numbers will produce another number which is the result of the addition of the two numbers. operators consist of arithmetic operators, task operators, relational operators and logic operators. This book will describe the functions of handlers and how they are used in c ++ programs. This book is expected to benefit students to facilitate their understanding of the topic of operators in solving programming code Abstract 5
01 Arithmetic Operator 05 02 Operator Precedence 06 Logical Operator Table of contents 03 Assignment Operator 07 Increment & Decrement 4 - 7 8 - 10 11-12 23-32 21-22 16-20 04 Self Test 08 Reference 13-15 33 Relational Operator
What is OPERATOR? Symbol to represent particular computer operation. An operator is a symbol used for performing operations on operands. An operator operates operands. The operations can be mathematical or logical. There are different types of operators in C++ for performing different operations. Introduction 1
Consist of: OPERATOR + , -, /, *, % Arithmetic Logical &&, ||, ! +=, -=, /=, *=, %= Assignment Increment ++ ==, >, <, >=, <=, != Relational Decrement - - 2
Arithmetic operators are used to perform arithmetic operations on variables and data ARITHMETIC OPERATOR
Arithmetic Operator C++ define the following arithmetic operators. Assume variable x holds 10 and variable y holds 20 then 4 Operator Name Desription Example + Addition Adds together two values x + y = 30 - Subtraction Subtracts one value from another x – y =-10 * Multiplication Multiplies two values x * y = 200 / Division Divides one value by another y/ x = 2 % Modulus Modulus. Divides two number and returns just the remainder portion x % y = 0 ++ Increment Increment operator increases the integer value by one. x++ = 11 -- Decrement Decrement operator decreases the integer value by one. x-- = 9
You can assign a positive or negative number to a variable by using a unary + or as shown below: X = -10 Y = +30 5 Assigns –10 to x Assigns 30 to y , + sign normally not needed
6 Balance is 1! Balance is 0! Note: The % operator can only be used with integers
Example of program : Arithmetic Operators Output 7 #include <iostream> using namespace std; int main() { int x, y; x = 10; y = 3; // display the sum of x and y cout << "x + y = " << (x + y) << endl; // display the difference of x and y cout << "x - y = " << (x - y) << endl; // display the multiple of x and y cout << "x * y = " << (x * y) << endl; // display the division of x by y cout << "x / y = " << (x / y) << endl; // display the modulus of x by y cout << "x % y = " << (x % y) << endl; return 0; }
Arithmetic expressions are evaluated with some rule called operator precedence. OPERATOR PRECEDENCE
Operator precedence Arithmetic expressions are evaluated with some rule called operator precedence. Also called math hierarchy. Determine exactly how C++ computes formulas multiplications (*) and divisions (/) are evaluated first additions (+) and subtractions (-) are performed last. The precedence of the arithmetic operators is shown here If there are multiple operators in a single expression, the operations are not evaluated simultaneously. Rather, operators with higher precedence have their operations evaluated first. Examples a) x = 5 + 2 * 4 – 1 5 + 8 – 1 13-1 14 9 Operator precedence Highest ( ) Higher ++ -- - (unary) Lowest + - for the same priority, start from left side
b) x = ( 10 + 2 ) * ( 2 - 1) x = ( 10+2 ) * ( 2 - 1) x = 12 * 1 x = 12 Example of program :operator precedence Output 10 Parentheses () has a highest priority #include <iostream> using namespace std; int main() { int x, y; x = 10; y = 3; // display the sum of x and y cout << "x + y = " << (x + y) << endl; // display the difference of x and y cout << "x - y = " << (x - y) << endl; // display the multiple of x and y cout << "x * y = " << (x * y) << endl; // display the division of x by y cout << "x / y = " << (x / y) << endl; // display the modulos of x by y cout << "x % y = " << (x % y) << endl; return 0; }
An assignment operator is used for assigning a value to a variable ASSIGNMENT OPERATOR
Assignment operator An assignment operator is used for assigning a value to a variable. Equal (=) is used as symbol in assignment operator variable = expression; Expression can be constants, variable or combination of constants and variables using math operators Here are some examples of assignment operations: weight =45; marks =85; width =2.5; If x= 8 and y =5, you will have the following results. 12 Operator Example Equivalent to result *= x*= y x = x * y x will have the value 40 /= x /=y x = x / y x will have the value 1.6 += x +=y x = x + y x will have the value 13 -= x -=y x = x - y x will have the value 3 %= x %=y x = x % y x will have the value 3
A relational operator is used to check the relationship between two operands RELATIONAL OPERATOR
Relational Operator Control statements use relation operators in order to compare two objects, which results in a value that is either true (1) or false (0). Relational operators are also known as comparison operators There are six relational operators as follows: 14 Operator Description Example Result < less than x < y 1 > 9 1 <= less than or equal to x <= y 10 <= 20 1 > greater than x > y 8 > 11 0 >= greater than or equal to x >= y 9 >= 5 1 == equal to x == y 8 ==5 0 != Not equal to x != y 7 != 5 1 Note: The return value of a comparison is either true (1) or false (0)
Example: #include <iostream> using namespace std; int main() { int x = 7; int y = 4; // returns 1 (true) because 5 is greater than 3 cout << (x > y); return 0; } An Application Example 15
Logical operators are used to determine the logic between variables or values LOGICAL OPERATOR
Symbol Meaning Description && AND Returns true if both statements are true || OR Returns true if one of the statements is true ! NOT Reverse the result, returns false if the result is true To combine relational operators into more powerful data testing statements Note: Truth Table shows how to achieve TRUE/FALSE results from an if statements that uses these operators. Logical Operator To be TRUE, both sides of the operator must be TRUE Causes an opposite relation To be TRUE, one or both of the operator must be TRUE Note: T: TRUE, F: FALSE AND T && T T T && F F F && T F F && F F Logical operator: Result: OR NOT T || T T T || F T F || T T F || F F !T F !F T Logical operator: Result: Logical operator: Result: 17
if((CGPA > = 3.5) && (workExperience > = 1)) { cout<<” Puts candidate name in the list.”; } Logical Operator AND Example: There are two (2) conditions: CGPA greater than or equal to 3.5 AND workExperience greater than or equal to 1 year if ((sales >= 5000.0) || (hoursWork > 80)) { bonus = 500.00; } else { bonus = 0; } There are two (2) conditions: sales greater than or equal to RM 5000.0 OR hoursWork greater than 80 hours Logical Operator OR Example: 18
if(!(sales <= 2500.0)) { bonus = 250.00; } else { bonus = 0; } Causes an opposite relation: NOT sales less than or equal to RM 2500.0 If sales = 2000.0 then, the condition (sales <= 2500.0) will returns TRUE. Logical Operator NOT Example: !(value1 == value2) is equal to (value1 != value2) !(value1 <= value2) is equal to (value1 > value2) !(value1 >= value2) is equal to (value1 < value2) !(value1 != value2) is equal to (value1 == value2) !(value1 > value2) is equal to (value1 <= value2) !(value1 < value2) is equal to (value1 >= value2) Note: value1 and value2 can be variable or constant Most of the time, however, you can avoid using ! by using the reverse logic shown on next slide. Convert this condition without using ! operator if ( !(A < B) && !(C != D) ) {...} Self-Test: 19
Example: #include <...> void main() { float test, assignment, final, sum; char grade, studentName[25]; cout<<” INPUT student name : “; cin>>studentName; cin>>test>>assignment>>final; sum = test + assignment + final; /* quit the program if sum out of range (1-100) */ if ((sum < 0) || (sum > 100)) { cout<<SORRY ! Invalid data …”; exit(0); /* quit the program immediately */ } /* check the grade */ if ((sum >= 80) && (sum <= 100)) grade = ‘A’; else if ((sum >= 66) && (sum <= 79)) grade = ‘B’; else if ((sum >= 50) && (sum <= 65)) grade = ‘C’; else if ((sum >= 40) && (sum <= 49)) grade = ‘D’ else grade = ‘F’; cout<<” Your grade is”<<grade; } An Application Example Determine the grade based on total marks for a student 80-100 A 66-79 B 50-65 C 40-49 D 0-39 F sum grade 20
Increment and decrement operators are unary operators that add or subtract one, to or from their operand, respectively. They are commonly implemented in imperative programming languages INCREMENT & DECREMENT
Increment & Decrement Operator Represent by ++ Add one to an integer variable Can be prefix or postfix increment Example: Description: a++; postfix increment a = a + 1; a += 1; ++a; prefix increment a = a + 1; a += 1; Compound assignment Increment Operator Equivalent Statements: Represent by -- Subtract one from an integer variable Can be prefix or postfix increment Decrement Operator Example: Description: a--; postfix increment a = a - 1; a -= 1; --a; prefix increment a = a - 1; a -= 1; Compound assignment Equivalent Statements: 22
Self test is to evaluate your understanding about operator in programming SELF TEST
Question 1 Write the resultant value of the following expressions 24 Expression Result 14 - 4 10 14 + 4 18 14 * 4 56 14/4 3.5 14 % 4 2
Question 2 Calculate the total marks for the given 3 subjects. Declare appropriate variables, assign values as given below: sejarah = 100 english = 85 fizik = 63 seni = 98 calculate the total marks calculate the average Example of program : Activity 2 Output 25 #include<iostream> using namespace std; int main( ) { int sejarah = 100, english = 85, fizik = 63, seni = 98; int total=0, average=0; total = sejarah + english + fizik + seni; average = total/4; cout << "Total for four subjects is : "<<total<<endl; cout << "Average is : "<<average<<endl; return 0; }
Question 3 Solve problem using Assignment and Arithmetic operators 1. Find the value for the following expression. Show your steps of solution. a) ( 1 + 2 ) + 6 * 4 / 2 – 1 b) ( 6 + 4 ) / 2 – 4 c) 6 * 3 / 6 + 9 d) 5 + 5 * ( 6 – 2) 26
Question 4 Given integer variables x = 10, y = 7 and z= 2.Determine the value of each of the arithmetic expression a) x + 2y – z b) x / z – (x * x + y) c) (x * y) % z d) 5 (x + y + z) – x / z 27
Question 5 Given the following declaration and initial assignments p = 6, q = 2 and r = 3. Determine the value of each of the following assignments. a) p + 3q - r b) p / r + ( p * p + r) c) r ( p +q ) (p –q) d) 12/ p + ( p + q – r) – 6 / r 28
Question 6 Solve problem using Relational and Logical operators. Determine whether the expression below is TRUE or FALSE if X = 2, Y = 6 and Fan = FALSE. Show your steps of solution. a) ( X ==Y ) || ( Y <=3 ) b) Fan && ( X > Y ) c) ( X >= 0 ) && ( X <= Y ) d) Fan && (! Fan) e) ! Fan || ! (! Fan) 29
Question 7 Given the value a = 0, b = 6 and c = 3. Write TRUE for the true expression and FALSE for the false expression. Show all the steps clearly. a) ! ( a == 0) && (b != 2) b) ( (a == c) && ( b == c) ) || (a < 1) c) ! ( !( c !=4) || !(4 ==2) || !(a==0) ) 30
Question 8 You are give 3 variables declarations: int a=1, b=2, c; What are the answers of a, b and c after execution of these statements? i. C = a++ + 2; ii. C = ++a + 2; iii. C = b-- - 2; iv. C = --b - 2; 31 Question 9 Create a program to calculate your BMI (Body Mass Index) by entering your height (M) and weight(KG). Categorize the BMI based on the table below. BMI Categories Underweight: < 18.5 Normal weight: 18.5 - 24.9 Overweight: 25 - 29.9 Obese: ≥ 30
32 Question 10 Run the program and display the output. #include <iostream> #include <string> using namespace std; int main() { int number = -4; string result; // Using ternary operator result = (number > 0) ? "Positive Number!" : "Negative Number!"; cout << result << endl; return 0;}
geeksforgeeks. (19 June, 2022). Retrieved from geeksforgeeks.org: https://www.geeksforgeeks.org/operators-c-c/ Halim, S. H. (2009). Asas Pengaturcaraan C++. Batu Caves: Venton Publishing(M) Sdn. Bhd. Malik, D. (2009). Brief Edition Introduction to C++ Programming . Boston USA: Cengage Learning . programiz. (21 Jun, 2022). Retrieved from programiz.com: https://www.programiz.com/cpp-programming/operators Sellappan, D. P. (2007). Visual C++ Programming. Batu Caves : Venton Publishing (m) Sdn Bhd . 33 Reference
By Time, Verily Man is in loss, Except those who believe and do good works, and enjoin one another to truth and patience. (Al- ‘Asr : 1 -3 ) 34 Notes
About the Author