Upload
others
View
11
Download
0
Embed Size (px)
Citation preview
Introduction to Programming2019/20 I. semester
Nagy Dávid
Information
• Email address: [email protected]
• Office: IK-231 Faculty of Informatics (4028 Debrecen Kassai út 26.)
• Online: WebEx: https://unideb.webex.com/join/nagy.david
• Office hours:• Tuesday 12:00-13:00
• Wednesday 12:00-13:00
Information
• Requirements:• 1 test (2020, May 7 18:00-19:00)
• After the test the will be an online interview (on MS Teams) in the next seminars where thestudents must explain their solutions. Other questions (besides the solutions) from thecurriculum can be also asked.
• Retake test: 2020, May 14 18:00-19:00
• Grading:• 0-50% 1
• 51-60% 2
• 61-70% 3
• 71-84 % 4
• 85-100% 5
Numeral systems
• A numeral system is a writing system for expressing numbers
• It is a mathematical method to represent numbers using digits or other symbols in a consistent manner.
• The value of any digit in a number can be determined by:1. The digit
2. Its position in the number
3. The base of the number system
Decimal System
• The value of the base is 10.
• Any decimal number n can be expressed in the following format:
• 𝑛 = 𝑛1 ∗ 100 + 𝑛2 ∗ 10
1 + …+ 𝑛𝑚 ∗ 10𝑚, where 𝑛𝑖(𝑖 = 1…𝑚)is the ith digit of the number.
• 587 = 5 * 102 + 8 * 101 + 7 * 100 = 5 * 100 + 8 * 10 + 7 * 10
• Any number can be expressed in the following format:
• 𝑛 = 𝑛1 ∗ 𝑟0 + 𝑛2 ∗ 𝑟
1 + …+ 𝑛𝑚 ∗ 𝑟𝑚, where 𝑟 is the base of thenumber system
Binary System
• The value of the base is 2.
• There are only 2 digits: 0 and 1.
• Give the decimal representation of the binary number 101110101!
• Its value is: 1*256+0*128+1*64+1*32+1*16+0*8+4*1+2*0+1*1 = 373(10)
Decimal digit 256 128 64 32 16 8 4 2 1
Binary Digit 1 0 1 1 1 0 1 0 1
Binary System
• Give the decimal representation of the binary number 10011.1011!• Integer part: 10011(2) ⇒ 19(10)
• Fractional part: 1011(2)
• Its value is: 1 * 0.5 + 0 * 0.25 + 1 * 0.125 + 1 * 0.0625 = 0.6875(10)
• The decimal representation of the number is: 19.6875(10)
Decimal digit 16 8 4 2 1
Binary Digit 1 0 0 1 1
Decimal digit 2-1 2-2 2-3 2-4
Binary Digit 1 0 1 1
Binary System
• Give the binary representation of the decimal number 543!
• Method: divide the number by 2 in each step and save the remainder.
Number Remainder
543 1
271 1
135 1
67 1
33 1
16 0
8 0
4 0
2 0
1 1
0
Binary representation: 1000011111
Binary System
• Give the binary representation of the decimal number 125.78125!
• Binary representation: 1111101.1100001Number Remainder
125 1
62 0
31 1
15 1
7 1
3 1
1 1
0
Integer part: 1111101
Number Integer part
0.78125 1
0.5625 1
0.125 0
0.25 0
0.5 0
0 1
Fractional part: 1100001
Multiply thenumber by 2
Hexadecimal systemHexadecimal digit Binary digit Decimal digit
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
A 1010 10
B 1011 11
C 1100 12
D 1101 13
E 1110 14
F 1111 15
Hexadecimal System
• Give the decimal representation of the hexadecimal number A12.3C!• Integer part: A12(2) ⇒ 2578(10)
• Fractional part: 3C(2)⇒ 0.234375(10)
• The decimal representation of the number is: 2578.234375(10)
Decimal digit 256 16 1
Hexadecimal Digit A 1 2
Decimal digit 16-1 16-2
Binary Digit 3 C
A*256 + 1*16 + 1*2 = 10*256 + 1*16 + 1*2
3 *0.0625 + C *0.00390625 = 3 *0.0625 + 12*0.00390625
Number representation
• Computer uses a fixed number of bits to represent a piece of data
• A n-bit storage location can represent up to 2n distinct numbers
• Integers, for example, can be represented in 8-bit, 16-bit, 32-bit or 64-bit.
• The programmer chooses an appropriate bit-length for the integers.
Integer representation
• Unsigned Integers: can represent zero and positive integers.
• Signed Integers: can represent zero, positive and negative integers. Three representation schemes had been proposed for signed integers:• Sign-Magnitude representation
• 1's Complement representation
• 2's Complement representation
Unsigned integer
• Unsigned integers can represent zero and positive integers, but not negative integers.
• The value of an unsigned integer is interpreted as "the magnitude of its underlying binary number".
• Example 1: Suppose that n=8 and the binary number is 0100 0001(2), the value of this unsigned integer is 1×20 + 1×26 = 65 (10).
• Example 2: Suppose that n=16 and the binary pattern is 0001 0000 0000 1000 (2), the value of this unsigned integer is 1×23 + 1×212 = 4104 (10).
Signed integers
• Signed integers can represent zero, positive integers, as well as negative integers. Three representation schemes are available for signed integers:• Sign-Magnitude representation• 1's Complement representation• 2's Complement representation
• In all the above three schemes, the most-significant bit (msb) is called the sign bit.
• The sign bit is used to represent the sign of the integer - with 0 for positive integers and 1 for negative integers.
• The magnitude of the integer, however, is interpreted differently in different schemes.
Sign-Magnitude representation
• The most-significant bit (msb) is the sign bit, with value of 0 representing positive integer and 1 representing negative integer.
• The remaining n-1 bits represents the magnitude (absolute value) of the integer. The absolute value of the integer is interpreted as "the magnitude of the (n-1)-bit binary pattern".
• Example 1: Suppose that n=8 and the binary representation is 0 100 0001 (2). Sign bit is 0 ⇒ positive.Absolute value is 100 0001 (2) = 65 (10)
Hence, the integer is +65 (10)
Sign-Magnitude representation
Example 2: Suppose that n=8 and the binary representation is 1 000 0001(2). Sign bit is 1 ⇒ negative.Absolute value is 000 0001 (2) = 1 (10)
Hence, the integer is -1 (10)
• The drawbacks of sign-magnitude representation are:• There are two representations (0000 0000 (2) and 1000 0000 (2)) for the
number zero, which could lead to inefficiency and confusion.
• Positive and negative integers need to be processed separately.
1's complement representation
• Again, the most significant bit (msb) is the sign bit, with value of 0 representing positive integers and 1 representing negative integers.
• The remaining n-1 bits represents the magnitude of the integer, as follows:• for positive integers, the absolute value of the integer is equal to "the
magnitude of the (n-1)-bit binary pattern".
• for negative integers, the absolute value of the integer is equal to "the magnitude of the complement (inverse) of the (n-1)-bit binary pattern" (hence called 1's complement).
1's complement representation
• Example 1: Suppose that n=8 and the binary representation 0 100 0001 (2).
• Sign bit is 0 ⇒ positive
• Absolute value is 100 0001 (2) = 65(10)
• Hence, the integer is +65(10)
• Example 2: Suppose that n=8 and the binary representation 1 000 0001 (2).
• Sign bit is 1 ⇒ negative
• Absolute value is the complement of 000 0001 (2), i.e., 111 1110 (2) = 126(10)
• Hence, the integer is -126(10)
1's complement representation
• Again, the drawbacks are:• There are two representations (0000 0000 (2) and 1111 1111 (2)) for zero.
• The positive integers and negative integers need to be processed separately.
2's complement representation
• Again, the most significant bit (msb) is the sign bit, with value of 0 representing positive integers and 1 representing negative integers.
• The remaining n-1 bits represents the magnitude of the integer, as follows:• for positive integers, the absolute value of the integer is equal to "the
magnitude of the (n-1)-bit binary pattern".
• for negative integers, the absolute value of the integer is equal to "the magnitude of the complement of the (n-1)-bit binary pattern plus one" (hence called 2's complement).
2's complement representation
• Example 1: Suppose that n=8 and the binary representation 0 100 0001 (2).
• Sign bit is 0 ⇒ positive
• Absolute value is 100 0001 (2) = 65 (10)
• Hence, the integer is +65 (10)
• Example 2: Suppose that n=8 and the binary representation 1 000 0001 (2).
• Sign bit is 1 ⇒ negative
• Absolute value is the complement of 000 0001 (2) plus 1, i.e., 111 1110 (2) + 1B = 127 (10)
• Hence, the integer is -127 (10)
2's complement representation
• There is only one representation for the number zero in 2's complement, instead of two representations in sign-magnitude and 1's complement.
• Positive and negative integers can be treated together in addition and subtraction. Subtraction can be carried out using the "addition logic".
Floating-Point Number Representation
• A floating-point number (or real number) can represent:• very large (1.23×1088)
• very small (1.23×10-88)
• very large negative number (-1.23×1088)
• very small negative number (-1.23×1088),
• zero
• Represented in scientific notation: 𝐹 ∗ 𝑟𝐸 , where 𝐹 is called the fracture, 𝑟 is called the radix and 𝐸 is called the exponent
Floating-Point Number Representation
• The Representation of a floating point number is not unique.• 55.66 can be represented as 5.566×10 1, 0.5566×10 2, 0.05566×10 3, etc.
• The fractional part can be normalized.
• In the normalized form, there is only one non-zero digit before the radix point.• The decimal number 123.4567 can be normalized as 1.234567×102;
Floating-Point Number Representation
• Remark: floating-point numbers suffer from loss of precision when represented with a fixed number of bits (e.g., 32-bit or 64-bit).
• This happens because there are infinite number of real numbers (even within a small range of numbers, for example between 0.0 and 0.1).
• On the other hand, a n-bit binary pattern can represent a finite 2n
distinct numbers.
• Hence, not every real number can be represented.
• The closest approximation can be used instead, resulted in loss of accuracy.
IEEE-754 32-bit Single-Precision Floating-Point Numbers
• In 32-bit single-precision floating-point representation:• The most significant bit is the sign bit (S) using 0 for positive numbers and 1
for negative numbers.
• The following 8 bits represent the exponent (E).
• The remaining 23 bits represents the fraction (F).
• number = (-1)S (1+F) (2E-127)
IEEE-754 32-bit Single-Precision Floating-Point Numbers
• Which number was represented by the following binary number0 10000000 110 0000 0000 0000 0000 0000 in IEEE-754 32-bit floating-point representation ?
• S = 0(10) → Positive number
• E = 10000000(2) = 128(10)
• F = 110 0000 0000 0000 0000 0000(2) = 0.75(10)
• Number = (-1)S (1+F) (2E-127) = 1.75(10) * 21 = 3.5(10)
IEEE-754 32-bit Single-Precision Floating-Point Numbers
• Which number was represented by the following binary number1 10000110 100 1100 0000 0000 0000 0000 in IEEE-754 32-bit floating-point representation ?
• S = 1(10) → Negative number
• E = 10000110(2) = 134(10)
• F = 100 1100 0000 0000 0000 0000(2) = 0.59375(10)
• Number = (-1)S (1+F) (2E-127) = -1.59375(10) * 27 = -204(10)
F 1 0 0 1 1 0 0 0 0 ...
2-1 = 0.5 2-2 = 0.25 2-3 = 0.125 2-4 = 0.0625 2-5 = 0.03125 ... ... ... ... 0.5+0.0625+0.03125=0.59375
IEEE-754 32-bit• Let’s store (represent) the number -416.75(10)
Number Remainder
416 0
208 0
104 0
52 0
26 0
13 1
6 0
3 1
1 1
0
Number Remainder
0.75 1
0.5 1
0
• The binary representation: 110100000.11• Scientific notation: 1.1010000011 * 28
• S = 1 because it is a negative number• E = 127+8 = 135 = 10000111 • F = 10100000110000000000000
• The binary pattern is: 1 10000111 10100000110000000000000
IEEE-754 32-bit• Let’s store (represent) the number 562.40625(10)
Number Remainder
562 0
Number Remainder
0.40625
• The binary representation: 110100000.11• Scientific notation: 1.1010000011 * 28
• S = 1 because it is a negative number• E = 127+8 = 135 = 10000111 • F = 10100000110000000000000
• The binary pattern is: 1 10000111 10100000110000000000000
IEEE-754 32-bit Single-Precision Floating-Point Numbers
• The representation scheme for 64-bit double-precision is similar to the 32-bit single-precision:• The most significant bit is the sign bit (S) using 0 for positive numbers and 1
for negative numbers.
• The following 11 bits represent the exponent (E).
• The remaining 52 bits represents the fraction (F).
Character Encoding
• In the computer memory, character are "encoded" (represented) using a chosen "character encoding schemes" (character set).
• The most commonly-used character encoding schemes are: 7-bit ASCII (ISO/IEC 646) and 8-bit Latin-x (ISO/IEC 8859-x) for western european characters, and Unicode (ISO/IEC 10646) for internationalization (i18n).
• ASCII (American Standard Code for Information Interchange) is one of the earliest character set.
• The original ASCII was a 7-bit code. It has been extended to 8-bit to better utilize the 8-bit computer memory organization.
ASCII
• Control characters (0-31): they do not represent printableinformation, but rather control devices
• Printable characters (32-126):• Space (32)
• Lowercase letters (97-122)
• Uppercase letters (65-90)
• Numbers (48-57)
• Other symbols
UNICODE
Computer Architecture
• Three basic units:• The Central Processing Unit (CPU)
• The Main Memory Unit
• The Input/Output Device
Instructions
• Instructions are commands/statements that are executed by the CPU.
• A CPU has a collection of instructions it can execute.
• It is called the instruction set.
• Example:• ADD
• COMPARE
• JUMP
• READ
• WRITE
Computer Architecture
• Control Unit –A control unit (CU) handles all processor control signals. It directs all input and output flow, fetches code for instructions and controlling how data moves around the system.
• Arithmetic and Logic Unit (ALU) –The arithmetic logic unit handles all the calculations the CPU requires (Addition, Subtraction, Comparisons). It performs Logical Operations, Bit Shifting Operations, and Arithmetic Operation.
Computer Architecture
Computer Architecture
• Main Memory Unit (Registers) –Accumulator: Stores the results of calculations made by ALU.
• Program Counter (PC): Keeps track of the memory location of the next instructions to be dealt with. The PC then passes this next address to Memory Address Register (MAR).
• Memory Address Register (MAR): It stores the memory locations of instructions that need to be fetched from memory or stored into memory.
• Memory Data Register (MDR): It stores instructions fetched from memory or any data that is to be transferred to, and stored in, memory.
• Current Instruction Register (CIR): It stores the most recently fetched instructions while it is waiting to be coded and executed.
• Instruction Buffer Register (IBR): The instruction that is not to be executed immediately is placed in the instruction buffer register IBR.
Memory
• The smallest addressable unit of computer memory is the byte, so theunit of memory capacity is the byte or its multiple
• It is used to store data
Multiple of byte Abbreviation Value
kilobyte kB 1024 byte
Megabyte MB 1024 kB
Gigabyte GB 1024 MB
Terabyte TB 1024 TB
Petabyte PT 1024 GB
Memory
• According to the writability, the memories can be divided into twogroups:
1. RAM (Random Access Memory)
2. ROM (Read Only Memory)
Random Access Memory (RAM)
• Readable and writable memory
• Loses all content when the power is turned off.
• Its content can be changed at any time.
• Its function is to store data
• It is sometimes referred to as the main memory
• It has two types.• DRAM (Dynamic RAM): It consists capacitors which lose their charge over
time, so the DRAM must be updated.• SRAM (Static RAM): is built from integrated circuit transistors, no upgrades
are needed, faster than DRAM
Computer Architecture
• Input/Output Devices – Program or data is read into main memory from the input device or secondary storage under the control of CPU input instruction. Output devices are used to display the information from a computer. If some results are evaluated by computer and it is stored in the computer, then with the help of output devices, it they can be presented it to the user.
• Buses – Data is transmitted from one part of a computer to another, connecting all the internal components to the CPU and memory, by the so-called buses. Types:• Data Bus: It transmits data among the memory unit, the I/O devices, and the processor.• Address Bus: It carries the address of data (not the actual data) between memory and
processor.• Control Bus: It carries control commands from the CPU (and status signals from other
devices) in order to control and coordinate all the activities within the computer.
Peripherals
• There are 3 typed of peripheral devices:
• Input devices: keyboard, mouse, controller, scanner, barcode reader, etc.
• Output devices: monitor, projector, speaker, printer,
• Input/Output devices (storage devices): HDD, SSD, DVD, CD, memory card
Flashdrive, etc.
Algorithms
• Algorithm: a process or set of rules to be followed in calculations or other problem-solving operations.
• A set of rules/instructions that step-by-step define how a work is to be executed upon in order to get the expected results.
• The algorithms are language-independent, i.e. they are just plain instructions that can be implemented in any language, and yet the output will be the same, as expected.
Algorithms
• Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of its steps should be clear in all aspects and must lead to only one meaning.
• Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs.
• Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it should be well-defined as well.
• Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite loops or similar.
• Feasible: The algorithm must be simple, generic and practical, such that it can be executed upon will the available resources. It must not contain some future technology, or anything.
• Language Independent: The Algorithm designed must be language-independent, i.e. it must be just plain instructions that can be implemented in any language, and yet the output will be same, as expected.
How to Design an Algorithm?
• In order to write an algorithm, the following pre-requisites are needed:• The problem to be solved by the algorithm.
• The constraints that must be considered while solving the problem.
• The inputs to solve the problem.
• The expected output when the problem the is solved.
• The solution to this problem, in the given constraints.
Example (add three numbers and print the sum)
• Step 1: Fulfilling the pre-requisites
• As discussed above, in order to write an algorithm, its pre-requisites must be satisfied.• The problem to be solved by the algorithm: Adding 3 numbers and printing
their sum.
• The constraints of the problem: The numbers must contain only digits.
• The input: The three numbers
• The output: The sum of the three numbers.
• The solution to this problem, in the given constraints: The solution consists of adding the 3 numbers. It can be done using the ‘+’ operator, or bit-wise, etc.
Example (add three numbers and print the sum)
• Step 2: Designing the algorithm
• Algorithm to add 3 numbers and print their sum:• START
• Declare 3 integer variables x,y and z
• Take the three numbers, to be added, as inputs in variables x, y, and z respectively.
• Declare an integer variable sum to store the sum of the given 3 numbers.
• Add the 3 numbers and store the result in the variable sum.
• Print the value of variable sum
• END
• Step 3: Implement the algorithm.
Example (add three numbers and print the sum)
Algortihms
• One problem, many solutions: The solution to an algorithm can be or cannot be more than one. It means that while implementing the algorithm, there can be more than one method to do implement it. For example, in the above problem to add 3 numbers, the sum can be calculated with many ways like:• + operator
• Bit-wise operators
• . . etc
Algorithm representation
To represent algorithms, the following two main techniques are used:
1. Flowchart diagrams
2. Pseudocodes
Flowchart diagrams
• Flowchart is a graphical representation of an algorithm.
• It is often used as a planning tool to solve a certain problem.
• It consists of symbols that are connected among them
• These connections represent the flow of the information.
• The process of drawing a flowchart is known as “flowcharting”.
Flowchart diagram
• Terminal: The oval symbol indicates Start, Stop and Halt in a program’slogic flow.
• Input/Output: A parallelogram denotes any function of input/output type.
• Processing: A box represents arbitrary instructions.
• Decision Diamond symbol represents a decision point.
• Connectors: Whenever flowchart becomes too complex or it spreads over more than one page, it is useful to use connector symbols. It is representedby a circle.
• Flow lines: Flow lines indicate the sequence in which instructions areexecuted. The direction of flow of control is represented by arrows.
Flowchart diagram
• Write an algorithm which reads 2 numbers from the standard input and displays their maximum.
Flowchart diagramWrite an algorithm which displays the first 10 positive integers.
Flowchart diagramWrite an algorithm which reads integer numbers until 0 is given and displays thesum of the input numbers.
Flowchart diagramLet's assume that the user will give these numbers: 5, 2, 8, 0.1. step: sum = 0
n = 1We need to check if n ≠ 0 --> 1 ≠ 0 --> TRUERead the value of n --> n = 5sum = sum + n --> sum = 0 + 5 = 5 (we increase the current value of the sum by the current value of n)
2. step: We need to check if n ≠ 0 --> 5 ≠ 0 --> TRUERead the value of n --> n = 2sum = sum + n --> sum = 5 + 2 = 7
3. step: We need to check if n ≠ 0 --> 2 ≠ 0 --> TRUERead the value of n --> n = 8sum = sum + n --> sum = 7 + 8 = 15
4. step: We need to check if n ≠ 0 --> 8 ≠ 0 --> TRUERead the value of n --> n = 0sum = sum + n --> sum = 15 + 0 = 15
5. step: We need to check if n ≠ 0 --> 0 ≠ 0 --> FALSE --> DISPLAY 15 --> END
Flowchart diagramWrite an algorithm which reads integer numbers until 0 is given and displays the average of the input numbers.
Flowchart diagramsLet's assume that the input numbers are as follows 10,2,5,0.
1. step: sum = 0count = 0n = 1We need to check if n ≠ 0 --> 1 ≠ 0 --> TRUERead the value of n --> n = 10count = count + 1 --> count = 0 + 1 = 1sum = sum + n --> sum = 0 + 10 = 10
2. step: We need to check if n ≠ 0 --> 10 ≠ 0 --> TRUERead the value of n --> n = 2count = count + 1 --> count = 1 + 1 = 2sum = sum + n --> sum = 10 + 2 = 12
3. step: We need to check if n ≠ 0 --> 2 ≠ 0 --> TRUERead the value of n --> n = 5count = count + 1 --> count = 2 + 1 = 3sum = sum + n --> sum = 12 + 5 = 17
4. step: We need to check if n ≠ 0 --> 5 ≠ 0 --> TRUERead the value of n --> n = 0count = count + 1 --> count = 3 + 1 = 4sum = sum + n --> sum = 17 + 0 = 17
5. step: We need to check if n ≠ 0 --> 0 ≠ 0 --> FALSE --> Display 17/4 --> END
Flowchart diagrams
Write an algorithm which reads integer numbers until 0 is given and displays the average of the input numbers. Do not consider 0!
Flowchart diagram
Write an algorithm which reads non-negative integer numbers until 0 is given and displays the largest input number.
Input numbers: 2, 1, 5, 0max = -1n = 11. step: We need to check if n!= 0 --> 1 != 0 --> TRUE
Read n --> n = 2We need to check if n > max --> 2 > -1 --> TRUE
max = n --> max = 22. step: We need to check if n!= 0 --> 2 != 0 --> TRUE
Read n --> n = 1We need to check if n > max --> 1 > 2 --> FALSE
3. step: We need to check if n!= 0 --> 1 != 0 --> TRUERead n --> n = 5We need to check if n > max --> 5 > 2 --> TRUE
max = n --> max = 54. step: We need to check if n!= 0 --> 5 != 0 --> TRUE
Read n --> n = 0We need to check if n > max --> 0 > 5 --> FALSE
5. step: We need to check if n!= 0 --> 0 != 0 --> FALSE --> END
Pseudocode
• A text-like representation of algorithms
• It is an implementation of an algorithm in the form of annotations and informative text written in English.
• It has no syntax like any of the programming language
• It cannot be interpreted by the computer.
• Improves the readability of any approach.
• Acts as a bridge between the program and the algorithm or flowchart.
Pseudocode
• Operators used in pseudocodes:• Assignment operators: =, <-• Arithmetic operators: +, -, *, /, mod• Comparison operators: <, >, ≤, ≥, ==, ≠• Logical operators: not, and, or
• Statements used in pseudocodes:• Decision making statements:
IF condition THENstatements
ELSEstatements
ENDIF
Pseudocode
• Statements used in pseudocodes:• Loops:
FOR variable = start_value TO end_value DOstatements
ENDFOR
FOR variable = start_value DOWNTO end_value DOstatements
ENDFOR
WHILE condition DOstatements
ENDWHILE
• Input/Output statements:READ / PRINT
Pseudocode
Write an algorithm which reads 2 numbers from the standard input and displays their maximum.
READ xREAD ymax = 0IF x > y THEN
max = xELSE
max = y
ENDIFPRINT max
PseudocodeWrite an algorithm which reads 3 numbers from the standard input and displays their maximum.
READ xREAD yREAD zIF x ≥ y AND x ≥ z THEN
PRINT xELSE IF y ≥ x AND y ≥ z THEN
PRINT yELSE
PRINT z
PseudocodeWrite an algorithm which reads 2 numbers from the standard input and displays the even numbers betweenthem.
READ xREAD yFOR i = x TO y DO
IF i mod 2 == 0 THENPRINT i
ENDIFENDFOR
Let x = 5 and y = 101. step: i = 5
We need to check if i mod 2 == 0 --> 5 mod 2 == 0 --> FALSE2. step: i = 6
We need to check if i mod 2 == 0 --> 6 mod 2 == 0 --> TRUEPRINT 6
3. step: i = 7We need to check if i mod 2 == 0 --> 7 mod 2 == 0 --> FALSE
4. step: i = 8We need to check if i mod 2 == 0 --> 8 mod 2 == 0 --> TRUEPRINT 8
5. step: i = 9We need to check if i mod 2 == 0 --> 9 mod 2 == 0 --> FALSE
6. step: i = 10We need to check if i mod 2 == 0 --> 10 mod 2 == 0 --> TRUEPRINT 10
END
PseudocodeWrite an algorithm which reads a number from the standard input and displays the text "YES" if it is a primenumber and the text "NO" otherwise
Pseudocode
Write an algorithm which reads integer numbers until 0 is given and displays the sum of the input numbers.
Pseudocodes
What is the output of the following algorithm?
READ nx = 0FOR i = 0 TO n DO
IF i mod 2 ≠ 0 THENx = x + 1
ENDIFENDFOR
Pseudocodes
What is the output of the following algorithm?
READ nx = 0FOR i = 0 TO n DO
IF i mod 2 ≠ 0 THENx = x + i
ELSEx = x - i
ENDIFENDFOR
Arrays• A data structure is a way of organizing data in a computer so that it can be used effectively.
• An array is static, homogeneous data structure which can store data
• An array consists of elements or items
• Homogeneous: the elements must have the same datatype
• Static: cannot be modified (insert, delete)
• Items are stored at contiguous memory locations
• It is easy to calculate the memory location of a certain element by knowing the address of thefirst element
• An element can be accessed by its index
• In many programming languages indeces start from 0.
• The size is the array must be defined
Arrays
Memory location 100 104 108 112 116 120 124 128 132
Element 5 2 3 4 6 10 -1 2 20
Index 1 2 3 4 5 6 7 8 9
Memory location 133 134 135 136 137 138 139 140 141
Element A C e F t 0 ? # !
Index 1 2 3 4 5 6 7 8 9
The address of a given element can be calculated as follows: first_address + index * 4
The address of a given element can be calculated as follows: first_address + index
ArraysWrite an algorithm which displays the highest element in an array
Size of an array = array_name.size
READ arraymax = -infFOR i = 1 TO array.size DO
IF array[i] > max THENmax = array[i]
ENDIF
ENDFORPRINT max
ArraysArray 5 2 3 6 0
1. Step: i = 1array[i] > max —> array[1] > max —> 5 > -inf —> TRUEmax = 5
2. Step: i = 2array[i] > max —> array[2] > max —> 2 > 5 —> FALSE
3. Step: i = 3array[i] > max —> array[3] > max —> 3 > 5 —> FALSE
4. Step: i = 4array[i] > max —> array[4] > max —> 6 > 5 —> TRUEmax = 6
5. Step: i = 5array[i] > max —> array[5] > max —> 0 > 6 —> FALSE
ArraysWrite an algorithm which displays the lowest element in an array
READ arraymin= array[1]FOR i = 2 TO array.size DO
IF array[i] < min THENmin = array[i]
ENDIF
ENDFORPRINT min
ArraysArray 5 2 3 6 0
1. Step: i = 2array[i] < min —> array[2] < min —> 2 < 5 —> TRUEmin = 2
2. Step: i = 3array[i] < min —> array[3] < min —> 3 < 2 —> FALSE
3. Step: i = 4array[i] < min —> array[4] < min —> 6 < 2 —> FALSE
4. Step: i = 5array[i] < min —> array[5] < min —> 0 < 2 —> TRUEmin = 0
ArraysWrite an algorithm which displays the index of the highest element in an array.
READ arraymax = -infFOR i = 1 TO array.size DO
IF array[i] > max THENmax = array[i]max_index = i
ENDIF
ENDFORPRINT max_index
Arrays
Write an algorithm which displays the sum of the elements in an array.
READ arraysum = 0FOR i = 1 TO array.size DO
sum = sum + array[i]
ENDFORPRINT sum
Arrays
Array 5 2 3 6 0
1. Step: i = 1sum = sum + array[i] —> sum = sum + array[1] —> sum = 0 + 5 = 5
2. Step: i = 2sum = sum + array[i] —> sum = sum + array[2] —> sum = 5 + 2 = 7
3. Step: i = 3sum = sum + array[i] —> sum = sum + array[3] —> sum = 7 + 3 = 10
4. Step: i = 4sum = sum + array[i] —> sum = sum + array[4] —> sum = 10 + 6 = 16
5. Step: i = 5sum = sum + array[i] —> sum = sum + array[5] —> sum = 16 + 0 = 16
Arrays
Write an algorithm which displays the number of even elements in an array.
READ arraycount = 0FOR i = 1 TO array.size DO
IF array[i] mod 2 == 0 THENcount = count + 1
ENDIF
ENDFORPRINT count
Arrays
Write an algorithm which displays the average of the elements in an array.
READ arraysum = 0FOR i = 1 TO array.size DO
sum = sum + array[i]
ENDFORPRINT sum/array.size
How to Analyze an Algorithm?
• Priori Analysis: Priori analysis means checking the algorithm before its implementation. In this, the algorithm is checked when it is written in the form of theoretical steps. This efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation. This is done usually by the algorithm designer. It is in this method, that the algorithm complexity is determined.
• Posterior Analysis: Posterior analysis means checking the algorithm after its implementation. In this, the algorithm is checked by implementing it in any programming language and executing it. This analysis helps to get the actual and real analysis report about correctness, space required, time consumed etc.
Algorithm Complexity
• An algorithm is defined as complex based on the amount of Space and Time it consumes. Hence the Complexity of an algorithm refers to the measure of the Time that it will need to execute and get the expected output, and the Space it will need to store all the data (input, temporary data and output). Hence these two factors define the efficiency of an algorithm.
• The two factors of Algorithm Complexity are:• Time Factor: Time is measured by counting the number of key operations
such as comparisons in the sorting algorithm.
• Space Factor: Space is measured by counting the maximum memory space required by the algorithm.
Algorithm Complexity
• Space Complexity: Space complexity of an algorithm refers to the amount of memory that this algorithm requires to execute and get the result. This can be for inputs, temporary operations, or outputs.
• Time Complexity: Time complexity of an algorithm refers to the amount of time that this algorithm requires to execute and get the result. This can be for normal operations, conditional if-else statements, loop statements, etc.
Space Complexity
• The space complexity of an algorithm is calculated by determining following 2 components:• Fixed Part: This refers to the space that is definitely required by the algorithm.
For example, input variables, output variables, program size, etc.• Variable Part: This refers to the space that can be different based on the
implementation of the algorithm. For example, temporary variables, dynamic memory allocation, recursion stack space, etc.
• Therefore Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I) is the variable part of the algorithm which depends on instance characteristic I.
• What is the space complexity of the previous algorithm?
Time Complexity
• The time complexity of an algorithm is also calculated by determining following 2 components:• Constant time part: Any instruction that is executed just once comes in this
part. For example, input, output, if-else, switch, etc.
• Variable Time Part: Any instruction that is executed more than once, say n times, comes in this part. For example, loops, recursion, etc.
• Therefore Time complexity T(P) of any algorithm P is T(P) = C + TP(I), where C is the constant time part and TP(I) is the variable part of the algorithm, which depends on instance characteristic I.
Time Complexity
• Example (linear search)• Step 1: START
• Step 2: Get the array in array and the number to be searched in x
• Step 3: Start from the leftmost element of array and one by one compare x with each element of array
• Step 4: If x matches with an element, Print True.
• Step 5: If x doesn’t match with any of elements, Print False.
• Step 6: END
• T(P) = 5 + n, which can be said as T(n).
Computer program
• A computer program is a set of instructions that the computer can perform in order to perform a certain task. The process of creating a program is called programming (coding). Programmers typically create programs by producing source code (code) which is a list of commands typed into text files.
• When a computer program is loaded into main memory and the hardware sequentially executes each instruction, this is called running or executing the program.
Programming languages
• A programming language is a formal languange.
• A formal language consists of words whose letters are taken from an alphabet and are well-formed according to a specific set of rules.
• A programming language consists of instructions and with their helpalgorithms can be implemented.
• The description of a programming language is split into two parts:• Syntax
• Semantics
Programming languages
• The main categories of programming languages:• Machine languages
• Assembly languages
• High-level languages
Machine language
• It contains instructions that can be executed directly by the CPU.
• Registers are used to store values and results.
• Each instruction makes the CPU perform a very specific task such as:• Store data,Load data, Jump,ALU operations
• It lacks a memory management support
• Machine code is usually written in hexadecimal format
• Example: 89 F8 A9 01 00 00 00 75 06 6B C0 03 FF C0 C3 C1 E0 02 83 E8 03 C3
• Problems:• Readability• Every processor or processor family has its own instruction set.
Assembly languages
• An assembly language is a low-level programming language.
• There is a strong correspondence between the instructions in the language and the architecture's machine code instructions.
• Assembly code is converted into executable machine code by a program called assembler.
• Each assembly language is specific to a particular computer architecture and sometimes to an operating system.
• It assigns human-readable labels (names) to memory locations, jump targets, etc.
Assembly languages
.globl f.text
f:mov %edi, %eax # Put first parameter into eax
registertest $1, %eax # Examine least significant bitjnz odd # If it's not a zero, jump to oddimul $3, %eax # It's even, so multiply it by 3inc %eax # and add 1ret # and return it
odd:shl $2, %eax # It's odd, so multiply by 4sub $3, %eax # and subtract 3ret # and return it
High-level programming languages
• Uses natural language (mostly English) elements
• Makes the development easier
• Complex expressions can be defined
• Control statements (if-else, switch, loops (for, while)) can be used
• Variables can be declared
• Data structures (array) can be used
• Easier to read and modify
• It is machine independent
• Easier to find and correct errors (debug)
High-level programming languages
• It requires time to translate the source to machine code.
• High level programs are generally slower than low level programs.
• Compared to low level programs, they are usually less memoryefficient.
• There is no direct communication with hardware elements.
High-level programming languages
• High-level languages can be categorized as follows based onthe modes of execution:
• Compiled:
• Machine code generation
• Intermediate representations
• Interpreted
High-level programming languages
• Machine code generation
• Intermediate representations
Java
• Java is a high-level programming language which was created in 1995.
• It is currently owned by Oracle
• It is used for:
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Games Database connection
Java
• Simple
• High-level
• Compiled• Object-oriented
• Robust Secure • Neutral • Open-source
• Very popular • Has a huge community support • Dynamic
• Multi-threaded
Java
Java
References and Resources
• The section Algorithms is based on the following website: https://www.geeksforgeeks.org/introduction-to-algorithms/
• The section Computer Architecture is based on the following website: https://www.geeksforgeeks.org/computer-organization-von-neumann-architecture/
• GeeksforGeeks: https://www.geeksforgeeks.org/
• The number representation and character representation section is based on the following website: https://www3.ntu.edu.sg/home/ehchua/programming/java/DataRepresentation.html?fbclid=IwAR20q2qu0_Xhr6wmXEMEzeuXUDLV6SyDIrermAzhoemlH6WlK60SDeoA9M
• Nagy Gusztáv: Java Programming (in Hungarian) 2007, version 1.3, http://nagygusztav.hu/