19
1 1 F.C Ledesma Avenue, San Carlos City, Negros Occidental Tel. #: (034) 312-6189/(034) 729-4327 CHAPTER 1 INTRODUCTION, BASIC SYMBOLS AND VARIABLES

Logic Formulation

Embed Size (px)

Citation preview

1

1F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

CHAPTER 1

INTRODUCTION,BASIC SYMBOLSAND VARIABLES

2

2F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

Lesson 1:

Computer System Components

In computer system, one cannot have an understanding of its operation without thecareful analysis of its components. As a starter, it is important to first lean the basics andrelationship of these components.

When we are given an objective to compute large numbers, the first instinct thatcomes to our mind is use a calculator. When we have the calculator, there are things that wethink and do unconsciously. The first response upon knowing the objective is automatic, weimmediately analyze the objective is automatic, we immediately analyze the objective byidentifying the mathematical operations needed (addition, subtraction, multiplication,division, exponentiation, etc.) then, we input the data to be computed by pressing thenumbers and the identified mathematical operations, we then press the equal sign key toprocess the inputted numbers. The result is then shown on the display of the calculator; thisresult whether correct or erroneous is what we call output.

The relationship of the input, process, and output components producing the resultdoesn’t stop there. The output we see on our calculator provides two things, first is theincorrect result, and second is the correct result. We get incorrect result when weaccidentally input wrong data by pressing either negative values or error results. When weget correct result from our calculation, chances are another instinct comes in our mind; weeither use the result again as an input for another computation, or store the computed resultin the memory for future computations. These output whether correct or incorrect, andwhether used as input for another computation is the feedback component of the computersystem.

The relationship of the components is shown below:

INPUT OUTPUT PROCESS

3

3F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

The Blue Print

The relationship of the components is the blue print of a computer system. Blue printis the logic and ideas transformed into a map of how computer should do things. It isimplemented through software (instructions that tells the computer what to do) and executedthrough the interaction of different hardware devices (physical computer itself). Blue printalso serves as the basis of how a computer functions, and how data are processed inside thecomputer.

Let us have a step backward, recall that in a computer system, we key in using akeyboard or mouse data for processing—data in computer system refers to numbers,alphabets and alphanumeric characters. The entered data is then processed by the CentralProcessing Unit (C.P.U.). The C.P.U. inside the computer box is just a tiny square piece ofIntegrated Circuit attached on the mother board that normally has a dimension of 1” x 1”,though small in size, its functions in the computer system is enormous because it functionsas the brain of the computer.

Central Processing Unit Components

The computer brain (C.P.U.) has different components that work cooperatively toexecute instructions. These components are:

Control Unit (C.U.) – The command center of the processor. It has three primaryfunctions: read and interpret instructions, direct flow of operations of computer andhardware devices and, control the flow of instructions and data.Register – A temporary storage microchip that holds data during processing. It islocated inside the CPU and has the same function that of a memory, specifically thetype Random Access Memory (R.A.M.) because of its volatile character – data are lostonce electric current is turned off; it just holds data temporarily for processing.Arithmetic and Logic Unit (A.L.U.) – the most significant component inside the C.P.U.for our learning of the “behind the scene”. It is the chief of operations of thecomputer. A.L.U. performs two major operations in processing data: all mathematicalcomputations (addition, subtraction, multiplication, and division) and all logicaloperations (comparisons of data such as; greater than, less than, equal, greater thanor equal to, and less than or equal to). These processing are the main concentrationof how a computer process data, and is the foundation of the “behind the scene”.

Behind the scene in action

As we have read the blue print of behind the scene, it is now clear why a computer isdefined as an electronic device that can accept, process, and store vast amount of data toproduce useful information. Let us now zero in on behind the scene and understand itslanguage of ABC. Computer programmers write computer instructions in computer programminglanguage. Just as people speak their native dialect, programmers write programs in differentlanguages; some examples are C++, Visual Basic, Java and COBOL. No matter whichprogramming language a Computer programmer uses, the language has rules governing its

4

4F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

terminology and punctuation. These rules are called the language’s syntax. This syntax is arule that governs a programming language is unique and have their specific set of syntax. When ideas are converted into a computer program, it is sent to the CPU processing.However, The CPU cannot understand the code (computer program) and will not do anythingbecause of language incompatibility. For the CPU to understand the code, a languagetranslator is needed. The language translator software is called compiler or interpreter. Therole of compiler is to transform the code into a machine language (series of 1’s and 0’s torepresent ON and OFF states of the computer devices. It is also the representation of thedigital electronic charges inside the computer). Once the code is compiled, it changes its formfrom computer program with strict syntax to a readable machine language that can beinterpreted by the CPU. CPU then executes the instructions and performs the tasks.

Lifeblood of a Computer System

Tasks executed by the CPU vary from simple acceptance of data to a complexmerging of different files. Whatever tasks the CPU is instructed to perform, the instructionwould have to be in the language of computers. Computer program is the lifeblood of acomputer system it is the fluid that runs through the veins of the computer that tells what theorgans to function and what action to perform. With the analogy, we can define computerprogram or code as a set of logical instructions given to a computer for data processing thatis interpreted by a compiler to produce useful information. Programmers integrate ideas to a code in no simple way. In their practice ofdeveloping computer programs, it brings to them the hurdles to accomplish the task. Beingnew to programming, we might not be ready yet to overcome the challenges. As a guide,programmers suggest to observe the following guide questions in planning and developing aprogram:

1. What is the problem?2. What are the available data?3. What output information or data is needed?4. When do you need the output?5. What processing is needed to produce the output?6. What is the desired output?7. Where should the output go?

We can now agree that code is the gasoline that powers the computer. It is now therole of behind the scene to translate ideas into a form that is friendlier and easier tounderstand and illustrate. Behind the scene can be illustrated by the use of flowchart. Flowchart is a modeling tool used to illustrate data, instructions, process,information, and workflow by the use of specialized symbols. In the world ofcomputers we can simply say that flow chart is a step-by-step graphicalrepresentation of a solution. The basic symbols used in programming are presentedin Table 1.

Table 1. Basic Flowchart SymbolsSYMBOL NAME DESCRIPTION

5

5F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

TERMINALDefines the starting and

ending point of a flowchart

INITIALIZATIONThe preparation or

initialization of memory spacefor data processing

INPUT/OUTPUTThe inputting of data for

processing

PROCESSManipulation of data(assignments and

mathematical computations)

FLOW LINES

Defines the logical sequenceof the program. It points to

the next symbol to beperformed.

ON-PAGE CONNECTORConnects to the flowchart toavoid spaghetti connection

on the same page.

OFF-PAGE CONNECTORConnects the flow chart on

different page to avoidspaghetti connection

No yes

DECISIONProcess conditions using

relational operators. Used fortrapping and filtering data.

Variables

The next most important thing to know is how data are represented in the program.Recall that data are entered into the program using a keyboard or mouse, and the dataentered for processing are saved on a certain location. This location is called variable.Variable is a primary storage location that can assume different numeric or alphanumeric

1

A

6

6F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

values. It is also a memory space allocated by a computer user for processing and storingdata. Variables like humans need names to be identified. Microsoft suggests a variablenaming convention called Hungarian Notation. Hungarian Notation specifies a variable withboth the data type and its description. The first three characters in this notation specify thedata type and the remaining characters are the description of the variable.

Date type is the type of the data being processed in the program. However, data typeis language specific and may have different representations. Table 2 shows the basic datatypes with their descriptions.

Table 2. Basic Data TypesDATA TYPE DESCRIPTION EXAMPLE

*Integer Whole number10 355 1590

54765 1 34000

**Float or doubleInteger with Decimal

numbers3.1416 0.12 1.0112.12 99.99 0.04

*characterAlphabets and special

charactersJ W A* & ?

*string Combination of charactersSum age int_1

a total grand total

*BooleanReply of the Compiler in theprogram that is performed

behind the scene.

Values are either 1 for YES or0 for NO

*used mostly by all programming languages**C/C++, Java, Visual Basic and other programming language specific*** Note that the data types above are not the only data types used in programming. Otherprogramming language may have their own set of data types with specific descriptions thatare not presented above.

Table 3. Sample variable names using Hungarian NotationVARIABLE NAME DATA TYPE DESCRIPTION

Intsum Integer Sum.DblTax Double TaxFltRate Float RateChrReply Character ReplyStrLname String LnameBooAns Boolean Ans

Data type is important in programming. However, data type is unique to everyprogramming language. In the study of programming logic, data types will not be integratedin the discussion to allow pure analysis and logic development among students.

The standard naming convention for variables used without any biases to anyprogramming language are presented through its characteristics:

Variables name characteristics

7

7F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

Must be descriptive and significant to the data, problem and its solution. It should bedescriptive enough to identify the process or data it is referring to.Combinations of alphanumeric characters (alphabet, numbers and special characters)can be used as a variable name provided that it starts with an alphabet.Although the length of variable name can have 256 characters, the lesser the numberof characters the more efficient the program is.

Examples:Class_size tuition intl incomesum char3 f_name answernet_income l_name total grand_total

Computer Operators: Processing Data

The languages of computers need to be converted to a language that the CPU canunderstand. For the programmer to instruct computers to process mathematicalcomputations and logical operations, they would have to define symbols that the computerscan understand. The symbols presented are the generic symbols used by computers forprocessing. However, as you progress to the different programming languages themathematical and relational symbols may vary.

ARITHMETIC OPERATORS

OPERATION SYMBOL EXAMPLE EXPLANATION

Multiplication * A * BMultiply the value of

variable A to thevalue of variable B

Division / X/YDivide the value ofvariable X by the

value of variable Y,

Addition + Intl +_ int2Add the value of

variable intl to thevalue of variable int2

Subtraction - A – BSubtract the value ofvariable B from thevalue of variable A.

Exponentiation ^ C^2Square the value of

variable C

Examples:

MATHEMATICAL EXPRESSION COMPUTER EXPRESSION

1. 3xy 3*x*y2. x2 + y2 (x*x) +(y*y) or x^2 + y^23. 3x (3*X) / (y*y*y) or Y3 (3*x) / (y^3)4. . a2 + b2 . [(a*a) + (b*b)] / (c*d)

Cd or (a^2 + b^2) / (c*d)

8

8F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

In the examples, it is important to note that the arithmetic hierarchy of computationstill applies in computers. The addition of exponentiation and parenthesis is now included inthe hierarchy giving the “MDAS” added acronyms, PEMDAS (Parenthesis, Exponentiation,Multiplication, Division, Addition and Subtraction)

ARITHMETIC OPERATORS

OPERATION SYMBOL EXAMPLE EXPLANATION

Greater than > A>BThe value of variableA is greater than thevalue of variable B.

Less than < X<YThe value of variable

X is less than thevalue of variable Y.

Equal to = = Int1 = = int2The value of variableint1 is equal to the

value of variable int2

Not equal to <> Net <> gross

The value of variablenet is not equal to

the value of variablegross

Greater than or equalto

>= Pay1>=pay2

The value of variablepay1 is greater thanor equal to the value

of variable pay2

Less than or equal to <= Age1 <=age2

The value of thevariable age1 is lessthan or equal to the

value of variableage2

TYPES OF VARIABLES

The role of variables in programming is very crucial. In the processing stage of aprogram, the variables hold the data and information (whether it will be stored in thememory or used for computation or printing processed data). The challenging part in thisstage is identifying who gets the processed data? This can be clarified by the descriptions ofthe types of variables below:

Destructive Variable – variables that destroy or change its value after processing.This type of variable is normally the temporary storage of data during processing.Constructive Variable – variables that maintains its value after being used in theprocess.

Let’s illustrate:

Suppose that we have variables A and B and the values of A and B are 5 and 10 respectively.What will happen if we have an instruction of A and B after performing the instruction? Whogets what data? This is the confusing part . . . to further illustrate:

9

9F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

=

A B

During the process this is what’s happening to the variables:

=

A B

After processing the instruction this is what happened to the value of the variables.

=

A B

As illustrated, Variable A has now the same value with variable B, 10, and theoriginal data of variable A, 5 was destroyed. This is what we mean by destructive andconstructive variable. As a rule, the manner of transferring data from one variable to anotheris always from right to left. Do not confuse your self from your algebra. Let it sink to you fromnow on that this is how you will transfer data from one variable to another.

These are the originalvalues of the variablesbefore processing

15

Variable A gets thevalue of variable B

15

Take note of the valueof variable A and thevalue of variable Bafter processing

15

10

10F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

CHAPTER 2

Working with ProcessSymbol

11

11F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

Flowcharting is as easy as typing ABC or counting 123, the challenging part indrawing flowchart is the analysis. Let us start harnessing our logic and look at the analyses ofthe problems in drawing flowcharts.

Basic things to remember in flowcharting:

To be familiar in drawing flowcharts, the learning exercises below will guide usin understanding the foundations needed in logic formulation needed in logic formulation,and for us to be ready to face challenging problems as we progress.

Learning exercises:

1. Create a flowchart that will store the value of A and B, where A= 5.2. Create a flowchart that will assigned stored value of C to both A and B where A = 15,

B = 10 and C = 203. Create a flow chart that will move the value of A and B and B to C. The values of the

variables are: A = 25, B = 30 and C = 35.

A flowchart always starts with the instructionSTART or BEGIN… the only guideline toremember in the terminal symbol is theconsistency of terminologies. The organizedway of writing the instruction is to use the

START

Initialization symbol is where you prepare thevariables to be available for use. When youinitialize, you are also allocating memory spacefor your data storage. As a rule we always

The processing symbol is only limited to;assignment of new value to the variables andmathematical computations.

Since we use START in the opening of ourflowchart, for consistency

STOP

12

12F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

4. Create a flowchart that will arrange the values of A, B and C in ascending order whereVariable A will gets the lowest value and variable C gets the highest value. The valuesof the variables are: A = 15, B = 10 and C = 20.

5. Create a flowchart that will arrange the values of A,B,C and D in highest to theLowest order where variable A gets the highest value and variable D gets the lowestvalue. The values of the variables are: A = 3, B = 9, C = 12 and D = 6

Solution No. 1

Problem:Create a flowchart that will store the value of A to B, where A = 5.

Analysis:

If we are to solve the problem, it is clearly stated that our objective is to storethe value of variable A to variable B. We are not interested if variable B has a value becauseall we need to do is store the value of variable A to variable B. We know that variable B is thedestructive variable and it will destroy its original value and get the value of variable.

Flowchart:

The uses of initialization in this flowchart are three things:1) Allocate two memory locations for variables A and

B;2) Assign number 5 to variable A; and3) Assure that variable B has no value.

The expression B=A is an assignment operation. Thevalue of variable B, Destroying the original value, 0 ofvariable B. After the assignment process, the newvalue of Variable B is 5.

STOP

B = A

A = 5 B = 0

START

13

13F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

Solution No. 2

Problem:Create a flowchart that will assign stored value of C to both A and B where A = 15, B = 10and C = 20

Analysis: The objective in this problem is to store the value of variable C to variables A and B.Regardless of the data stored on both variables A and B, we have to assign the value ofvariable C. This would mean that the original data of variables A, 15 and B, 10 will bedestroyed.

Flowchart:

The processing of data in the processsymbol is suggested to be as detailedAnd exact as possible. In the solutionshown, we can see that theassignment of the data from variable Cto variables A and B are doneseparately. This is to ensure that theprocesses are clear and done instep-by-step manner. If theprogrammers place all theassignments in one process symbol,the process will look like this:

Or

B = C

A = C

A = 15B = 10C = 20

START

A = C = B

14

14F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

Clearly we can see the confusion that we cannot identify who gets the data and who retains the original data. More so, in

separating instructions with asemi-colon, it sends a meaning thattwo assignments are performed in asingle process symbol and should notbe practiced.

Solution No. 3

Problem:Create a flowchart that will move the value of A to B and B to C. The values of the variableare: A = 25, B = 30 and C = 35.

Analysis:The greatest challenge in this learning exercise is not moving the values of A to B and B to C,but on how to preserve the value of B before it will be stored to C. If we move the data of Ato B immediately we destroy the data of B, and the data on B can no longer be stored to Cbecause it was already lost. The best way is to use the swap technique. Let’s illustrate:

Given variables and their values:

A B COutput Requirement:

A B C

Moving the data of A to B destroys the value of B25

STOP

A = C; B = C

3530

30

35

15

15F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

A B C

Moving the destroyed data of B to C now gives a wrong solution.25

Implementing Swap Technique would need a new variable say Temp to temporarily hold thedata of B so that during the process the data is preserved. Since we know that we have tosave first the data of B before it accepts the data from A, let us move the data of B to Temp.

Temp A B C

We can now destroy the data on B since it is now saved on a temporary variable.25

Temp A B C

The first objective of moving the data of A of B was accomplished and we can now save thedata from Temp to C to accomplish the problem.

30

Temp A B C

The output after the using the swapping technique is:

0

16

16F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

Temp A B C

Flowchart:

The swapping technique is very clear in thisflowchart. You can see the pattern of theswapping of data from variable of variable.

In the first process, the data on B was firstsaved to Temp .

Since the data was saved,we can now destroy the data on B.

In the second process, B gets the value of A,Destroying the data of B. We don’t have toworry if in this process the data B will bedestroyed because the original data wasalready save to Temp.

In the last process, the preserved data onTemp is now save to A destroying theoriginal data. Moving the data to A fromTemp completes the swapping process andthe requirements of the problem.

Solution no.5

Problem:

START

A=20B=25C=30

Temp = B

B = A

A = Temp

STOP

17

17F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

Create a flowchart that will arrange the values of A,B.C and D in a Highest toLowest order where variable A gets the highest value and variable D gets the lowestvalue. The values of the variable are: A = 3, B= 9,C=12 and D=6.

Analysis:The problem in this learning exercise is to arrange the data in Highest to Lowestorder. It also has a clear direction on where to save the arranged values, variable Ashould get the highest value (12) and variable D should get the lowest value (3).We know from the given values that the highest value stored in variable C shouldbe placed in variable A, and logically we connot immediately move the data from Cto A because we might destroy the data n A. Swapping the contents would needadditional variable to temporary hold the data that we want to swap and to preservethe data. Variable temp will initialize to function as temporary holder of the data toanother. The solution using the swapping technique is illustrated as follows:

Given variables and their values: The presence of variable Temp is for the preservation of data that will be used tosave the data on variable A for A to accept Highest number.

3 9 12 6

12 9 6 3

A B C D

A B C D

Output Requirement

9 6 0123

18

18F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

Since the data of Variable A is now saved, we can now destroy the data of A andmove the Highest.

The value of variable C, 12, the highest value is now stored on variable A, Logically,both C and A have the same values now and we can now destroy the value ofvariable C. Since variable B has the second highest value, variable B will not be partof the process of swapping. Let us now move the data on variable D to variable C.

B C D temp

To complete the solution, the data kept on the temporary variable should be placedto variable D.

A B C D tempThe final data of the variables after the final swapping process is:

tempDCBA

A

331293

tempDCB

129 6 312

A

12 9 6 16 3

9 6 3 312

19

19F.C Ledesma Avenue, San Carlos City, Negros Occidental

Tel. #: (034) 312-6189/(034) 729-4327

A B C D temp