Programming Fundamentals – ALF Module CC - 1101 PDF

Document Details

SuccessfulRing

Uploaded by SuccessfulRing

Laguna University

2024

Nomer B. Aguado

Tags

programming fundamentals computer science information technology programming

Summary

This document is a module for a programming course at Laguna University. It covers topics such as computer fundamentals, programming concepts, and programming languages.

Full Transcript

Programming Fundamentals – ALF Nomer B. Aguado College of Computing Studies Revision done on June 2024 i VISION Laguna University shall be a socially responsive educational institution...

Programming Fundamentals – ALF Nomer B. Aguado College of Computing Studies Revision done on June 2024 i VISION Laguna University shall be a socially responsive educational institution of choice providing holistically developed individuals in the Asia-Pacific Region MISSION Laguna University is committed to produce academically prepared and technically skilled individuals who are socially and morally upright ii Table of Contents Module 1: Introduction to Computer and Programming Fundamentals Introduction 1 Learning Outcomes 2 Lesson 1: Understanding Computer System 2 Major Components of Computer System 2 Hardware 2 Software 3 Software Classifications 3 Hardware and Software major operations 3 Hardware Concept 5 Software Concept 7 Peopleware – Human Resources 8 Information Processing Cycle 9 Basic Program Logical Sequence 10 Elements of a Computer Programs 11 Language 11 Data 13 Expression 16 Arithmetic expression 16 Mixed Arithmetic Expression 19 Order of Operation 19 String Expression 21 Boolean Expression 22 Relational Expression 22 Logical Expression 25 Mixed Logical Expression 27 Conversion of Algebraic to Program Expression 28 Formulation of Numeric Expression 29 Multi-lined Expression 30 Formulating Boolean Expression 31 Statements or Commands 33 Assessment Tasks 35 Summary 36 References 37 iii Course Code: CC 1101 - Computer Programming 1 (Fundamentals of Programming) Course Description: The course covers the use of general-purpose programming language to solve problems. The emphasis is to train students to design, implement, test and debug programs intended to solve computing problems using fundamental programming constructs. This course is an introductory lecture/lab course on the basic foundation in programming. This course deals with the basic programming concepts with the applications of the common program designing tools such as flow chart and pseudocode; program structures like conditions, loops, and iterations, branching, sorting, and array processing. Course Intended Learning Outcomes (CILO): At the end of this course, the students should be able to: 1. Identify and describe the basic program elements, components and structures 2. Analyze simple problems, and identify and define the computing requirements for the problem 3. Demonstrate and apply the fundamental steps in the program development 4. Construct the general form/format/syntax inf a computer program independently based on applicable program design technique/paradigm. 5. Appreciate the values and importance of computer programming as a solution tool. Course Requirements: ▪ Assessment Tasks (AT) - 60% ▪ Major Exams (ME) - 40% Periodic Grade 100% Prelim Grade (PG) = (AT x 60%) + (ME x 40%) Midterm Grade (MG) = ((AT x 60%) + (ME x 40%)) x 70%)+(PG x 30%) Final Grade = ((AT x 60%) + (ME x 40%)) x 70%)+(MG x 30%) iv Module for Prelim v MODULE 1 Introduction to Computers and Programming Fundamentals Introduction Many professions require some form of programming. Accountants program spreadsheets; musicians program synthesizers; authors program word processors; and web designers program style sheets. The typical course on programming teaches a “tinker until it works” approach. When it works, students cry out “It works!” and move on. Sadly, this phrase is also the shortest lie in computing, and it has cost many people many hours of their lives. This module focuses on habits of good programming, addressing both professional and vocational programmers. By “good programming,” we mean an approach to the creation of software that relies on systematic thought, planning, and understanding from the very beginning, at every stage, and for every step. To emphasize the point, we speak of systematic program design and systematically designed programs. This, articulates the principle of the desired functionality. Good programming also satisfies an aesthetic sense of accomplishment; and the elegance of a good program. There are different ways on how people use computers. In school, students use computers for tasks such as writing papers, searching for articles, sending email, and participating in online classes. At work, people use computers to analyze data, make presentations, conduct business transactions, communicate with customers and co-workers, control machines in manufacturing facilities, and do many other things. At home, people use computers for tasks such as paying bills, shopping online, communicating with friends and family, and playing computer games. Computers can do such a wide variety of things because they can be programmed. This means that computers are not designed to do just one job, but to do any job that their programs tell them to do, an instructions that a computer follows to perform a task. Programs are commonly referred to as software. Software is essential to a computer because it controls everything the computer does. Students will be 1 trained and learn the steps in problem solving as well as the Systems Development Life Cycle. These concepts will help the students on how to solve problems and create programs systematically and logically. Learning Outcomes At the end of the lesson, the student is expected to: 1. Understand concept of computer system; 2. How a computer executes a program 3. Apply the steps involved in the program development cycle 4. Demonstrate and understand Programming and user environments 5. Enumerate and define the different elements of a computer program 6. Formulate expressions with ease 7. Evaluate and simplify expressions 8. Enumerate and explain the classification of commands 9. How a computer solves a problem Lesson 1: Understanding Computer Systems Computer System A computer system is a combination of all the components required to process and store data using a computer. Every computer system is composed of multiple pieces of hardware and software. (Farrell, 2015) ❖ Major components of computer system: Hardware, software, and human resources Hardware is the equipment, or the physical devices, associated with a computer. For example, keyboards, mice, speakers, and printers are all hardware. The devices are manufactured differently for computers of varying sizes—for example, large mainframes, laptops, and very small devices embedded into products such as telephones, cars, and thermostats. However, the types of operations performed by different-sized computers are very similar. When you think of a computer, you often think of its physical components first, but for a computer to be useful, it needs more than devices; a computer needs to be given instructions. Just as your stereo equipment does not do much until you provide music, computer hardware needs instructions that control how and when data items are input, how they are processed, and the form in which they are output or stored. 2 Software is computer instructions that tell the hardware what to do. Software is programs, which are instruction sets written by programmers. You can buy prewritten programs that are stored on a disk or that you download from the Web. For example, businesses use word-processing and accounting programs, and casual computer users enjoy programs that play music and games. Alternatively, you can write your own programs. When you write software instructions, you are programming. This module focuses on the programming process. Software can be classified into two broad types: Application software comprises all the programs you apply to a task, such as wordprocessing programs, spreadsheets, payroll and inventory programs, and games. When you hear people say they have “downloaded an app onto a mobile device,” they are simply using an abbreviation of application. System software comprises the programs that you use to manage your computer, including operating systems such as Windows, Linux, or UNIX for larger computers and Google Android and Apple iOS for smartphones. This module focuses on the logic used to write application software programs, although many of the concepts apply to both types of software. Together, computer hardware and software accomplish three major operations in most programs: Input—Data items enter the computer system and are placed in memory, where they can be processed. Hardware devices that perform input operations include keyboards and mice. Data items include all the text, numbers, and other raw material that are entered into and processed by a computer. In business, many of the data items used are facts and figures about such entities as products, customers, and personnel. However, data can also include items such as images, sounds, and a user’s mouse or finger-swiping movements. Processing—Processing data items may involve organizing or sorting them, checking them for accuracy, or performing calculations with them. The hardware component that performs these types of tasks is the central processing unit, or CPU. Some devices, such as tablets and smartphones, usually contain multiple processors. Writing programs that efficiently use several CPUs requires special techniques. Output—After data items have been processed, the resulting information usually is sent to a printer, monitor, or some other output device so people can view, interpret, and use the results. Programming professionals often use the term data for input items, but use the term information for data 3 that has been processed and output. Sometimes you place output on storage devices, such as your hard drive, flash media, or a cloud-based device. (The cloud refers to devices at remote locations accessed through the Internet.) People cannot read data directly from these storage devices, but the devices hold information for later retrieval. When you send output to a storage device, sometimes it is used later as input for another program. We write computer instructions in a computer programming language such as Visual Basic, C, C#, C++, or Java. Just as some people speak English and others speak Japanese, programmers write programs in different languages. Some programmers work exclusively in one language, whereas others know several and use the one that is best suited to the task at hand. The instructions you write using a programming language are called program code; when you write instructions, you are coding the program. Every programming language has rules governing its word usage and punctuation. These rules are called the language’s syntax. Mistakes in a language’s usage are syntax errors. If you ask, “How the gee too store do I?” in English, most people can figure out what you probably mean, even though you have not used proper English syntax—you have mixed up the word order, misspelled a word, and used an incorrect word. However, computers are not nearly as smart as most people; in this case, you might as well have asked the computer, “Xpu mxv ort dod nmcad bf B?” Unless the syntax is perfect, the computer cannot interpret the programming language instruction at all. When you write a program, you usually type its instructions using a keyboard. When you type program instructions, they are stored in computer memory, which is a computer’s temporary, internal storage. Random access memory, or RAM, is a form of internal, volatile memory. Programs that are currently running and data items that are currently being used are stored in RAMfor quick access. Internal storage is volatile—its contents are lost when the computer is turned off or loses power. Usually, you want to be able to retrieve and perhaps modify the stored instructions later, so you also store them on a permanent storage device, such as a disk. Permanent storage devices are nonvolatile—that is, their contents are persistent and are retained even when power is lost. If you have had a power loss while working on a computer, but were able to recover your work when power was restored, it’s not because the work was still in RAM. Your system has been configured to automatically save your work at regular intervals on a nonvolatile storage device—often your hard drive. After a computer program is typed using programming language statements and stored in memory, it must be translated to machine language that represents the millions of on/off circuits within the computer. Your programming language statements are called source code, and the translated machine language statements are object code. Each programming language uses a piece of software, called a compiler or an interpreter, to translate your source code into machine language. Machine language is also called binary language, and is represented as a series of 0s and 1s. The compiler or interpreter that translates your code tells you if any programming language component has been used incorrectly. Syntax errors are relatively easy to locate and correct because 4 your compiler or interpreter highlights them. If you write a computer program using a language such as C or C++ but spell one of its words incorrectly or reverse the proper order of two words, the software lets you know that it found a mistake by displaying an error message as soon as you try to translate the program. Although there are differences in how compilers and interpreters work, their basic function is the same—to translate your programming statements into code the computer can use. When you use a compiler, an entire program is translated before it can execute; when you use an interpreter, each instruction is translated just prior to execution. Usually, you do not choose which type of translation to use—it depends on the programming language. However, there are some languages for which both compilers and interpreters are available. After a program’s source code is successfully translated to machine language, the computer can carry out the program instructions. When instructions are carried out, a program runs, or executes. In a typical program, some input will be accepted, some processing will occur, and results will be output. Besides the popular, comprehensive programming languages such as Java and C++, many programmers use scripting languages (also called scripting programming languages or script languages) such as Python, Lua, Perl, and PHP. Scripts written in these languages usually can be typed directly from a keyboard and are stored as text rather than as binary executable files. Scripting language programs are interpreted line by line each time the program executes, instead of being stored in a compiled (binary) form. Still, with all programming languages, each instruction must be translated to machine language before it can execute. Hardware: (Gaddis, 2016) CONCEPT: The physical devices that a computer is made of are referred to as the computer’s hardware. Most computer systems are made of similar hardware devices. The term hardware refers to all of the physical devices, or components, that a computer is made of. A computer is not one single device, but a system of devices that all work together. Like the different instruments in a symphony orchestra, each device in a computer plays its own part. If you have ever shopped for a computer, you’ve probably seen sales literature listing components such as microprocessors, memory, disk drives, video displays, graphics cards, and so on. Unless you already know a lot about computers, or at least have a friend who does, understanding what these different components do can be confusing. 5 Figure 1. Desktop Computer (Wempen) As shown in the next figure (Figure 2), a typical computer system consists of the following major components: The central processing unit (CPU) Main memory Secondary storage devices Input devices Output devices Figure 2. Typical components of a computer system 6 Computer Software Software, commonly known as programs or apps, consists of all the instructions that tell the hardware how to perform a task. These instructions come from a software developer in the form that will be accepted by the platform (operating system + CPU) that they are based on. For example, a program that is designed for the Windows operating system will only work for that specific operating system. Compatibility of software will vary as the design of the software and the operating system differ. Software that is designed for Windows XP may experience a compatibility issue when running under Windows 2000 or NT. (Mullins, 2017) Software is capable of performing many tasks, as opposed to hardware which can only perform mechanical tasks that they are designed for. Software provides the means for accomplishing many different tasks with the same basic hardware. Practical computer systems divide software systems into two major classes: (Mullins, 2017) A pre-written program is any type of software program that is configured to provide specific solutions or fixes for certain types of functions. Unlike other types of software, canned software products are not designed to allow much in the way of customization. Typically, the canned program is designed to be used in specific ways and to perform specific tasks (What Is a Canned Program?, 2022). They can be bought from any software distributors that are stored in disk or can be downloaded from the internet. This program is sometimes called canned program and are ready to use. On the other hand, you can write your own program. When you do so, it is called programming. Programming is the process of giving machines a set of instructions that describe how a program should be carried out. It is the process that professionals use to write code that instructs how a computer, application or software program performs. At its most basic, computer programming is a set of instructions to facilitate specific action. Programmers spend their whole careers learning a variety of programming languages and tools so they can effectively build computer programs. The program written by a programmer is commonly called customized programs. These are written according to the user’s needs. Software are classified in two broad types: Application software. Application Software is a type of computer program that performs specific functions. These functions, performed by application software, can be personal, business as well as educational. Thus, application Software is also known as end-user software or productivity software (OpenXcell, 2021). These are program that are use do certain task, such as word processing, spreadsheet, payroll, games, inventory and the like. System software. The system software is a collection of programs designed to operate, control, and extend the processing capabilities of 7 the computer itself. System software is generally prepared by the computer manufacturers. These software products comprise of programs written in low-level languages, which interact with the hardware at a very basic level. System software serves as the interface between the hardware and the end users. Some examples of system software are Operating System, Compilers, Interpreter, Assemblers, etc. (Computer - Software, 2022). Programs that is use to manage computer in its overall operations. These would include operating system, utilities and I/O operations. Software is generally created (written) in a high-level programming language, one that is (more or less) readable by people. These high-level instructions are converted into "machine language" instructions, represented in binary code, before the hardware can "run the code". When you install software, it is generally already in this machine language, binary, form. In this course, programs will be created using C as the high-level programming language. (Mullins, 2017) Figure 3. Examples of System Software (right) and Application Software (left) Peopleware or Human Resources Peopleware refers to the human role in an IT system. It encompasses various aspects related to the involvement of people in the development and utilization of computer software and hardware systems. Here are some key points about peopleware: 1. Development Productivity: Peopleware addresses the productivity of developers and teams. It explores how individuals and groups can work efficiently to create high-quality software. 8 2. Teamwork and Group Dynamics: Understanding how teams collaborate, communicate, and function is crucial. Effective teamwork contributes to successful project outcomes. 3. Psychology of Programming: Peopleware delves into the psychological aspects of programming. It considers factors such as motivation, cognitive load, and decision-making. 4. Project Management: Managing projects involves coordinating people, resources, and timelines. Peopleware examines project management practices that lead to successful software development. 5. Organizational Factors: The organizational context significantly impacts software development. Peopleware considers organizational culture, learning, and adaptability. 6. Human Interface Design: Creating user-friendly interfaces requires an understanding of human behavior and cognitive processes. Peopleware emphasizes designing interfaces that align with users’ mental models. 7. Human–Machine Interaction: How humans interact with machines (software and hardware) affects usability and efficiency. Peopleware explores ways to optimize this interaction. The term “peopleware” gained prominence through the book “Peopleware: Productive Projects and Teams” by Tom DeMarco and Timothy Lister in 19871. It continues to be relevant in the field of information technology, emphasizing that successful systems depend not only on hardware and software but also on the people behind them. To sum up, peopleware recognizes that technology is shaped by human factors, and fostering a positive, collaborative environment is essential for achieving successful outcomes in software development and system implementation. ❖ Information Processing Cycle The information processing cycle, in the context of computers and computer processing, has four stages: input, processing, output and storage (IPOS). However, at some levels within a computer, some processing devices actually only use three of these stages -- input, processing and output -- without the need to store data. Each of these stages plays an important role in the collection, analysis and distribution actions performed by a computer system. Figure 4. Information Processing Cycle 9 Basic Program Logical Sequence In a computer-oriented data processing system, there are four logical sequences that are being followed and done, they are: 1. Input 2. Process 3. Output 4. Storage Inputs are provided by users and are needed by the computer hardware for it (hardware) to do something depending on what instruction is to be done. After data has been entered, they are stored in the memory where processing then takes place. Processing is the manipulation of data based on the instruction given, either mathematically or logically such as organizing, sorting, calculations, etc. and are done by the Central Processing Unit or CPU. When processing is done, output or result can now be retrieved. Output, which is also considered as information are processed data, organized and made more meaningful and important to the person receiving it. Storage. It is the saving of important data/information into the memory or a storage device/s. All data that is stored in a computer is converted to sequences of 0s and 1s. A computer’s memory is divided into tiny storage locations known as bytes. One byte is only enough memory to store a letter of the alphabet or a small number. In order to do anything meaningful, a computer has to have lots of bytes. Most computers today have millions, or even billions, of bytes of memory (Tony Gaddis, 2019). From input to processing, to output and then to storage, instructions to a computer are written in a computer programming language. Programmers write program in different languages that computer can understand like Java, C/C++, C#, VB.Net, Go, Python, PHP, Javascript and many many more. Just like human who use English, Filipino, French and many more. No matter what language a computer programmer uses, he/she follows certain rules called syntax. This syntax rules must be observed properly. Computer languages have translators that are commonly called compilers or interpreters that will tell you if you have used the language correctly or otherwise. This incorrect usage of language syntax is called syntax error which is easier for the programmer to see as specified by the interpreter. Meaning, interpreter will let you know there is a mistake as you run the program. The program must be translated into machine language or binary language that represents million of on/off circuits within the computer. Program statements are called source program and the translated machine language statements is called object code. 10 For the program to work properly, program instructions must be given to the computer following a certain order. This order is called the logic of the computer program. Logic is the order by which instructions are written. Once instructions are entered into the computer, it can now be executed. Computer evaluates from the top of the list. ❖ Elements of Computer Programs: Computer program. As mentioned in the previous chapter, program is a list of instructions or commands written in a programming language, arranged logically that tells what the computer should follow. Computer programs can be divided into; 1. system programs, 2. utility programs 3. application programs. System programs refer to all programs that require the computer to function effectively. It is the intermediary or the bridge that links computer users and the hardware. Utility programs are programs provided so that user can maintain the computer system, Application programs written by user to obtain solution to a specific problem that transform a computer machine into a tool for performing a specific kind of work. Computer program is composed of different elements, they are: 1. language; 2. data; 3. expression/operation; 4. statement or command. Language: The process of program design and implementation is called programming. At this point, user or programmer must specify the operation that should be done and to be performed. Programs however, are written in various programming languages. A programming language is an artificial language that can be used to control the behavior of a machine, particularly a computer. Programming 11 languages, like human languages, are defined through the use of syntactic and semantic rules, to determine structure and meaning respectively. Programming languages are used to facilitate communication about the task of organizing and manipulating information, and to express algorithms precisely. Some authors restrict the term "programming language" to those languages that can express all possible algorithms; sometimes the term " computer language" is used for more limited artificial languages (Programming Language, 2022). Thousands of different programming languages have been created, and new ones are created every year. Programming languages are divided into three levels: 1. high-level languages 2. middle-level language - hybrid 3. low-level languages. High-level programming languages (HLL), such as PASCAL, BASIC, or C allows the programmers to express the program using keywords or reserved words and syntax that resemble to human natural language. Each statement in a high-level language corresponds to several machine language instructions so you can write programs more easily and quickly compared to a low-level programming language. However high-level language runs more slowly than that of programs written in a lower level of programming language. High-level language Programmers find machine code difficult to learn, program in and debug. As a result, the majority of programmers write programs in high-level programming languages. These languages are close to natural language - the spoken and written language of humans C, C++, Java, Perl and COBOL are some of the examples of high-level language which lets the developer focused on the logic of the problem to be solved. (Bitesize, 2020). Low-level programming languages (LLL), such as assembly language, allow programmers to code the instruction with the maximum possible efficiency. Using the low-level language requires more detailed expertise about exact capabilities of a given computer system and its microprocessor. Programming in a lower-level language requires more time. 12 Machine language Machine language, the numeric codes for the operations that a particular computer can execute directly. The codes are strings of 0s and 1s, or binary digits (“bits”), which are frequently converted both from and to hexadecimal (base 16) for human viewing and modification. Machine language instructions typically use some bits to represent operations, such as addition, and some to represent operands, or perhaps the location of the next instruction. Machine language is difficult to read and write, since it does not resemble conventional mathematical notation or human language, and its codes vary from computer to computer. (Computer Programming Language | Encyclopedia Britannica, n.d.) Assembly language Assembly language is one level above machine language. It uses short mnemonic codes for instructions and allows the programmer to introduce names for blocks of memory that hold data. One might thus write “add pay, total” instead of “0110101100101000” for an instruction that adds two numbers. (Computer Programming Language | Encyclopedia Britannica, n.d.) Assembly language is designed to be easily translated into machine language. Although blocks of data may be referred to by name instead of by their machine addresses, assembly language does not provide more sophisticated means of organizing complex information. Like machine language, assembly language requires detailed knowledge of a particular internal computer architecture. It is useful when such details are important, as in programming a computer to interact with input/output devices (printers, scanners, storage devices, and so forth). (Hemmendinger, 2018) Data: Computer data can be defined as a representation of facts, concepts, or instructions in a formalized manner, which should be suitable for communication, interpretation, or processing by human or electronic machine. Data is represented with the help of characters such as alphabets (A-Z, a-z), digits (0-9) or special characters (+,-,/,*,,= etc.) (Computer - Data and Information, 2022). Data is a collection of factual information which are either in the form of numbers, letters, or symbols. Data are needed by the computer, for it to function through the program installed into it. Without the presence of data, computer has nothing to do or manipulate. Data are like raw materials as far as production of goods is concern. Data are called an input data if they are entered into the machine through input 13 devices and are transformed by the computer machine, through a program, into an output data which is commonly called information. Data are categorized or classified into two: 1. the numeric 2. the non-numeric. Numeric data are used for mathematical computations. Numeric data items can be an integer (whole number) or a real number (with a decimal or floating point or fractional part). Non-numeric data is composed of alphanumeric (letters or numerical figures) character or any special symbol, such as $, ! etc. Non-numeric data are usually organized into sequences of characters enclosed in an open and close quotation mark ( “ or ‘ ) and are commonly called string. Non-numeric or string data are used for giving description and identification to where they are intended for. These are not normally used for mathematical computation but rather used for description and/or identification. Data are used or represented in a program as 1. constant 2. variable. Constant: Constant is a data item that is commonly described as literal value. This data item does not change during program execution. Constant can be of numeric or string (non-numeric) in type. Numeric Constant: Numeric constant maybe an integer or a real numbers which may either be preceded by a positive (+) or a negative (-) sign. Example: integers real 100 10.3526 10 0.125 +25 -0.143 -125 +13.425 Numeric constant may contain only of the following characters: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,. , +, -. No other characters must appear or must be used together with the characters shown above. 14 Example of illegal constant with illegal characters. 100,000 - comma is not allowed. $ 125.00 - $ symbol to signify monetary value is not allowed. 10 inches - inches as a description should not be used. 18 ¼ - slash (/) is a symbol of division and is not allowed. String Constant: String constant is a group of characters enclosed in constant may include numerical form (numbers 0-9), letters from A-Z or a-z and all other characters like $, space, % and etc. Example of string constants. “A” “ ” “14344” “Gorio’s Store” “How are you” “200” Variable: Variable is the names we give to computer memory locations which are used to store values in a computer program (Computer Programming - Variables, 2022). It is a named data item, the value of which may change during the execution of the program. The values stored in a variable are not permanent. They may change, through program execution, and that they can only hold a certain value at any given time. During the program execution, variables reside in the memory of the computer. Variables should be given their own unique (no duplication) name. (Variable name are normally called identifier). Name of variables are given based on the following rules or requirements: a) must contain only letters, numbers and an underscore character ( _ ) b) must always begin with a letter c) must be unique (no duplication of names) d) must not be a keyword or reserve word (keyword are word with a special meaning to the computer like commands or statements) e) should not start with a number Examples: X GRP1 GRP2 STUDENT_ID Grand_total X3 Total A243B X2X 15 Variable is used to store data of either numeric or string depending on the declared type of the variable (as numeric variable or string variable). Numeric variable is a variable that can contain or hold values of numeric types only while string variable can hold of values of type string or non-numeric only. Variable, when used in a program should be declared to specify the name and the type. Normally, declaration of variables is placed at the beginning of the program or on the specific area required by the language program-structure being used. Expression: An expression is a particular concept in computer science in which a number of variables or constants, and operators and functions, are put together in a single statement that is acted on by a particular programming language (Techopedia, 2014). It is a program element consisting of operands separated by an operator which yield a value of a certain type depending on the type of an expression used. Operands can be any data item (constant or variable). Operator is a symbol that expresses the operation to be done. These operators can be arithmetic, logical, relational, and string. Expressions are of different types, they are: a) arithmetic expression b) string expression c) Boolean expression Arithmetic Expression: Arithmetic expression is sometimes called numeric expression, consisting numeric constant or numeric variable operands, separated by an arithmetic operator, which yield a numeric value. Arithmetic operators are the following: operators operation to be done + addition - subtraction * multiplication / real division (result is real number) div, / integer division (result is an integer number) 16 mod, % modulus division (extract the remainder) ^ , ** exponentiation (in Basic) -- decrement ++ increment Arithmetic expression format: 1) operand operator operand 2) operand operator operand operator operand… Examples: 403 + 205 constant operand constant operand operator A * B variable operand variable operand operator constant operand variable operand X / 5 + B variable operand operators Examples of arithmetic expression a) 25 div 5 b) 25 mod 5 5 0 c) 25 * 3 d) 250.0 / 80.0 17 75 3.125 e) 125 - 75 f) 50 + 80 50 130 Div or / and mod or % operators: Div or / and mod or % operators might be new to you. These operators use integer operands and yield an output value which is also an integer. Div or % operator yields a truncated quotient (no floating point or decimal number) while mod extract the remainder of a division operation. Example of div or / operation Solution: a) 5 div 3 1 since 2 is no longer divisible 3 5 by 3 so the operation stop 1 3 having 1 as the quotient. 2 b) 25 / 5 5 5 25 25 5 0 c) 4 / 5 0 5 4 0 0 4 Example of mod operation a) 5 mod 3 1 since 2 is no longer divisible by 3 the operation stops getting 2 as 3 5 the remainder. 2 3 2 b) 25 % 5 5 18 5 25 0 25 0 c) 4 % 5 0 5 4 4 0 4 Mixed Arithmetic Expression: Mixed expression is an expression having several operands and operators. Parenthesis can be used to group a sequence or certain portion of an expression. Examples: 8+4–3 9 * ( 3 + 25 ) ( 5 ^ 2 + ( 35 – 30 ) % 3 ) mod 5 When dealing with mixed expressions, precedence rule or order of operation must be considered. Operators with the highest priority must be done first. Order of operation according to priority Highest priority 1) ( ) expression in parenthesis 2) ^ 3) *, /, / or div, mod or % 4) +, - Lowest priority If you could notice *, /, % or div, and mod are of the same priority as well as – and +. In this case the rule of left-to-right sequence should be observed. Operator on the left side will be done first. In any expression, operations inside parenthesis are done first. In the case that parenthesis encloses mixed operations, order of precedence is in effect. Nested parenthesis (a parenthesis inside another parenthesis) the innermost parenthesis is evaluated first ahead of the outer parenthesis. 19 In case parentheses are of equal priority (equal level) the left -to- right sequence is also in effect. Example of evaluation: a) 10 + 25 * 2 * has a higher priority than + 10 + 50 60 b) 30 div 5 * 4 div and * have the same priority, left-to-right sequence is to be followed 6 * 4 24 c) 5 * 3 + 12 mod 5 – 2 ^ 2 ^ has the higher priority then the * and mod where left-to-right sequence 5 * 3 + 12 mod 5 – 4 is applied, + and – have the lowest priority where left-to-right will be 15 + 12 mod 5 – 4 done. 15 + 2 - 4 17 - 4 13 d) ( 8 + 5 )* 3 parenthesis has a higher priority than * so + will be done first since it is inside the 13 * 3 parenthesis 39 20 String Expression: String expression is an expression consisting of string constant or string variable operands separated by a string operator which yield a string value. Format of String Expression operand operator operand operator operand… String Operator + concatenation Concatenation is a process or operation by which the value of the second operand (right operand) is appended or attached to the end of the first operand (left operand). (The + operator adds if operands are numeric type and will concatenate if operands are string type). Examples of string expression: Note: Please remember that any data items enclosed in a quotation mark are considered string or non-numeric. If they in numerical form they can’t be use in mathematical operations. a) “3” + “25” 25 is attached to 3 “325” b) “Hello” + “James” “James” is attached to “Hello” “HelloJames” Be aware that in any expressions with operands of different types causes an error, a mismatch error in particular. Example of incorrect expressions 13 + “25” first operand is numeric and the second is string “Dog” + 20 first operand is a string and the second is numeric Boolean Expression: 21 A Boolean expression is one that conforms to one of two given Boolean results, commonly characterized as true or false. These expressions and operators are a core part of computer science and programming languages. A Boolean expression is either a relational or logical expression, which yield either a TRUE or FALSE value. Types of Boolean Expression 1) Relational expression 2) Logical expression Relational expressions: Relational expression is a Boolean type of expression composed of numeric or string constant or expression operands, separated by a relational operator which yield either a TRUE or FALSE value. The General Format: operand operator operand… The relational operators are as follows: operators meaning == equal to > greater than < less than >= greater than or equal 25 mod 3 c) 5 == 4 d) 5 < > 30 e) 25 3 Q: Is 5 greater than 3? TRUE A: TRUE b) 20 == 21 Q: Is 20 equal to 21? FALSE A: FALSE There are few rules to be considered and followed in evaluating relational expressions. They are the following: 1) if operand is a variable, use the value assigned to it for comparison. 2) if the operand is either a string or numeric expression, evaluate first the said expressions to determine its final value that will be used for comparison. 3) in the case of >= and = 4 Q: Is 5 greater or equal to 4? Analysis: 5 may not be equal but it is greater than 4. TRUE A: TRUE 25 5*5 11 7 25 > 25 TRUE FALSE 24 2) 25 mod 20 = “Nom” B >= 25 TRUE TRUE Logical Expression: Logical expression is composed of one or more relational expressions separated by a logical operator which yield either TRUE or FALSE value. FORMAT: relational expression operator relational expression… The Logical Operators are: 1) NOT 2) AND 3) OR Only the NOT is allowed to be placed before the relational expression operand. AND and OR operators are always used in between relational expression. Parenthesis can be added to signify priorities. Examples of Logical Expressions 14 >= 5 AND X == 5 NOT 5 == 2 + 3 NOT ( “Hi” == “Hello” ) OR 25 mod 3 == 5 div 5 To evaluate logical expressions, relational expressions must be evaluated first whether the said relational expression is TRUE or FALSE. After evaluating 25 relational expression, logical operation is to be evaluated next using the Truth Table as the basis of the final answer. The truth table for each logical operators: NOT NOT TRUE = FALSE NOT FALSE = TRUE AND TRUE AND TRUE = TRUE TRUE AND FALSE = FALSE FALSE AND TRUE = FALSE FALSE AND FALSE = FALSE It only become TRUE if both the operands are true – the rest are false OR TRUE OR TRUE = TRUE TRUE OR FALSE = TRUE FALSE OR TRUE = TRUE FALSE OR FALSE = FALSE It only become FALSE if both the operands are false – the rest are true Examples of Logical Expression Evaluation: Assuming that: X=5 Y = 35 Name = “John” 1) 35 > 50 OR Name == “Johnny” Relational and arithmetic expressions are evaluated FALSE OR FALSE first before all logical operations. To get the final FALSE answer, follow the Truth Table 2) X+Y == Y+X AND 5 == 35 mod 15 40 == 40 AND 5 == 5 TRUE AND TRUE TRUE 26 Mixed Logical Expression: In the case of mixed operations in a logical expressions, order of precedence are considered. They are as follows: 1) Parenthesis highest precedence 2) NOT 3) AND 4) OR lowest precedence The left-to-right rule is applied to operations with equal priority. And for the nested parentheses, the inner parentheses are evaluated first prior to the outer parenthesis. Example: 5 mod 3 == 2 AND (25 >= 25 OR 5 < 7 ) Analysis: - Numeric and relational 2 == 2 AND ( TRUE OR TRUE ) expressions are evaluated first - Next is the OR operation inside the parenthesis 2 == 2 AND TRUE - Followed by the AND operator. Note: In the list of precedence OR is less in TRUE AND TRUE priority compared to AND however it is inside the parenthesis. Thus, it was evaluated first. TRUE More Examples: A=1 B = 10 C = 50 a) A == 1 OR A == 2 OR A == 3 TRUE OR FALSE OR FALSE TRUE OR FALSE TRUE 27 b) C div 5 == B AND B * 5 == C OR C div C == A 10 == B AND 50 == C OR 1 == A TRUE AND TRUE OR TRUE TRUE OR TRUE TRUE CONVERSION OF ALGEBRAIC EXPRESSION INTO A PROGRAM EXPRRESSION: In programming, mostly, if not all, algebraic expressions do not normally operate when used as it is in a program. Examples XY + 2 100 – 5 * 2 5 + 3 ) ( AB ) ABC 5 In any programming language, these examples will not be evaluated, instead they will be considered as invalid or incorrect. They need to be converted into a programming format in accordance to the syntax rule of a computer language being used. In programming, operands must be separated by an operator and only valid symbols must be used. In this manual, having used the pseudo – programming language, only the following symbols and elements must be included in an expression. They are: ( ) parenthesis *, /, mod, div, +, -, ^ operators constants (string or numeric) operands variable (string or numeric) operands 28 Conversion Example: Algebraic Program Expression 1. XY + 2 ( X * Y + 2 ) / ( A * B * C) ABC 2. 100– 5 * 2 ( 100 – 5 * 2 ) / 5 5 3. ( 5 + 3 ) ( AB ) (5+3)* (A*B) 4. 3+6 (3 + 6 ) / (( 6 – 2 ) * ( 8 + 5 )) (6–2)(8+5) 5. A + _X_ A/(X+B)+X/(1/2) X+B 1 2 On the converted program expression, parentheses are added to prioritize a certain sequence of operation in the expression. FORMULATION of NUMERIC EXPRESSIONS: It would be easier to construct numeric expression when there is a given algebraic expression or formula. The matter of conversion into a program form should be considered. However, there are cases that programmer’s ability to construct numeric expression is solicited. It is considered one of his primary jobs. More often, numeric expression can be constructed based from what a problem statement conveys. Examples of constructing numeric expression based from a statement. Statement1: Perimeter of an isosceles triangle is equals two times the length of one of the equal sides plus the length of the base. Note: Keywords to use in the expression are underlined 29 Constructed numeric expression: P=2*S+B P – perimeter S – sides B – base Statement 2: The surface area of a circle equals PI multiplied by the square of the radius. Constructed numeric expression: AREA = 3.1416 * R ^ 2 R – radius or AREA = 3.1416 * ( R*R ) Statement 3. The circumference of a circle is equals pi times the diameter. Constructed numeric expression: Circumference = 3.1416 * diameter Multi-lined expression: Multi-lined expression can also be applied for the benefits of simplicity and accuracy. Multi-lined expression is also good for an itemized reporting as the program warrants. (Multi-lined expression is an expression which obtains its final answer through a series of sub expressions as the origin of the final output.) Example Statement: Gross Pay in the sum of all incomes acquired by an employee as follows: Basic Pay, Allowance and Overtime pay. However, some deductions are taken from their Gross Pay such as: SSS which is 2 percent of the Gross Pay, Withholding tax which is 4 percent of the Gross Pay and PhilHealth amounting to 75 pesos. 30 Net Pay is the only amount given to the employee for take home. Net Pay is the amount left after deducting all the deductions. Multi-lined expression: Gross_Pay = Basic_ Pay + Allowance + Overtime SSS = Gross_Pay * 0.02 WTax = Gross_Pay * 0.04 PhilHealth = 75 Total_Deduction = SSS + WTax + Phil health Net_Pay = Gross_Pay – Total_Deduction Take a note that by constructing multi-lined expressions, the basis of computation or the value needed by the lower lines should have been evaluated prior to its use. In the case of our example, Gross pay was the basis of computation of SSS, WTax and Net Pay as in the case of SSS, WTax and PhilHealth was the basis of the Total_deduction, as well as Net_Pay using Gross Pay and Total_deduction as its basis. FORMULATION of Boolean expression: Like numeric expression, it is a good idea that constructing Boolean expression is an important skill to be considered. Programmers should know how to deal with this. Boolean expression can be constructed based from a given statements or problem, however, they should be constructed in such a way that it will conform to whatever language is being used. Keywords from a given statement must be noted so that idea being expressed must be conveyed in the expression being constructed. Aside, constructing Boolean expression must follow the rule mentioned in the previous topic. Example: Statement 1 Applicant’s age is at most 30 years old. Expression AGE 120 AND X < > 140 AND X < > 160 ) Or ( X > 100 AND X < 200 ) AND NOT ( X == 120 OR X == 140 OR X == 160) Statement 6 Sum of A and B is at most 100 Expression A + B

Use Quizgecko on...
Browser
Browser