The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

QuickLearner_ProblemSolvingProgramDesign

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Juhaina, 2023-09-03 23:06:22

QuickLearner PSPD

QuickLearner_ProblemSolvingProgramDesign

Quick Learner : Problem Solving & Program Design (2nd Edition) First Published 2021 Published 2021 (electronic) Politeknik Kuala Terengganu eISBN 978-967-2240-20-4 All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic, including photocopying, recording or by any information storage or retrieval system, without prior written permission from the publisher, Politeknik Kuala Terengganu Author : Yusnita Halim Napisah Harun Rosmayati Ismail Published by : Politeknik Kuala Terengganu, 20200 Jalan Sultan Ismail, Kuala Terengganu, Terengganu. Perpustakaan Negara Malaysia Cataloguing-in-Publication Data Yusnita Halim, 1979- QUICK LEARNER : PROBLEM SOLVING & PROGRAM DESIGN / YUSNITA HALIM, NAPISAH HARUN, ROSMAYATI ISMAIL. - 2ND EDITION. Mode of access: Internet eISBN 978-967-2240-20-4 1. Programming languages (Electronic computers). 2. Problem solving--Data processing. 3. Programming (Electronic computers). 4. Government publications--Malaysia. 5. Electronic books. I. Napisah Harun, 1984-. II. Rosmayati Ismail, 1976-. III. Title. 005.133


Praise Allah the Almighty for the knowledge and strength that He has granted upon us in writing this book. We would like to express our deepest appreciation to our team members for their unparalleled support towards the completion of this book. To our families, the completion of this book would not have been possible without their encouragement, care and support. Our appreciation also goes out for our friend and colleagues. Thank you for your advice, support, and constructive critics, etc. We are really grateful for your support and friendship. To our former students, thank you for your comments and feedback during the process for producing this book. For our students and others who will be using this book, we hope that this book will provide a better understanding in problem solving and program design. Finally, to everyone that have helped us in the production of this book, please accept our deepest thanks. May Allah bless you. Yusnita Halim Napisah Harun Rosmayati Ismail ACKNOWLEDGEMENTS


Chapter 1 : Introduction to Programming Language PREFACE This book is written specifically for the use of students who are studying Problem Solving and Program Design course in the form of a simpler infographic. The syllabus is written for polytechnic and foundation level for problem solving using C++ language, however, it can also be a useful guide for undergraduates. For each topic in this book, there are examples of activities and solutions provided. In addition, exercise questions were provided for each topics to enhance student’s understanding. The book has been organized by chapter. Chapter 1 covers the history of programming language. Included in this chapter are types of programming languages and it generations. In addition, this chapter also covers various language translators. Chapter 2 : Problem Solving Methods Chapter 2 explain about phases revolve in Programming Development Life Cycle (PDLC). Additionally it also covers about concept of problem solving and different types and pattern in algorithm to solve problem. Chapter 3 : Fundamentals of Programming Language Chapter 3 covers about data, identifier, variable and constant. It also discuss about various operators like assignment, logical, increment, decrement, arithmetic and relational. Furthermore, this chapter also explains about control structures for sequence, selection and looping by utilizing flowchart and pseudocode. Chapter 4 : Basic Programming Codes Chapter 4 covers the element of the programming language, its standards, best practices in programming and steps in creating a C++ program. In addition, it also covers the basic programming concepts. Finally, this chapter also includes a topic on constructing a pseudocode and flow chart based on a given program code.


This book is written with the intention of providing a quick reference for educators and students in problem solving and program design. Infographic concepts are applied to simplify and enhance readers understanding of the subject. This book provides quick reference and information for problem solving concepts with various activities and exercises. Upon completion of this book, students will be able to solve a programming problem for a different scenarios. Disclaimer: Images used is modified from the Internet and free PowerPoint template. The originals are solely held by their owner. INTRODUCTION


Table of Contents Chapter 1 Introduction to Programming Language Chapter 2 Problem Solving Methods Chapter 3 Fundamentals of Programming Language Data and Identifier Operator Control Structure Chapter 4 Basic of Programming Language 1 82 43 15 Page Acknowledgements Preface Introduction References


CHAPTER 1 1 Introduction to Programming Language Photo by freddie marriage on Unsplash


2 Chapter 1 | Introduction to Programming Language Electronic device. Machine Capable. Device. Computer Fundamentals Assembler Compiler Interpreter Translator Machine Assembly High Level Generations Set of rules Artificial language Example : C++, PHP, Java Programming Language Contents : History of programming language and approaches. Types of programming languages : Machine, Assembly, High Level Generations of programming language. Definitions of programmer, program and programming. Explain the language translators : Assembler, Compiler, Interpreter


3 Chapter 1 | Introduction to Programming Language 1.1 Fundamentals Electronic Device • Used to process data • Simply a calculator, which works automatic and quite fast. Machine Capable • Machine capable of solving problems and manipulating data. Device • May define computer as a device that transform data. How it Works? There are variety electronic device now that act as computer such as smartphone, tablet, laptop that comes in variety of brand.


4 Chapter 1 | Introduction to Programming Language 1.2 Language SET OF RULES A set of rules and reserved words (keywords) that can be used to tell a computer what are the operations to be done. ARTIFICIAL LANGUAGE Artificial language composed by a fixed vocabulary and set of rules is used to create instructions for the computer to follow. EXAMPLE Now, there are over 200 programming languages in the world. For example: Cobol, Pascal, C, C++, Fortran and Java. How it Works? Current programming language around the world are Python, Javascript, Java, PHP, C#, C++, Ruby, Go, Dart Language, Visual Basic, Haskell, SQL and so on.


5 Chapter 1 | Introduction to Programming Language 1.2 Language How Human Interact Example: People communicate using human languages, such as Bahasa Melayu, English and Japanese. How Human and Computer Interact Example : People communicate with computers using programming languages such as C, C++, Cobol, Java and PHP. Human, Computer Interaction Interaction HUMAN LANGUAGE (Example: BAHASA MELAYU) PROGRAMMING LANGUAGE (C, C++, COBOL, JAVA, PHP) Interaction


6 Chapter 1 | Introduction to Programming Language 1.3 of Programming Language Some text here 1 Machine Language (1950-1960) st Gen. Assembly Language (1950s) 2nd Gen. 3 High Level Language (start 1960s) rd Gen. o Called a procedural language. o Written as a series of English-like words. o Use translator (compiler or interpreter) to translate the program to machine language. o Not machine-dependent. o Known as symbolic language. o Use mnemonic codes. o Use assembler to translate the program to machine language. o Machine-dependent. o Known as query language. o Written as a series of English-like words. o Use to retrieve data from database. o Use translator (compiler or interpreter) to translate the program to machine o Known as knowledge-based language. language. o Written as a series of English-like words. o Programming language that resembles human language. 4 High Level Language (start 1960s) th Gen. 5th Gen. High Level Language (start 1960s) o Lowest level of language. o Represented data and program instructions as 1s and 0s – binary digits. o The ONLY language the computer could understand. o Machine-dependent.


7 Chapter 1 | Introduction to Programming Language Some text here 1 Machine Language (1950-1960) st Gen. Assembly Language (1950s) 2nd Gen. 3 High Level Language (start 1960s) rd Gen. o Advantage:- Machine-Independent. The program can be written and executed on any computer. Easy to be developed and maintained. o Advantages:- Program can run faster. An efficient use of the memory. o Disadvantages:- Errors can be made easily. Difficult to understand. It takes a long time to write the program. o Advantage:- Machine-Independent. The program can be written and executed on any computer. Easy to be developed and maintained. It is simpler and easier to o Advantage code. :- Machine-Independent. The program can be written and executed on any computer. Easy to be developed and maintained. 4 High Level Language (start 1960s) th Gen. 5th Gen. High Level Language (start 1960s) o Advantage : most efficient in terms of storage area and speed. o Disadvantage :- instruction and syntax in a program is not standardized. o Machine-dependent. Example: a program written in Apple PC cannot be run in IBM PC. 1.4 Advantage & Disadvantage


8 Chapter 1 | Introduction to Programming Language 1.5 of Programming Language Some text here Instruction to compute 2 * 4 Instruction to compute 2 * 4 Example : Mnemonic code Instruction to compute average of 3 numbers ‘BASIC PROGRAM ‘AVERAGING THREE INTEGERS PRINT “Mengira Purata” PRINT “---------------------“ PRINT “Nilai A = “; 20 PRINT “Nilai B = “; 30 PRINT “Nilai C = “; 40 PRINT “Purata tiga nombor ialah “; (20+30+40)/3 END Instruction to compute average of 3 numbers Create table order (OWNERID INT(5) NOT NULL UNIQUE, ITEM CHAR (40) NOT NULL); Example : Machine language Example : BASIC program Example : SQL Language


9 Chapter 1 | Introduction to Programming Language 1.6 of Program, Programming, Programmer Programmer o Person who writes the program. Programming o Programming is a process of designing / creating a program. Program o A set of step-by-step instructions that directs a computer to perform a specific task and to produce the required results. o It’s written in a programming language and is converted into the computer’s machine language.


10 Chapter 1 | Introduction to Programming Language 1.7 Some text here o It is a program that will checks syntax of a program to ensure the programming language is used correctly, by giving you the syntaxerror messages, which is known as diagnostics. o Translates a program into language that the computer can understand. o Produces descriptive error messages known as syntax-error to programmer if there are errors in the programs. o Syntax – set of rules to be followed when writing a program, these rules are similar to the grammatical rules in English. o Example: Message displayed on the screen is “please enter a number”. C++ Language : cout<<“please enter a number”; o Syntax Error– error in the use of a programming language. o Example in C++: Statement : system("pause") If semicolon (;) is not placed after statement, a message will display: “error C2143: syntax error : missing ';' before '}‘ ” The correct syntax is : system("pause");


11 Chapter 1 | Introduction to Programming Language 1.8 Some text here ASSEMBLER o Translates the whole program at one time. o Also called assembler program. o Convert assembly language to machine language. Sseg segment stack db 256 dup (?) Sseg ends dseg segment data db “2 x 4 = ” dseg ends cseg segment Assume cs:cseg:ds:sdeg:ss:sseg es:nothing Start proc far 11101 100000 100000 11110 10111000 11101000 11111100 10111000 10001110 11011000 10111000 10001110 11000000 Assembler Assembly Language Machine Language


12 Chapter 1 | Introduction to Programming Language 1.8 Some text here COMPILER o Translates the whole program at one time. o Translates the source code, for COBOL language to machine example language. o Used to translate C, COBOL and other language. o A program that translates from a low level language to a higher level one is a decompiler. # include <stdio.h> int main( ) { int x, y, z, sum; double avg; printf(" Enter 3 numbers:"); scanf("%d %d %d",&x, &y, &z); sum = x + y + z; avg = sum / 3; printf("x = %d y = %d z = %d", x, y, z); printf("the average is = %f", avg); return 0; } 11101 100000 100000 11110 10111000 11101000 11111100 10111000 10001110 11011000 10111000 10001110 11000000 Compiler C Language Machine Language


13 Chapter 1 | Introduction to Programming Language 1.8 Some text here INTERPRETER o Program that translates a high level language to machine language. o It translates one line at a time and executes each line after it is translated. o Displays feedback as the error occurred. o Used to translate BASIC and SQL language. ‘BASIC PROGRAM ‘AVERAGING THREE INTEGERS PRINT “Mengira Purata” PRINT “---------------------“ PRINT “Nilai A = “; 20 PRINT “Nilai B = “; 30 PRINT “Nilai C = “; 40 PRINT “Purata tiga nombor ialah “; (20+30+40)/3 END 10001110 11000000 10111010 10111011 10001101 110110 10111111 10110000 000000010 10110011 000001000 11100011 111111000 00001110 110000 10100000 10111001 10100100 Interpreter Basic Language Machine Language


14 Chapter 1 | Introduction to Programming Language Some text here 1. Write the definitions of : a) Programmer b) Programming c) Program d) Language translator Activity 1.1 Words Definitions a) Programmer Person who writes the program. b) Programming Process of designing/ creating a program. c) Program step-by-step instructions that directs a computer to perform a specific task and to produce the required results. d) Language translator program that will checks syntax of a program to ensure the programming language is used correctly, by giving you the syntax-error messages, which is known as diagnostics. Answer 1. List and explain generations of programming language. 2. State translator that translates high level language to machine language. 3. Differentiate between compiler and interpreter. Exercise 1.1 Answer 1. 2. 3. Compiler Interpreter


CHAPTER 2 15 Problem Solving Methods


16 Chapter 2 | Problem Solving Methods Specify the problem Analyze the problem Design algorithm Implement algorithm Test and verify Maintain and update Documentation Programming Life Cycle Terminator Connector Lines Process Input / Output Decision On and Off Page Reference Flowchart symbols Sequential Conditional Iterational Patterns in algorithm Input Process Output Problem Analysis Contents : Phase in Programming Life Cycle (PLC) Problem solving concept. Input, process and output. Identify the input, process and output based on problem statement. Different types and pattern in algorithm to solve problem.


17 Chapter 2 | Problem Solving Methods 2.1 in Programming Life Cycle (PLC) 01 Specify the problem To specify the inputs and outputs, processing requirements, system constraints, and error handling methods Analyze the problem To review program specifications, meeting with the analyst and users and identifying program components. Precisely define the problem to be solved and write program specifications. Design algorithm to solve problem Develop a detailed logic plan using a tool such as pseudocode, flowcharts, object structure diagrams, or event diagrams to group the program’s activities into modules. Plan a method of solution or algorithm for each module; and test the solution algorithms. 1 2 3 Implement the algorithm Translate the design into an application using a programming language or application development tool by creating the user interface and writing code. Test and verify the completed program Test the program, finding and correcting errors (debugging) until it is error free. There are three (3) types of error occur during this phase which are syntax error, logic error and runtime error. Maintain and update the program Provide education and support to end users. Correct any unanticipated errors that emerge and identify user-requested modifications (enhancements). Documentation Review and if necessary, revise internal documentation; formalize and complete end-user (external) documentation 4 5 6 7


18 Chapter 2 | Problem Solving Methods Apply the first 2 phase of PLC for the case study below: Problem: Annie wishes to bake a cake. But all the ingredients are weight is ounces. Please help Annie to convert the measurement in grams which is 1 ounces is equal to 28.4395g . Activity 2.1 Answer 1st phase - Specify the problem. In this phase, the development team visits the customer and studies their system. The essential purpose of this phase is to find the need and to define the problem that needs to be solved. 2nd phase - The development team will identify the types of cake to bake. Then check the ingredients need to bake a cake. They also studies about measurement and equipment's need to use to bake a cake. Identify the phase involve for the activities below:- 1. Develop a detailed logic plan. 2. This step is also known as programming phase. 3. Syntax error, logic error and runtime error always occur in this phase. Exercise 2.1 Answer 1. 2. 3.


Notes : 19 Chapter 2 | Problem Solving Methods 2.2 Different people use different techniques to solve problem. Thinking process and is part of the larger problem process that includes problem finding and problem shaping. A computer cannot solve a problem on its own. Programmer has to provide step by step solutions which the computer can understand and execute. Occurs when a system needs to move from a given state to a desired goal state. To be a good problem solver and good programmer, you must follow good problemsolving techniques. Write an algorithm. Identify the inputs and outputs Identify what needs to be computed. Identify other data and constants required to solve the problem.


20 Chapter 2 | Problem Solving Methods 2.3 Method for Input Process of entering data and programs in to the computer system Process Task of performing operations like arithmetic and logical operations Output Process of producing results from the data for getting useful information. Input Process Output


21 Chapter 2 | Problem Solving Methods Some text here • Assume that the transaction is money withdrawal. The instructions are below. Identify the IPO for each statements. » Get the card number from the user » Get pin number from the user » Process the input data » Get the transaction chosen by the user » Get the account type from the user » Process the transaction as wanted by the user » Withdraw amount of money required by the user » Print receipt for the user Activity 2.2 Discuss on steps needed to deposit cash on Cash Deposit Machine (CDM). Identify input, process and output. Exercise 2.2 Answer Input : » Get the card number from the user » Get pin number from the user » Get the transaction chosen by the user » Get the account type from the user Process : » Process the input data » Process the transaction as wanted by the user Output : » Withdraw amount of money required by the user » Print receipt for the user Answer Input : Process : Output :


22 Chapter 2 | Problem Solving Methods Write a program that will get 3 numbers as input from the users. Find the average and display the three numbers and its average. Activity 2.3 Answer Problem Analysis: Input : number1, number2, number3. Process: 1. Add the three numbers using formula: sum = number1 + number2 + number3 2. Calculate average using formula: average = sum / 3 Output: number1, number2, number3 and average Input Process Output


23 Chapter 2 | Problem Solving Methods How fast is a car traveling if it goes 50 miles in 2 hours? Activity 2.4 Answer Problem Analysis: Input : distance and timeHour Process: Calculate speed using formula : speed= distance / timeHour Output: speed Answer IPO Chart Input Process Output distance, timeHour speed = distance/time Hour speed Calculate the total fine charged by library for late return books. The charge is RM0.20 for 1 day Activity 2.5 Answer IPO Chart Input Process Output day total_fine= day x fine total_fine Answer Problem Analysis: Input : day Process: 1. Set fine = 0.20 2. Calculate total fine charge using formula : total_fine= day x fine Output: total_fine


24 Chapter 2 | Problem Solving Methods Answer IPO Chart Input Process Output Exercise 2.3 Answer Problem Analysis: Input : Process: Output: Uncle Ahmad wants to buy 5 cans of paint to paint his house. The price for a can of paint is RM 25.50. Calculate the price to be paid for 5 cans of paint that bought. Answer Problem Analysis: Input : Process: Output: Answer IPO Chart Input Process Output Exercise 2.4 Calculate and display the total mark of three quizzes, where the users have to enter the mark of each quiz.


25 Chapter 2 | Problem Solving Methods LOGIC and ALGORITHM Systematic logical approach which is a well-defined, step-by-step procedure that allows a computer to solve a problem. LOGIC Reasoning conducted or assessed according to strict principles of validity. A system in a computer or electronic device so as to perform a specified task. 03 02 01 PROGRAM DESIGN It is a framework or flow that shows the steps in problem solving. some organizational tools to help us solve problems on the computer such as the following. - Flowchart - Pseudocode


26 Chapter 2 | Problem Solving Methods 2.4 A sequence of instructions to solve a problem, written in human language. 01 A step-by-step procedure to solve a given problem. 02 An algorithm should always have a clear stopping point. 03 Algorithms for making things will divided into sections; The parts/components/ Ingredients (inputs) required to accomplish the task actions/steps/methods (processing) to produce the required outcome(output). 05 Programmer writes the problem solving in the form of an algorithm before coding it into computer language. 04 Algorithm can be developed using: Pseudo code (Similar to programming language) Flow chart 06


27 Chapter 2 | Problem Solving Methods 2.5 of good 01 Inputs and outputs should be defined precisely. 02 Each steps in algorithm should be clear. 03 Algorithm should be most effective among many different ways to solve a problem. 04 An algorithm shouldn't have computer code. 05 Algorithm should be written in such a way that, it can be used in similar programming languages. An example of algorithm and life for people use to make a recipe for a cake. Activity 2.6 Answer 1. Heat the oven at 180 Celsius. 2. Prepared the baking tin (mould). 3. Beat the butter and sugar. 4. Add eggs and vanilla essence. 5. Stir in the flour into the mixture. 6. Pour into a mould. 7. Put in the oven.


28 Chapter 2 | Problem Solving Methods An example of algorithm and life for student to attend a lecture in faculty. Activity 2.7 Answer Refinement step 1: wake up 1. rise out of bed at 6 am 2. brush the tooth and take bath 3. dawn prayer 4. make up bed Refinement step 2: preparation to attend class 1. Breakfast 2. Dressing 3. wear shoes Refinement step 3: heading to the faculty. 1. walk to the nearest bus stop 2. waiting for bus 3. boarding a bus 4. go to the lecture hall Answer 1. wake up 2. preparation to attend class 3. heading to the faculty. Identified the main steps, do the refinement algorithm for each step. Step 1,2 and 3 may be refined or detail. An example of algorithm and life for preparing a cup of coffee. Activity 2.8 Answer 1. boil water 2. add a cup of coffee 3. if necessary sugar 3.1. add sugar 4. if necessary cream 4.1 add cream 5. put hot water into the cup


29 Chapter 2 | Problem Solving Methods Answer : Problem Analysis Exercise 2.5 Answer : Algorithm Write a program that will get 3 numbers as input from the users. Find the average and display the three numbers and its average. Exercise 2.6 Write a program to calculate the area of a circle. Answer : Algorithm Answer : Problem Analysis


30 Chapter 2 | Problem Solving Methods 2.6 in A Sequential (Sequence structure): 1. step_1 2. step_2 3. step_3 : n. step_n B Conditional (The structure of the selection): if condition then code block true else code block is not true End if C Iterational (Repetition/Looping): repeat part to repeat until condition Example Sequential 1. Set total = 0 2. Input quiz1, quiz2 3. Calculate total quiz : total = quiz1 + quiz2 4. Display total Example Conditional 1. Enter testMark 2. Check testMark 2.1 If testMark >= 50 Display “PASS” 2.2 If not Display “Try Again” 3. Display statement Example Iterational (do..while) 1. Set no=0; Average = 0; Total = 0 2. Input number 3. Add Total using formula: Total = Total + number 4. Add Counter using formula: no = no + 1 5. Compare whether condition is less than 5 If yes , go to step 2 If not, go to step 6 6. Calculate Average of numbers using formula; Average = Total/5 7. Display Average


31 Chapter 2 | Problem Solving Methods 2.7 Flowchart is 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. Flowchart is a tool developed in the computer industry, for showing the steps involved in a process. Using flowchart, programmer can test the solution for bugs and go on to code the solution to the problem into a computer language for entry into the computer. Definition


32 Chapter 2 | Problem Solving Methods 2.8 symbol Symbol Name Function Terminator Indicates the starting or ending the program, process or interrupt program. Connector lines Shows direction of flow. Process Indicates any type of internal operation inside the processor or memory. Subroutine process/functions Used to invoke a subroutine or an interrupt program. Input / Output Used for any input / output operation. Indicates that the computer is to obtain data or output result. Decision Used to ask question that can be answered in binary format (Yes/No, True/False) Connector At same page Connector Off-page connector Start End A A 3 2


33 Chapter 2 | Problem Solving Methods 2.9 of using symbol Notes : START END Process Input Output Entering data from keyboard / input device Task performing operation / formula Display data


34 Chapter 2 | Problem Solving Methods 2.10 for flowcharting 4 3 2 1 All boxes of the flowchart are connected with Arrows. (Not lines) Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit point for all flowchart symbols is on the bottom except for the Decision symbol. The Decision symbol has two exit points; these can be on the sides or the bottom and one side. Generally a flowchart will flow from top to bottom. 8 7 6 5 Connectors are used to connect breaks in the flowchart. Examples are: From one page to another page. From the bottom of the page to the top of the same page. An upward flow of more then 3 symbols Subroutines and Interrupt programs have their own and independent flowcharts. All flow charts start with a Terminal or Predefined Process (for interrupt programs or subroutines) symbol. All flowcharts end with a terminal or a contentious loop.


35 Chapter 2 | Problem Solving Methods Convert algorithm into flowchart. Activity 2.9 Algorithm 1. Set Total=0, Average=0; 2. Input num1, num2, num3 3. Total up the 3 numbers Total= num1+num2+num3 4. Calculate average Average=Total/3 5. Display num1, num2, num3 and the average Answer : Flowchart START END Total=0, Average=0 Total= num1 + num2 + num3 Average= Total / 3 Display num1, num2, num3 Display Average Input num1, num2, num3 Algorithm 1. Set Pi=3.142 2. Input a radius value. 3. Calculate area using formula: area = Pi * radius * radius 4.Print the area of the circle. Exercise 2.7 Answer : Flowchart Convert algorithm given into flowchart.


36 Chapter 2 | Problem Solving Methods 2.11 Steps in problem solving, written half in programming code and half in human language. Helps programmer to “think out” the program. Advantage: Simple and easy to understand Semi-formal, English-like description of logic of the algorithm. For example, some parts uses C language code and some parts use Malay or English language. Definition START Input Statement Output END Format pseudocode


37 Chapter 2 | Problem Solving Methods 2.12 How to write 1 Computer can receive information Read (information from a file) Get (information from the keyboard) 2 Computer can put out information Write (information to a file) Display (information to the screen) 3 Computer can perform arithmetic Use actual mathematical symbols or the words for the symbols Example: Add number to total Total = total + number +, -, *, / Calculate, Compute also used SIX(6) basic computer operations. 4 Computer can assign a value to a piece of data Three (3) cases : i. To give data an initial value (using Initialize, Set) ii. to assign a value as a result of some processing “=‟ *x=5+y iii. to keep a piece of information for later use Save, Store 5 Computer can compare two piece of information and select one of two alternative actions. IF condition THEN some action ELSE alternative action ENDIF 6 Computer can repeat a group of actions WHILE condition (is true) some action ENDWHILE FOR a number of times some action ENDFOR


1 Each step must be clear and easy to understand. 2 Each step not more than 2 actions. 3 The steps are implemented sequentially. 4 Each step consists of keywords that describe the operation / action. 5 Statements in sequence can be grouped into blocks consisting of start and end keywords. 38 Chapter 2 | Problem Solving Methods 2.13 to write 6 Each step is written in a separate row, if necessary, the next line must be indent.


39 Chapter 2 | Problem Solving Methods Convert algorithm into pseudo code to calculate area of circle. Activity 2.10 Algorithm 1. Set Pi = 3.142 2. Input radius value. 3. Calculate the area using the given formula: area = Pi * radius * radius 4. Print the area of the circle. Answer : Pseudocode START Pi = 3.142 Input radius area = Pi * radius *radius Output area END Convert algorithm into pseudo code to calculate the average of 3 numbers. Algorithm 1. Set Total=0, Average=0 2. Input a, b, c 3. Total up the 3 numbers Total= a+b+c 4. Calculate average Average=Total/3 4. Display the average Exercise 2.8 Answer : Pseudocode


40 Chapter 2 | Problem Solving Methods Answer : Algorithm Exercise 2.9 Answer : Flowchart Write problem analysis, algorithm, pseudocode and flowchart for scenario below : You had bought a nice shirt which cost RM29.90 with 15% discount. Count the net price for the shirt. Answer : Pseudocode Answer : Problem Analysis


41 Chapter 2 | Problem Solving Methods 2.15 VS Pseudocode Flowchart • Steps in problem solving that is written half in programming code and half in human language • A graphical representation of instructions done in problem using certain symbols that are connected to flow lines • Work well for small problems • Used for larger problems • Which a mixture of English statement , some mathematical notation, selected keywords from programming language • Diagrammatic method which consists of terminator boxes, process boxes and decision boxes, with flow of logic indicated by arrows START Pi = 3.142 Input radius area = Pi * radius *radius Output area END Pi = 3.142 area= Pi * radius * radius Display area Input radius START END


CHAPTER 3 42 Fundamentals of Programming Language Photo by Aleks Dorohovich on Unsplash


43 Chapter 3 | Fundamentals of Programming Language Data Types A data type is a classification of the type of data that a variable or object can hold in computer programming. A data storage format that can contain a specific type or range of values. When computer programs store data in variables, each variable must be assigned a specific data type. Examples of data types include integers, floating point numbers, characters, strings, and arrays. Identifier Identifiers are used to name constants, variables, function names and labels. Identifiers are formed by combining letters (both upper and lower case letters) digits and the underscore ( _ ). Identifiers in C++ are case sensitive. Data Data is an array of facts that can be modified by computer into useful form for human. Users deal with data in ways that let them know what kind of information they are managed. Data is managed by the instructions in computer language. Examples of data are number, text, currency and others. Contents : Data and Data Types Identifier Variable and Constant


44 Chapter 3 | Fundamentals of Programming Language A variable is any measured characteristic or attribute that differs for different subjects. Variables also can be defined as identifiers whose value may change during the course of execution of a program. Each data used for computer program is stored in a variable. Variable Constants are used to store values that never change during the program execution. Using constants makes programs more readable and maintainable. Constants are expressions with a fixed value. Constant


Click to View FlipBook Version