PROBLEM: Compute the total salary of an employee. PROBLEM ANALYSIS: Input: Hours, Basic_salary, OT_rate Process: 1) Calculate overtime using formula: Overtime = OT_rate * Hours 2) Calculate salary using formula: Salary = Basic_salary + Overtime Output: Salary ALGORITHM: 1. Enter Hours, Basic_salary, OT_rate 2. Calculate overtime using formula: Overtime = OT_rate * Hours 3. Calculate salary using formula: Salary = Basic_salary + Overtime 4. Display Salary 42 Example: Sequential Different Patterns in Algorithm
PROBLEM: If student’s grade is greater than or equal to 60 Print “Passed” else Print “Failed” ALGORITHM: 1. Enter grade 2. If ( grade >= 60 ) print “Passed” Else print “Failed” 43 Different Patterns in Algorithm Example: Conditional
PROBLEM: Develop a program to print “DFC10212 is easy” for 5 times using looping. ALGORITHM: 1. Set n = 0 2. Check condition (n < 5) If true, print “DFC10212 is easy” Go to step 3 If false, process will end 3. Increase counter using formula: n = n + 1 Go to step 2 44 Different Patterns in Algorithm Example: Iterational
BBUuRrBgGeErR FrieBdURCBGhEicRken FreBnUcRBhGFErRies PROBLEM: Write an algorithm to calculate the total price for food as in figure above, based on price input by user for each item. ALGORITHM: 1. Insert burger_price, fried_chicken_price, french_fries_price 2. Calculate total price using formula: Total_price = burger_price + fried_chicken_price + french_fries_price 3. Display Total_price 45 Example 1 Problem Solving using Algorithm
PROBLEM: Write an algorithm based on the following scenario: Alisya went to the biscuit shop and she chose a box of biscuits. Each customer will get a discount of 5% during the shop anniversary promotion. Calculate the total payment need to be paid by Alisya after getting the discount. ALGORITHM: 1. Enter price of a box of biscuits 2. Calculate discount price using formula: Discount price = 0.05 * price of a box of biscuits 3. Calculate total payment using formula: Total payment = price of a box of biscuits - Discount price 4. Display Total payment 46 Problem Solving using Algorithm Example 2
Chapter 2 PROBLEM SOLVING METHODS 2.3 DIFFERENT TYPES AND PATTERNS IN ALGORITHMS 2.3.6 Describe flowcharts. 2.3.7 Identify the standardized symbols to visually represent various aspects of an algorithm or a process. 2.3.8 Represent the algorithm pattern (decisions and repetitive processes) in a flowchart. 2.3.9 Develop flowchart using problem solving tools. 47
A graphical representation of data, information and workflow using certain symbols that are connected to flow lines to describe the instructions done in problem solving. It shows the flow of the process from the start to the end of the problem solving. 48 Flowchart
Symbol Function Start/ End Process Input/ Output Decision Flow lines On page Connector Off page Connector 49 Flowchart Symbol
Enter data from keyboard / input device Task performing operation / formula Display data (result) START INPUT END PROCESS OUTPUT 50 Flowchart Sequential Processes
51 Flowchart Decisions Processes false grade >= 60 true print "Passed" print "Failed"
n<5? print "DFC10212 is easy" End Start No n++ Yes n=0 52 Flowchart Repetitive Processes
PROBLEM: Draw a flowchart to calculate the total rate for room by multiplying room rate by number of days and adding 10% room service charge. FLOWCHART: Start Enter room rate, number of days Rate = room rate * number of days Room service charge = 0.1 * Rate Total rate = Rate + Room service charge Display Total rate End 53 Problem Solving using Flowchart Example 1
PROBLEM: Draw a flowchart to represent the program design based on the following scenario: Amir went to the shoe store and he chose a pair of shoes. Each customer will get a discount of 20%. Calculate the total payment need to be paid by Amir after getting the discount. FLOWCHART: Discount price = 0.2 * price of a pair of shoes Total payment = price of a pair of shoes - Discount price Start Insert price of a pair of shoes End Display Total payment 54 Example 2 Problem Solving using Flowchart
Chapter 2 PROBLEM SOLVING METHODS 2.3 DIFFERENT TYPES AND PATTERNS IN ALGORITHMS 2.3.10 Describe pseudo code. 2.3.11 Explain the purpose of using pseudo code, guidelines and best practices. 2.3.12 Solve problem using pseudo code. 55
Steps in problem solving that is written half in programming code and half in human language. Pseudo code Example: START Input number1, number2, number3 Total = number1 + number2 + number3 Average = Total/3 Display Total, Average END 56
Purpose of using Pseudo code It is easier for people to understand than conventional programming language code. It is an efficient and environment-independent description of the key principles of an algorithm. Explaining a computing process to less technical people. Computers need a very strict input syntax to run a program, but humans (especially nonprogrammers) may find it easier to understand a language that clearly states the purpose of each line of code. 57
Keep things simple and separate your program into individual actions working on one action (statement) at a time. Indicated by writing one action after another, each action on a line by itself. The actions are performed in the sequence (top to bottom) that they are written. 58 Guidelines and Best Practices
Flowchart Pseudo code Definition A graphical representation of instructions done in problem using certain symbols that are connected to flow lines. Steps in problem solving that is written half in programming code and half in human language. Use Work well for small problems. Used for larger problems. Statement or symbols used Diagrammatic method which consists of terminator boxes, process boxes, and decision boxes, with flows of logic indicated by arrows. Which a mixture of English statement, Some mathematical notation, Selected keywords from programming language. 59 Differences between Flowchart and Pseudo code
BJUaRcBkGeEtR TBrUoRuBsGeErRs BBUlRoBuGsEeR PROBLEM: Write a pseudo code to calculate the total price for clothes as in figure above, based on price input by user for each item. PSEUDO CODE: START Input jacket_price, trousers_price, blouse_price Total_price = jacket_price + trousers_price + blouse_price Display Total_price END 60 Example 1 Problem Solving using Pseudo code
PROBLEM: Write a pseudo code to calculate the perimeter of a rectangle. PSEUDO CODE: START Input width, length Total_width = 2 * width Total_length = 2 * length PerimeterofRectangle = Total_width + Total_length Display PerimeterofRectangle END 61 Problem Solving using Pseudo code Example 2
PROBLEM: Compute the total salary of an employee. PROBLEM ANALYSIS: Input: Hours, Basic_salary, OT_rate Process: 1) Calculate overtime using formula: Overtime = OT_rate * Hours 2) Calculate salary using formula: Salary = Basic_salary + Overtime Output: Salary ALGORITHM: 1. Enter Hours, Basic_salary, OT_rate 2. Calculate overtime using formula: Overtime = OT_rate * Hours 3. Calculate salary using formula: Salary = Basic_salary + Overtime 4. Display Salary 62 Problem Solving using Algorithm, Pseudo code and Flowchart
FLOWCHART: Start Input Hours, Basic_salary, OT_rate Overtime = OT_rate * Hours Salary = Basic_salary + Overtime Display Salary End PSEUDO CODE: START Input Hours, Basic_salary, OT_rate Overtime = OT_rate * Hours Salary = Basic_salary + Overtime Display Salary END 63 Problem Solving using Algorithm, Pseudo code and Flowchart
D) Specification of program requirement Identify the first phase in Programming Life Cycle. A) Documentation B) Specify the problem C) Analyze the problem D) Design the algorithm Identify the phase to create an input, process, output (IPO) chart. A) Specify the problem B) Analyze the problem C) Implement the algorithm D) Design the algorithm Identify the INCORRECT content of documentation. A) Test results B) System performance C) User's manual book QUIZ! Time 1 2 3 Answ er: 1. B 2. B 3. B 64
D) Decision Select process X as in table below. A) Second = Hour * 60 B) Second = Hour * 3600 C) Second = Hour / 60 D) Second = Hour / 3600 Identify the symbol used in flowchart based on figure above. A) Data B) Process C) Decision D) Terminator Choose the CORRECT symbol based on figure above. A) Process B) Input/output C) Start/End QUIZ! Time Input Process Output Hour X Second 4 5 6 Answ er: 4. B 5. C 6. B 65
D) Input, process, output (IPO) Identify the definition of algorithm. A) A graphical instruction B) A formula for calculation C) An instruction to solve problem D) A computer program to compile Choose the BEST answer for the statement below. A) Program B) Algorithm C) Flowchart D) Pseudo code Identify the method to design a program based on figure below. A) Algorithm B) Flowchart C) Pseudo code QUIZ! Time 7 8 9 Answ er: 7. C 8. D 9. A The steps in problem solving that is written half in programming code and half in human language 1. Enter Mark_Quiz1, Mark_Quiz2, Mark_Quiz3 2. Calculate the addition of Mark_Quiz1, Mark_Quiz2 and Mark_Quiz3 and divide by 3. Average = (Mark_Quiz1 + Mark_Quiz2 + Mark_Quiz3)/3 3. Display Average 66
Write an algorithm based on scenario below. Answer : Lim has to calculate the total salary including bonus that received by his employee. Given bonus was 30% of the salary. Convert the problem to a pseudo code. Answer : QUIZ! Time 10 11 Zamri is a mathematic teacher. He wants to teach his students about how to convert weight in kilogram to gram. Help Zamri to solve his problem by construct an algorithm. *Hint: 1 kilogram is equivalent to 1000 gram 67
Write a pseudo code to calculate the BMI for a user. User is required to input height (meter) and weight (kilogram). Answer : Draw a flowchart to calculate the perimeter of a rectangle. Answer : QUIZ! Time 12 13 68
3.1.1 State the definition of data. 3.1.2 Explain the data types: numeric and non-numeric 3.1.3 Define identifier, variable, constant and reserved words. 3.1.4 State the naming convention rules for identifier. 3.1 DATA AND IDENTIFIER Chapter 3 FUNDAMENTALS OF PROGRAMMING LANGUAGE 69
Data refers to any information that can be stored, retrieved, or manipulated by a computer program. It represents the values, facts, or instructions that are input, processed, and output by software applications. It can be numbers, words, currency, or any other form of information that can be stored and processed by a computer. Definition of data 70
Data types is a classification of data that can be stored and manipulated within a program. They specify the size, format, and operations that can be performed on the data. Data type defines memory space for a particular variable in computer. 2 types of data: Numeric and Non-numeric data Data Types 71
Non-numeric data refers to information that is not represented by numbers. Numeric data refers to information that represents numbers. Data Types Numeric Non-numeric 72 It includes values that can be used for mathematical calculations and comparisons. Numeric data can be positive, negative, or zero, and it can have decimal points or be whole numbers. It includes various types of data that are not used for mathematical calculations or comparisons. Non-numeric data can be text, characters, symbols, or other forms of information that do not have a numerical value.
Floating-point Represents whole numbers. Can store both positive and negative values. Keyword : int Example: 0, +5, -10. Integer Represents floating numbers. Can store both positive and negative values. Suitable for representing real-world quantities that involve fractional parts, such as measurements or scientific calculations. Keyword : float Example: 5.2, 37.6, 440.35. Float Data Types Numeric Integer A type of floating-point data type that provides higher precision compared to float. Can store larger values and has a greater range than float. Suitable for applications that require higher precision, such as financial calculations or scientific simulations. Keyword : double Example: 65574.35585, 947.5856416 Double 73
Represents a single character that consists of all letters, numbers and special symbols. Character is surrounded by single quotation mark ‘ ‘. Keyword : char Example: 'a', 'B', '$', '5' Non-numeric Data Types Char Represents a collection of character that consists of all letters, numbers and special symbols. Character is surrounded by double quotation mark " ". Keyword : string Example: "JTMK PSIS", "pspd" String Represents a logical value indicating either true or false. Used in logical operations, conditions, and decision-making. Keyword : bool Examples: true, false Boolean 74
Match the following data types to its description. 4 1 2 3 Data Type Description float Used to represent a single character int Used to represent true or false values char Used to store decimal numbers with single precision bool Used to store whole numbers LET'S CHECK! LET'S CHECK! 75
Match the following data types to its description. 4 1 2 3 Data Type Description float Used to represent a single character int Used to represent true or false values char Used to store decimal numbers with single precision bool Used to store whole numbers Answer LET'S CHECK! LET'S CHECK! 76
"weight" is the identifier given to a variable that will be used to store an individual's weight in the program. The identifier "weight" can be used throughout the program to manipulate or access the value stored in that variable. Example of declaration: float weight; a name given to an entity in a program, such as a variable, function, class, or label. serves as a unique name that is used to refer to that particular thing within the program. must follow certain naming convention rules specified by the programming language being used. Identifier Example : 77
"mark" is a variable that has been declared with the type integer. the value assigned to "mark" is 88, which represents a quiz score. during execution of the program, the value of the "mark" variable can be changed. Example of declaration: int mark = 88; a named storage location in a program that holds a value. used to store and manipulate data during program execution. types of Variable determine the kind of data they can hold such as numbers, text etc. values that can be changed during the execution of the program. Variable Example : 78
Choose variable names that express the meaning or purpose of the information they contain. Avoid using single-letter names or abbreviations unless they are well-known within the context of the program. Make the code clearer for others to understand, including your future self, by using relevant words or phrases. Variable Tips for naming variables to enhance readability and maintainability Tips! 79
"Min_Score" is a constant with a value of 50. It is declared using the const keyword to indicate that its value cannot be changed once assigned. Example of declaration: const int Min_Score = 50; A constant is a value that remains unchanged during the execution of a program. It is a fixed value that cannot be modified once it is assigned. Constant Example : By using constants, if the value needs to be changed, you only need to update it in one place. Constants prevent accidental modification of important values and help catch errors at compile-time. Tips! 80
Naming Convention Rules for Identifier Valid Characters can include letters (both uppercase and lowercase), digits, and underscores must start with a letter or an underscore cannot start with a digit cannot use special characters E.g. !@#$%^&* cannot contain space, words are separated by underscores E.g. "my_variable" programming language has specific rules and conventions that must be followed when naming identifiers. to ensure clarity, readability, and adherence to best coding practices. Followings are naming convention rules for an identifier: 1 81
Naming Convention Rules for Identifier Case Sensitivity Most programming languages are casesensitive, so 'myVariable' and 'myvariable' would be considered different identifiers. Cannot use reserved words. They have special meaning and are used by the language itself E.g. if, for, while, int, double, Reserved Words 2 3 82
Determine whether the given identifier name is valid or invalid according to the naming convention rules. Give reason for the invalid identifier. QUIZ! Time 10 1 2 3 4 5 6 7 8 9 Identifier Invalid Valid/ Reason mystudent1 123Marks _car_plate class Price$ calculateSum() CONST_VALUE bool 2ndElement matric number 83
Determine whether the given identifier name is valid or invalid according to the naming convention rules. Give reason for the invalid identifier. QUIZ! Time 10 1 2 3 4 5 6 7 8 9 Identifier Invalid Valid/ Reason mystudent1 123Marks _car_plate class Price$ calculateSum() CONST_VALUE bool 2ndElement matric number 84 Answer Valid Invalid Valid Invalid Invalid Invalid Invalid Valid Invalid Invalid Start with digit Use reserved word Cannot contain space Use special character Use special character Use reserved word Start with digit
QUIZ! Time A program needs to store the details of a student, including their name, age, and grade. Identify the suitable variables and data types for the following program. 3. 1. 2. Variables Data types You are building a music player application and need to store the song title, artist name, and duration. Variables Data types A program is designed to manage a library system, and it needs to store the book title, author's name, and publication year. Variables Data types 85
QUIZ! Time A program is created to manage a product inventory, and it needs to store the product name, price, and quantity. Identify the suitable variables and data types for the following program. 6. 4. 5. Variables Data types In a game, you need to keep track of a player's score, level, and remaining lives. Variables Data types A program is designed to manage a library system, and it needs to store the book title, author's name, and publication year. Variables Data types 86
QUIZ! Time You are developing a calendar application and need to store event details such as event name, date, and start time. Identify the suitable variables and data types for the following program. 9. 7. 8. Variables Data types You are building a recipe app and need to store recipe names, ingredients, and instructions. Variables Data types A program is created to manage employee payroll and requires storing employee ID, hourly wage, and hours worked. Variables Data types 87
Chapter 3 FUNDAMENTALS OF PROGRAMMING LANGUAGE 3.2.1 Explain the following operators in a program: a. Assignment operators b. Arithmetic operators c. Relational operators d. Logical operators e. Increment and Decrement operators 3.2.2 Write expression to solve problem by using appropriate operators. 3.2 OPERATORS IN A PROGRAM 88
Used to assign values to variables. Allow to store and update values in variables, which are essential for manipulating data and performing computations. Basic assignment operator Equals sign (=) The most common assignment operator which assigns the value on the right-hand side to the variable on the left-hand side. Example: x = 8 Value 8 is assigned to the variable x. The variable x holds the value 8. Compound assignment operators Addition assignment (+=) Adds the value on the right-hand side to the variable on the lefthand side. Example: x += 3 Equivalent to x = x + 3. The value of x is incremented by 3. Assignment Operators Operators 89
Subtraction assignment (-=) Subtracts the value on the right-hand side from the variable on the left-hand side. Example: x -= 2 Equivalent to x = x - 2. The value of x is decremented by 2. Multiplication assignment (*=) Multiplies the variable on the left-hand side by the value on the right-hand side. Example: x *= 4 Equivalent to x = x * 4. The value of x is multiplied by 4. Division assignment (/=) Divides the variable on the left-hand side by the value on the right-hand side. Example: x /= 2 Equivalent to x = x / 2. The value of x is divided by 2. **Compound assignment operators can be used with other arithmetic operators like modulus (%) as well. Assignment Operators Operators 90
#include <iostream> using namespace std; int main() { int x = 5; int y = 3; // Basic assignment int a = x; cout << "a: " << a << endl; // Addition assignment x += y; cout << "x: " << x << endl; // Subtraction assignment y -= 2; cout << "y: " << y << endl; // Multiplication assignment a *= x; cout << "a: " << a << endl; // Division assignment x /= 2; cout << "x: " << x << endl; return 0; } Assignment Operators // Output: a: 5 // Output: x: 8 // Output: y: 1 // Output: a: 40 // Output: x: 4 Operators 91