Module02-Introduction To Programming
Module02-Introduction To Programming
MODULE 2
INTRODUCTION TO PROGRAMMING
What is Programming?
►After abstraction, you work only on the model, you leave the problem
►So, you must make sure that the model captures all the required details of the
real problem
►You solve the model, not the problem
Programming Language
Model,
Algorithm
Abstraction/
Modeling Implementation
Real-World
Problem
COMPUTER
PROGRAMMER
Computer Programs
►how to represent/model the problem?
– computers work on numbers
– program about the highways in Turkey
– entities: cities and roads
– representing a city: name, latitude, longitude
– Data Structures Course deals with different modeling tools to represent
the problem in computers
– But we will use simple tools such as single variables, (static/dynamic)
arrays, ADT.
►how to express the solution?
– We will use simple ones: Flowchart, Pseudo Code
MODELING
►Very hard
►More accurate More complicated Ankara
İzmir
Representation: Model
►FIRST STEP: build a correct/accurate (and feasible) model
►what you are solving is the model, not the problem itself
– incorrect model incorrect solution
– inaccurate model meaningless solution
– infeasible model expensive implementation
Representing the Problem
►Representing highways:
– if you are only interested in total distances, you can use lines
– if you will talk about “the 274th km of the İstanbul-Ankara highway”, you
should use consecutive lines
Data
►data is represented by variables
►symbolic name for the data
►variables take values
►city variables: name, latitude, longitude
to represent İstanbul:
name: “İstanbul”
latitude: 41
longitude: 29
Variables
►variables are kept in memory
– variable is the name of the memory cell
– value is the content of the memory cell
name latitude longitude
“İstanbul” 41 29
Assignment
►block structured programs proceed by assigning values to variables
►notation: latitude 41
– “store the value 41 in the memory cell named latitude.”
► left-hand side is a variable
► right-hand side is an expression
– a computation that yields a value
Expressions
►can be a single value or variable:
– 41
– latitude
►can be combinations of values and variables connected via operators:
– 4 * longitude multiplication operator
– latitude + longitude addition operator
Assignment
►ASSIGNMENT IS NOT EQUALITY!!!
►41 latitude doesn’t make sense
►i i + 1 means: increment the value of i by 1
– if i was 5 before the operation, it will become 6 after the operation
►Mathematically, it would be incorrect:
0=1
Swap
►swap the values of two variables:
Swap: Incorrect
►num1 num2
►num2 num1
num1 num2
num1 num2
154 154
num1 num2
154 154
num2 num1
num1 num2
32 154
Swap
►tmp num1
►num1 num2
►num2 tmp
Data Types
►basic data types:
– integer
– real number
– logical
– character
– string
►composite data types: record
►vector data types: array
Basic Data Types
►integer
– birthyear, number of letters in the surname, height in cm
►real numbers
– height in m, average of several exam scores, square root of a number
►logical: values can be true or false
– student successful, older than 18 years
Character
►any symbol: letter, digit, punctuation mark, ...
– first letter of surname, the key the user pressed
►mostly written between single quotes:
– ‘Y’, ‘4’, ‘?’
Encoding
►numbers correspond to symbols
►ASCII, ISO8859-X, Unicode
integer
240 ISO8859-1
‘ð’
ISO8859-9
240
‘ğ’
Strings
►name, word, sentence, ISBN number, ...
►mostly written between double quotes:
– “Dennis Ritchie”, “ISBN 0-13-110362-8”
►use numbers if you plan to make arithmetic operations on it:
– student numbers at ITU: 9-digit numbers
– will you add/multiply/... student numbers?
– no sense in using integers, use strings
Composite Data Types
►grouping types to form a new type
capital
city name
►access:
– capital.name “Ankara”
latitude
– NOT city.name “Ankara”
longitude
►access:
– tem.code “E-6” start end
name name
– tem.end.name “Ankara”
latitude latitude
longitude longitude
Vector Data Types
►grouping elements of the same type
– exam scores for a 50 student class:
• 50 integer variables: score1, score2, ..., score50
• an integer array with 50 elements: score
score
►access:
– score22 95
1 2 50
Strings
►strings are usually arrays of characters
fullname
‘D’ ‘e’ ‘n’ ‘n’ ‘i’ ‘s’ ‘ ‘ ‘R’ ‘i’ ...
1 2 3 4 5 6 7 8 9 10
Arrays of Records
►represent the factors of a number:
– an array where each member is a factor
– a factor is a record of a base and a power
factors
base base base ►access:
2 7 11 – factors2.base 7
PROGRAM DEVELOPMENT
Development Stages
► You will study the stages in detail: Software Engineering Course
► We will use a simple version
Development Stages
►design: on “paper” ►testing: does the program work as
– model, algorithm expected?
– which programming language? – scenarios
– software engineering ►debugging: finding and correcting
the errors
►coding: writing the program
– debugger
– source code
– editor
Phase 1: Define the Problem
►In this phase, create a program specification.
►Specification defines the input data, processing that occurs, and output
data.
►This phase requires cooperative work with the programmer and the
problem owner.
►Other phases are only for the programmer.
Algorithms
►Algorithms are created for program design.
►An algorithm is a set of steps for carrying out a task.
►It is a step-by-step solution to the given problem.
►An algorithm can be represented with one of the following methods:
►Flow Chart
– Is composed of standard shapes and symbols
– It gives the solution steps to the problem
►Pseudo Code
– Is an alternative to flow chart
– Constrained form of English to produce steps involved in a problem
solution
Algorithms
Pseudo Code
►Pseudo code
– is not a programming language, so not prepared for compilation
– contains both some structural features of a programming language and a
speaking language such as English
– is easily understandable by non-programmers
– aims at defining a solution to a problem
►Rules for writing a pseudo-code:
– Use clear and proper English (or Turkish)
– Use simple and short sentences (avoid compound sentences)
– Each sentence is to indicate an action
Flow Chart
►A flowchart is a diagrammatic representation that illustrates the sequence
of operations to be performed to get the solution to a problem.
►Flowcharts are drawn in the first stages of program development.
►Flowcharts facilitate communication between programmers and non-
programmer people.
►Flowcharts play a vital role in the programming of a problem and are quite
helpful in understanding the logic of complicated and lengthy problems.
►Once the flowchart is drawn, it becomes easy to write the program in any
high-level language such as Python.
Flowcharts
►Describe algorithms
►Elements:
– box: an operation
– arrow: flow direction
– diamond: decision point
– parallelogram: input/output operation
Flow
FlowChart
ChartSymbols
Symbols
Loop
Start/End
Input Function,
(keyboard) Flow lines Procedure,
Subroutine
Process
Connection Output
(Action) (Off-page) (to printer)
Connection
Decision Output
(In-page)
(to Monitor)
Flowchart
FlowchartExample
Example
►This flowchart calculates the factorial of a given number n.
►(n! = 1*2*3*4*.....*n)
START
fact = 1
count = 1
fact
END
Flowcharts
►find the maximum score in an exam 1. choose the first score as maximum
with 50 students 2. if there are more students, go to
– represent exam scores by a 50- step 3, else go to step 5
element integer array (variable: 3. if the next score is higher than the
score) maximum, choose it as maximum
– represent maximum score by an 4. proceed to the next student
integer (variable: max) 5. print the maximum
Flowcharts
►representation problem: 1. max score1, i 2
– more students? Next score? 2. if i 50 go to step 3 else go to step 5
– counter variable: i 3. if scorei > max
then max scorei
4. i i + 1 and go to step 2
5. print max
Flowcharts
start
max score1
Y
i2 scorei > max
N max scorei
Y
i 50
N ii+1
print max
stop
Flowcharts
start
74>43
58<74
74<82
65<74
37<82
max 43
Y
i2 scorei > max
3<6
4<6
5<6
6=6
7>6
2<6 N max scorei
Y
i6
74 82
N ii+1
print max 3 4 5 6 7
82
1 2 3 4 5 6
stop
43 74 65 58 82 37
Flowcharts
►using tables to represent flow:
Flowcharts
►number guessing game:
– one player picks a number (target) between lower and upper bounds
– the other player makes a guess:
• if the guess is bigger than the target, the picker says “smaller.”
• if the guess is smaller than the target, the picker says “bigger.”
• game ends when guess = target
Flowcharts
►Algorithm I: ►Algorithm II:
– start with lower, increment by 1 until – try the number in the middle
found – if “smaller,” narrow the
1. guess lower search to the bottom half
2. if guess = target stop – if “bigger,” narrow the search
to the top half
3. guess guess + 1 and go to step 2
Flowcharts
1. bottom lower, top upper
2. guess (top + bottom) /2
3. if guess = target stop
4. if guess > target then top guess - 1
otherwise bottom guess + 1
and go to step 2
Flowcharts
start
bottom lower
top upper Y
guess = target
N print guess
guess (bottom + top) / 2
stop
guess > target
N Y
Flowcharts
start
32=19
20=19
24=19
16=19
18=19
19=19
bottom 1
top 63 Y
guess = target
19
N print guess
32>19
24>19
20>19
16<19
18<19
guess (bottom + top) / 2
stop
32 16 24 20 18 19 guess > target
N Y
17 19 31 23 19
Flowcharts
Comparing Algorithms
►number guessing: which algorithm is better?
►speed:
– worst case: first one 63, second one 6
– average case: first one 32, second one ~5
►size: the second one requires two more variables
Block Structures
► sequence ► repetition ► selection
block1
condition
condition
block2
block1 block2
block
Abstraction
►divide the main task to sub-tasks
►consider each sub-task as the main task and divide it into sub-sub-tasks, ...
– divide-and-conquer
►top-down design
►each task is implemented by a procedure (in a Python function)
Abstraction
main task
Abstraction
►procedures are only interested in WHAT sub-procedures are doing, not
HOW they are doing it
►smaller units are easier to manage
►maintaining is easier
– if the HOW of the sub-procedure changes, the super-procedure is not
affected
Abstraction
►procedures should be general:
– instead of “find the maximum score in the final exam of AIN1001”
– do “find the maximum of any array.”
– you can use this to find the “maximum score in the final exam of
AIN1001”
– and also to find the “maximum shoe size of the LA Lakers players.”
Parameters
►which data will the procedure work on?
– input parameter:
• the scores in the final exam of BIL105E
• the shoe sizes of the LA Lakers players
►what value will the procedure produce?
– output parameter:
• maximum score
• maximum shoe size
Abstraction
►find the greatest common divisor (gcd) of two numbers:
1. decompose the first number to its prime factors
2. decompose the second number to its prime factors
3. find the common factors of both numbers
4. compute the gcd from the common factors
Abstraction
►sample numbers: 9702 and 945
1. 9702 = 2 * 32 * 72 * 11
2. 945 = 33 * 5 * 7
3. 32 * 7
4. 63
Abstraction
9702
compute gcd
945
find common
factorize
factors
Euclid's Algorithm
►finding the greatest common divisor (gcd) of two numbers: Euclides
algorithm
– let a be the bigger number and b the smaller number
– the gcd of a and b is the same as the gcd of b and a % b
Euclid's Algorithm
Y N
num1 > num2
N
b>0
a num1 a num2
b num2 b num1 Y
print a
ra%b
ab
br
Euclid's Algorithm
a b r
9702 945 252
945 252 189
252 189 63
189 63 0
Comparing Algorithms
►Algorithm I:
– hard to factorize numbers
– easier to compute the gcd/lcm of more than two numbers?
►Algorithm II (Euclides):
– very fast
– very easy to implement
Input
►most programs read the data from outside:
– ask the user: get from the keyboard
– read from a file
– read from the environment: get the temperature of the room via a sensor
►input commands transfer the value read from outside to a variable
Output
►what to do with the produced results?
– tell the user: print it on the screen
– write it to a file or printer
– send to the environment: control the valve of a gas pipe
►output commands send results to output units
►error messages to error unit
Program Types
►console / command line / text mode ►graphical programs are event-
programs: driven:
– read inputs – prepare the environment
– process data and produce results (windows, buttons, ...)
– show outputs – wait for events (mouse click,
key press, ...)
– respond to events
Errors
►syntax errors
– not conforming to the rules of the language
►logical errors
– division by zero
Evaluating Programs
►efficiency ►understandability
– speed – can others (or you)
– hardware requirements understand your code?
►portability ►ease of maintenance
– can it run on another platform – can new features be
without much change? added?
– source code portability ►robustness
– can it tolerate user
errors?
Computer Hardware
Users
Applications software
Kernel
Operating systems
Hardware
APPLICATION LAYER
SYSTEMS SOFTWARE
MACHINE LEVEL
SOFTWARE
HARDWARE
DATABASE
CPU
MEMORY
DISK
KEYBOARD
MONITOR
etc.
Machine Code
►executable files have to have a ►programmers cannot write directly
computer-understandable format in machine code
►executable format differs between ►write source code in a high-level
– hardware language
– operating systems ►use tools to convert source code to
machine code
Conversion
►interpreted ► compiled
– read a command from source code – read the whole source code
– convert – convert and build an
executable file
– execute
– if an error report (all errors)
– repeat for next command
and no executable
– if error report (only first error) and abort
– conversion is done once
much faster
EXAMPLE PROBLEM:
CALCULATE THE GRADE OF A STUDENT
Get values of
Midterm1,Midterm2,
and Final
Print value of
Grade
End
Program Listing
midterm1 = float(input("first midterm:"))
midterm2 = float(input("second midterm:"))
final = float(input("final:"))
grade = 0.3 * (midterm1 + midterm2) + 0.4 * final
print(f"Grade is {grade}.")
Problem Model
Solution Algorithm
Summary
Design
Coding
Solution & Algorithm
Testing
Summary
Software Design
Coding
Solution & Algorithm
Testing