580 likes | 696 Views
Information Science 1 Review. College of Information Science and Engineering Ritsumeikan University. Week 15. Instruction Fetch. Instruction Decode. Operand Fetch. Execute. Result Store. Next Instruction. CPU: How it works.
E N D
InformationScience 1Review College of Information Science and EngineeringRitsumeikan University Week 15
Instruction Fetch Instruction Decode Operand Fetch Execute Result Store Next Instruction CPU: How it works CPU reads program instructions from RAM and executes one instruction at a time until completion, according to the Machine Cycle algorithm: Obtain an instruction from RAM Determine required actions and instruction size Locate and obtain instruction data Compute result Store result in memory for later use Determine the next instruction
CPU registers and operation Memory Address Register (MAR):holds main memory addresseswhen fetching instructionsor data
Computer structure: I/O • Input and Output devices (I/O) allow humans to interact with computers • I/O gives computers long-term memory • I/O lets computers control and communicate with other systems • Examples: I/O Device BehaviorPartner Keyboard I Human Mouse I Human Sound card I and O Human HDD I and O Computer Printer O Human CD, DVD drive I and O Computer Network card I and O Computer Display usually O Human
Decimal system • Decimal numbers have radix = 10 (in Latin, “decima” means “a tenth part”) • Symbols used:0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 • Position weights:… 103 102 101 100 . 10-1 10-2 10-3 …1000 100 10 1 1/10 1/100 1/1000 • For example, the decimal number 36.250:36.250 = 3*10 + 6*1+ 2*1/10 + 5* 1/100 +0* 1/1000
Binary system • Binary numbers have radix = 2 (in Latin, “bini” means “two together”) • Symbols used:0 and 1 • The radix (10) is denoted by a subscript (2 • Position weights:… 23 22 21 20 . 2-1 2-2 2-3 …8 4 2 1 1/2 1/4 1/8 • For example, the binary equivalent of 36.250:36.250 = 1*32 + 1*4 + 1/4 = 100100.01(2
Octal system • Octal numbers have radix = 8 (in Latin, “octo” means eight) • Symbols used:0, 1, 2, 3, 4, 5, 6, and 7 • Convenient when bits are grouped in triplets • Position weights:… 83 82 81 80 . 8-1 8-2 2-3 …512 64 8 1 1/8 1/64 1/512 • For example, the octal equivalent of 36.250:36.250 = 4*8 + 4*1 + 2*1/8 = 44.2(8
Hexadecimal system • Hexadecimal numbers have radix = 16 (in Greek, “hexa” means six) • Symbols used:0, …, 9, A, B, C, D, E, and F • Convenient to represent nibbles (hextets) • Position weights:… 163 162 161 160 . 16-1 16-2 16-3 …4096 256 16 1 1/16 1/256 1/4096 • For example, the hexadecimal equivalent of 36.250: 36.250 = 2*16 + 4*1 + 4*1/16 = 24.4(16
Example: Decimal to binary 22.8125 = ?(2 22.8125 = 10110(2. 11 R 0 5 R 1 2 R 1 1 R 0 0 R 1 22.8125 = .1101(2 1.625 I 1 1.25 I 1 0.5 I 0 1.0 I 1 0 I 0 22.8125 = 10110.1101(2
The remaining conversions • To convert between binary, octal, and hexadecimal, memorize and use the conversion table: • Octal is 3 bits for each digit • Hexadecimal is 4 bits for each digit • Use binary as the intermediate to convert between octal and hexadecimal 0110100110.1(2 = ?(8 = ?(16 000 110 100 110.100 0001 1010 0110.1000 6 4 6 .4 1 A 6 .8 0110100110.1(2 = 646.4(8 = 1A6.8(16
Binary addition 1 1 1 0 0 0 0 0 0 Carries: 00 Augend: 01100 10110 Addend:+10001+10111 Sum: Note: 5-bit numbers are assumed. The underlined bit is a carry-in to the least significant digit 1 1 1 0 1 1 0 1 1 0 1
Binary subtraction 0 0 0 1 0 0 0 0 Borrows: 02 Minuend: 11101 11110 Subtrahend:-10001-10011 Difference: Note: 5-bit numbers are assumed. The underlined bit is a borrow-in to the least significant digit. If the Subtrahend is larger than the Minuend, interchange and append a “minus” to the result 0 1 1 0 0 0 1 0 1 1
Multiplicand 1011 Multiplier 101 Partial Products 1011 0000 · 1011 · · Product 110111 Binary multiplication The binary multiplication table is simple:00 = 0, 10 = 0, 01 = 0, and 11 = 1
0010.1 100 1010.0 0011 11 1001 100 100 011 100 0011 0 11 0 Binary division The same as for decimal numbers – long division: Quotient Dividend Divider
BCD code • Binary Coded Decimal, BCD:A code used to represent each decimal digit of a number by a 4-bit binary value • Valid one-nibble representations for 0-9 are 0000 to 1001; the binary codes 1010 to 1111 are invalid (not used in BCD) • Also called an 8421 Code due to the decimal weight of each bit position • Example: 5689 = 0101 0110 1000 1001(BCD • Advantages: Allows for easy conversion to decimal for display and faster decimal calculations • Disadvantages: Is inefficient and requires relatively complex hardware
Gray code • The Gray code (also called “reflected binary code”): A binary numeral system where two successive values differ in only one bit • It is unweighted and is not an arithmetic code 4-bit Gray code Decimal Binary Gray code | Decimal Binary Gray code 0 0000 0000 | 8 1000 1100 1 0001 0001 | 9 1001 1101 2 0010 0011 | 10 1010 1111 3 0011 0010 | 11 1011 1110 4 0100 0110 | 12 1100 1010 5 0101 0111 | 13 1101 1011 6 0110 0101 | 14 1110 1001 7 0111 0100 | 15 1111 1000 • Gray code is used to facilitate error correction in digital communications
Integers: Signed magnitude representation • A= an-1an-2 …a0is anndigit number, wherean-1is the sign, and the remainingn-1bits are the magnitude • Ais • positive ifan-1 (which is msb) is 0 • negative ifan-1is 1 (or radix-1 for radix > 2) • Range is from-(2n-1 - 1) to (2n-1 - 1) • There are two zero representations:00…0(2 = +0 and 10…0(2 = -0
Machine word 110010.. …00101110010101 Sign bit Remaining bits for magnitude Problems with signed magnitude representation • Signed magnitude (or sign-magnitude) representation is easy for people to understand, but it is inefficient and requires complicated computer hardware. (Think: Why? Hints: Arithmetic, negative numbers, machine word size)
Machine word Sign bit 110010.. …00101110010101 How integers are actually stored: Two’s complement • When an integer is negative, it is stored in 2’s complement • Step 1. Find 1’s complement of the number by inverting all the bits: Binary: 11000110 1’s complement: 00111001 • Step 2. Add 1 to the 1’s complement: 00111001+ 00000001 = 00111010
2’s complement overflowdetection • Detection rules. Overflow occurs if: • Overflow occurs if 1) there is a carry in to the sign bit, but no carry out of it, or2) there is a carry out of the sign bit, but no carry in to it
Assumed order Requirements Analysis System design Program design Coding Unit Testing & Integration System Testing Software processes Acceptance Testing Operation & Maintenance The Waterfall model
The concept of algorithm • Definition:An algorithm is a finite set of unambiguous, executable instructions that direct a terminating activity • In an algorithm, always • the number of steps (instructions) is finite • we are able to do each of the instructions • when we have followed all of the steps, we obtain a solution, and then stop
Logic comparison operation.Always has one entry and two exit points Beginning or end of a task Input/output operation Direction of logic flow Data manipulation operations e.g arithmetic Logic flowconnectors Algorithm design tools: Flowchart • Flowchart is a logic diagram to describe each step that the program must perform to arrive at the solution • It is a very popular design tool used for showing an algorithm in a graphical form.Most common flowchart symbols are:
i = i + 1 Display i2 Start NO is i > 7 ? i = 2 YES Stop Flowchart: Example • Suppose you want to calculate the squares of the integers from 2 to 7 • a simple solution would be to arrange a loop for both calculation and display
Algorithm design tools: Pseudocode • Pseudocode is a textual description of a program • Basic pseudocode operations: • Read the input from user • Print/Display the output to the user • Carry out basic arithmetical computations • Conditional operations: Execute an operation if the condition is true • Repeat operations: Execute a block operation multiple times until a certain condition is met • Pseudocode is a simplified form of English (or any other natural language – Japanese, Vietnamese, Arabic, etc), but looks like programming
Basic data types • There are only four basic (fundamental) datatypes built into almost all high-level programming languages(Note that “String” is not a basic data type)
This creates a variable called a, sets aside memory for it, and writes 5in that memory location int a = 5; 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 MEMORY This creates a variable called myVar, sets aside memory for it but does not put a value in it. So, the content of myVar remains undefined (i.e. random) int myVar; • Variables are names that refer to memory locations where information can be stored • The value of a variable can be changed • All variables must be declared (given a name and assigned a type) before use Variables
It is conventional to capitalise constant names This would give an error! Named constants • Constants are declared like normal variables but have a keyword (“final”, “const”,…) in front to indicate that the value cannot change final double PI = 3.141592654; const float PI = 3.141592654; ... ... ... PI = 62.3;
The concept of identifier • An identifier is a descriptive name assigned to a variable or named constant used in a program • Identifiers must start with a letter and, in most cases, can only contain: • letters, A-Z, a-z • digits, 0-9 • the underscore _ • Identifiers must not be confused with reserved words of the programming language
Literals • A literal is an explicit value in a program. For example, instead of using the constant PI, use the numeric value of 3.141593 • The use of literals in programming is discouraged. Literals mask the meaning of statements in which they appear, and make understanding and modification of the code more difficult
Operator precedence Example: x = a / b * (c + (d - e)) 5 3 4 2 1
+ / – Expression trees • Sometimes, the evaluation of an expression is convenient to show using an expression tree • The operators lower in the tree have higher precedence for that expression a + (b – c) / d a d b c
Mixed-type arithmetic • In most programming languages, when performing calculations with operands of different data types (onright side): • Lower-precision operands are promoted to higher-precision data types, then the calculation is performed • Promotion is effective only for expression evaluation and does not cause a permanent change to the data • This is called "implicit type casting" • Any expression involving a floating-point operand will have a floating-point result (onright side)
Rules of promotion Applies the first of these rules that fits: • If either operand is a double, the other operand is converted to a double • If either operand is a float, the other operand is converted to a float • If either operand is along, the other operand is converted to a long • If either operand is an int, the other operand is promoted to anint • If neither operand is a double, float, long, or an int, both operands are promoted to int
Relational operators • Boolean expressions compute Boolean-type results and make use of therelational operators: “<“less than “<=“less than or equal to “>”greater than “>=“greater than or equal to “==“equal to “!=“not equal to
Logical operators The negation (logical NOT) is denoted by symbol “!” or “^”. It is defined by!FALSE==TRUE and !TRUE==FALSE The Boolean sum (disjunction, logical OR) is denoted by symbol “||” and is defined byTRUE||TRUE == TRUE, FALSE||FALSE == FALSE, TRUE||FALSE == TRUE, FALSE||TRUE == TRUE The Boolean product (conjunction, logical AND) is denoted by symbol “&&” and is defined byTRUE&&TRUE == TRUE, FALSE&&FALSE == FALSE, TRUE&&FALSE == FALSE, FALSE&&TRUE == FALSE • Besides relational operators, Boolean expressions also make use of the logical operators:
Algebraic expressions: Operator precedence ( ) evaluated 1st !, NOT, ^ 2nd (pre) ++, -- 3rd * , / , % 4th +, - 5th <, >, <=, >= 6th ==, != 7th &&, AND 8th ||, OR 9th = evaluated last
A B C P B 0 0 0 0 C 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 0 A P 1 0 1 0 Alarm system Buzzzzz!!! 1 1 0 1 1 1 1 0 Truth table: Truth tables • A truth table can be used to show the relationships between the input and the output of an algorithm • consider an alarm which sounds when: • The lights are on and • The door is open and • The key is not in the ignition P = A && B && !C
x y z F(x, y, z) 0 0 0 1 0 0 1 1 0 1 0 0 0 1 1 0 1 0 0 1 1 0 1 0 1 1 0 0 1 1 1 0 Truth tables: Another example • Problem:For the given truth table, construct the corresponding boolean expression • Solution:SinceF(x, y, z) = 1if and onlyif (x == y == z == 0)or(x == y == 0, z == 1)or(x == 1, y == z == 0),F(x, y, z) = !x && !y && !z || !x &&!y && z || x && !y && !z
De Morgan's Laws • Expressions with logical operators “&&,” “||,” and “!” obey De Morgan's laws: ! (p && q) == ( !p || !q ) and ! (p || q) == ( !p && !q ) • Example • if ( ! ( x => -10 && x <= 10 ) ) Now, let’s make it simpler / easier to read: • if ( x < -10 || x > 10 )
if…elsesyntax • The condition is interpreted as a boolean expression (i.e. is evaluated to True or False), and it must be enclosed in parentheses • No semicolon is required after the condition parenthesis, but clauseIF and clauseELSE may required them • The condition can have a side effect (i.e. change a variable’s value) • clauseIF and clauseELSE can be any expression, even another if…elsestatement • clauseIF and clauseELSE can each only be one statement, but it may be a compound statement or block • elseis optional
Multiple choice • if…else provides the most general way to make choices in a program. Another way is using the switch statement that is a very special form of nested if…else • switch is used when a discrete variable of type ‘char’ or ‘int’ (or other integer-compatible type) specifies what should be done, and it has the following format: switch (selector){ case CONSTANT_1: statements_1; case CONSTANT_2: statements_2; break; … case CONSTANT_n: statements_n; default: statements_D; }
Loop classification • In general, loops can be classified in one of two categories: • Counter-Controlled Loops • are used when we need to perform an action a particular number of time • consists of initializing, testing, and updating a counter • the number of iterations may or may not be constant • Event (or sentinel) -Controlled Loops • are used when actions should be performed until a particular event occurs or a particular state is reached
The while statement while ( condition ) statement; • A while statement has the following format: • If the condition is true, the statement is executed • The statement will, thus, be executed 0 or more times • Then the condition is evaluated again, and if it is still true, the statement is executed again • The statement is executed repeatedly until the condition becomes false • It is the most basic repetition structure
Thedo/whilestatement do statement; while( condition ) • A do/while statement has the following format: • The statement is executed once initially, and then the condition is evaluated • The statement will, thus, be executed at least 1 time • The statement is executed repeatedly until the condition becomes false (i.e. remains true)
Theforstatement for (initialization; condition; increment) statement; • A for statement has the following format: • Each expression in the header of a for loop is optional: • If the initialization is missed, no initialization is performed • If the condition is missed, it is always considered to be true, and therefore creates an infinite loop • If the increment is missed, no increment operation is performed (which may cause an infinite loop) • You can even miss them all: for ( ; ; )statement;
Event-controlled loops Initialize total to zeroInitialize counter to zero Input the first grade (possibly the sentinel)While the user has not as yet entered the sentinel { Add this gradeinto the running total Add one to the grade counter Input the next grade (possibly the sentinel)}If the counter is not equal to zero Set the average to the total divided by thecounter Print the averageelse Print “No grades were entered” • An example (a class-averaging algorithm in pseudocode) with sentinel-controlled repetition:
Side effects may occur while the function is executing, but before the function returns Examples of side effects: • changing an input variable • printing output to the screen • changing a global variable Function concept • A function is a mini program that performs one well-defined task. A function always has: • a set of inputs • one output • a body of statements