You are on page 1of 58

1

Introduction to Programming Concept


Outline
Introduction
What Is a Computer?
Computer Organization
Evolution of Operating Systems
Personal Computing, Distributed Computing and Client/Server
Computing
Machine Languages, Assembly Languages and High-level
Languages
The History of C
The C Standard Library
The Key Software Trend: Object Technology
C++ and C++ How to Program
Java and Java How to Program
Other High-level Languages
Structured Programming
The Basics of a typical C Program Development Environment
2

Introduction
• We will learn
– The C programming language
– Structured programming and proper programming techniques
• This course is appropriate for
– Technically oriented people with little or no programming
experience
– Experienced programmers who want a deep and rigorous
treatment of the language
3

What is a Computer?
• Computer
– Device capable of performing computations and making
logical decisions
– Computers process data under the control of sets of
instructions called computer programs
• Hardware
– Various devices comprising a computer
– Keyboard, screen, mouse, disks, memory, CD-ROM, and
processing units
• Software
– Programs that run on a computer
4

Computer Organization
• Six logical units in every computer:
1. Input unit
• Obtains information from input devices (keyboard, mouse)
2. Output unit
• Outputs information (to screen, to printer, to control other
devices)
3. Memory unit
• Rapid access, low capacity, stores input information
4. Arithmetic and logic unit (ALU)
• Performs arithmetic calculations and logic decisions
5. Central processing unit (CPU)
• Supervises and coordinates the other sections of the computer
6. Secondary storage unit
• Cheap, long-term, high-capacity storage
• Stores inactive programs
5

Evolution of Operating Systems


• Batch processing
– Do only one job or task at a time
• Operating systems
– Manage transitions between jobs
– Increased throughput
• Amount of work computers process
• Multiprogramming
– Computer resources are shared by many jobs or tasks
• Timesharing
– Computer runs a small portion of one user’s job then moves
on to service the next user
6
Personal Computing, Distributed
Computing, and Client/Server Computing
• Personal computers
– Economical enough for individual
• Distributed computing
– Computing distributed over networks
• Client/server computing
– Sharing of information across computer networks between
file servers and clients (personal computers)
7
Machine Languages, Assembly Languages,
and High-level Languages
• Three types of programming languages
1. Machine languages
• Strings of numbers giving machine specific instructions
• Example:
+1300042774
+1400593419
+1200274027
2. Assembly languages
• English-like abbreviations representing elementary computer
operations (translated via assemblers)
• Example:
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY
8
Machine Languages, Assembly Languages,
and High-level Languages
3. High-level languages
• Codes similar to everyday English
• Use mathematical notations (translated via compilers)
• Example:
grossPay = basePay + overTimePay
9

History of C
• C
– Evolved by Ritchie from two previous programming
languages, BCPL and B
– Used to develop UNIX
– Used to write modern operating systems
– Hardware independent (portable)
– By late 1970's C had evolved to "Traditional C"
• Standardization
– Many slight variations of C existed, and were incompatible
– Committee formed to create a "unambiguous, machine-
independent" definition
– Standard created in 1989, updated in 1999
10

The C Standard Library


• C programs consist of pieces/modules called
functions
– A programmer can create his own functions
• Advantage: the programmer knows exactly how it works
• Disadvantage: time consuming
– Programmers will often use the C library functions
• Use these as building blocks
– Avoid re-inventing the wheel
• If a premade function exists, generally best to use it rather than
write your own
• Library functions carefully written, efficient, and portable
11

The Key Software Trend: Object Technology


• Objects
– Reusable software components that model items in the real
world
– Meaningful software units
• Date objects, time objects, paycheck objects, invoice objects,
audio objects, video objects, file objects, record objects, etc.
• Any noun can be represented as an object
– Very reusable
– More understandable, better organized, and easier to
maintain than procedural programming
– Favor modularity
12

C++ and C++ How to Program


• C++
– Superset of C developed by Bjarne Stroustrup at Bell Labs
– "Spruces up" C, and provides object-oriented capabilities
– Object-oriented design very powerful
• 10 to 100 fold increase in productivity
– Dominant language in industry and academia
• Learning C++
– Because C++ includes C, some feel it is best to master C,
then learn C++
– Starting in Chapter 15, we begin our introduction to C++
13

Java and Java How to Program


• Java is used to
– Create Web pages with dynamic and interactive content
– Develop large-scale enterprise applications
– Enhance the functionality of Web servers
– Provide applications for consumer devices (such as cell
phones, pagers and personal digital assistants)
• Java How to Program
– Closely followed the development of Java by Sun
– Teaches first-year programming students the essentials of
graphics, images, animation, audio, video, database,
networking, multithreading and collaborative computing
14

Other High-level Languages


• Other high-level languages
– FORTRAN
• Used for scientific and engineering applications
– COBOL
• Used to manipulate large amounts of data
– Pascal
• Intended for academic use
15

Structured Programming
• Structured programming
– Disciplined approach to writing programs
– Clear, easy to test and debug and easy to modify
• Multitasking
– Specifying that many activities run in parallel
16
Basics of a Typical C Program Development
Environment
Program is created in
• Phases of C Programs: Editor Dis
the editor and stored
on disk.
k
Preprocessor program
1. Edit Preprocessor Dis processes the code.
k
Compiler creates
2. Preprocess Compiler Dis object code and stores
k it on disk.
3. Compile Linker Dis Linker links the object
code with the libraries
Primary k
Memory
4. Link Loader
Loader puts program
5. Load Disk ..
in memory.
..
..

6. Execute Primary Memory


CPUtakes each
CPU instruction and
executes it, possibly
storing new data
..
.. values as the program
..
executes.
17

Hardware Trends
• Every year or two the following approximately
double:
– Amount of memory in which to execute programs
– Amount of secondary storage (such as disk storage)
• Used to hold programs and data over the longer term
– Processor speeds
• The speeds at which computers execute their programs
18

General Notes About C


• Program clarity
– Programs that are convoluted are difficult to read,
understand, and modify
• C is a portable language
– Programs can run on many different computers
– However, portability is an elusive goal
• We will do a careful walkthrough of C
– Some details and subtleties are not covered
– If you need additional technical details
• Read the C standard document
• Read the book by Kernigan and Ritchie
Introduction to Algorithm
20

7 Steps in Program Development


1. Define the problem
• The inputs
• The outputs
• The processing steps to produce the required outputs
2. Outline the solution
• The major processing steps involved
• The subtask (if any)
• The user interface (if any)
• The major control stuctures (e.g. Repetition loops)
• The major variables and record structures
• The mainline logic
3. Develop the outline into an algorithm
21

7 Steps in Program Development (cont)

4. Test the algorithm for correctness


5. Code the algorithm into a specific programming
language
6. Run the program on the computer
7. Document and maintain the program
22

How do we solve problems?

• We "just do"
• Guesswork-and-luck
• Trial-and-error
• Experience (possibly someone else's)
• "Scientifically"
23

The Problem-solving Process

"Doctor, my head hurts"

Analysis Patient has elevated


pressure in anterior
Problem parietal lobe
specification
1. Sterilize cranial saw
Design
2. Anaesthetize patient
3. Remove top of skull
Algorithm 4. Get the big spoon...
5. etc., etc.
Implementation sterilize(saw,alcohol);
raise_hammer();
lower hammer(fast);
Program
start(saw);
/* etc. etc. */
Compilation 0100111010110010101010101
0010101010101001100101010
Executable 1010100101101001110101010
(solution) 1010010010111010011110101
010111110101010001101…
24

The Problem-solving Process


"Doctor, my head hurts"

Patient has elevated


Analysis pressure in anterior
Problem parietal lobe.
specification
1. Sterilize cranial saw
Design
2. Anaesthetize patient
3. Remove top of skull
Algorithm 4. Get the big spoon...
5. etc., etc.
Implementation sterilize(saw,alcohol);
raise_hammer();
lower hammer(fast);
Program start(saw);
/* etc. etc. */
Compilation
01001110101100101010101010010
10101010100110010101010101001
011010011101010101010010010111
Executable 010011110101010111110101010001
(solution) 10100001101...
25

The Problem-solving Process

Analysis
Problem
specification
Design

Algorithm

Implementation

Program

Compilation
Executable
(solution)
26

Algorithm

• A sequence of instructions specifying the steps


required to accomplish some task
• Named after:
Muhammad ibn Musa al-Khwarizmi
of Khowarezm (now Khiva in Uzbekistan)
Circa 780-850 C.E. (Common Era)
27

Algorithm –History

Muhammad ibn Musa Al-Khwarizmi


http://www-groups.dcs.st-andrews.ac.uk/~history/Mathematicians/Al-Khwarizmi.html

• Book on arithmetic:
– Hindu numeration, decimal numbers, use of zero, method for
finding square root
– Latin translation (c.1120 CE): “Algoritmi de numero Indorum”
• Book on algebra
– Hisab al-jabr w’al-muqabala
28

Algorithm – Working Definition

• A sequence of instructions describing how to do


a task

[As opposed to actually executing


the instructions]
29

Algorithm -- Examples

• A cooking recipe
• Assembly instructions for a model
• The rules of how to play a game
• VCR instructions
• Directions for driving from A to B
• A knitting pattern
• A car repair manual
• Recipe for Almond and honey slice
30

Preheat oven for 200° C


Almond and Honey Slice
Line a 30 cm  20 cm baking tray with
baking paper, and then with pastry
1/2 quantity Shortcrust Pastry Bake blind for 20 minutes, then remove
185 g unsalted butter weights and foil
100 g castor sugar Turn oven up to 220° C.
5 tablespoons honey Bring remaining ingredients to a boil,
50 ml cream stirring.
50 ml brandy or any other liqueur Spread evenly over pastry.
or spirit Bake until topping is bubbling and has
300 g flaked almonds caramelised evenly, about 15
minutes.
Cool before cutting into fingers or
squares.

From: Stephanie Alexander, The


Cook’s Companion, Viking/Penguin,
Ringwood, Victoria, 1996, p. 349.
31

Preheat oven for 200° C


Almond and Honey Slice
Line a 30 cm  20 cm baking tray with
baking paper, and then with pastry
1/2 quantity Shortcrust Pastry Bake blind for 20 minutes, then remove
185 g unsalted butter weights and foil
100 g castor sugar Turn oven up to 220° C.
5 tablespoons honey are given
Instructions Bring remaining ingredients to a boil,
50 ml cream stirring.
in the order in which
50 ml brandy or any other liqueur Spread evenly over pastry.
they are performed
or spirit Bake until topping is bubbling and has
(“executed”) caramelised evenly, about 15
300 g flaked almonds
minutes.
Cool before cutting into fingers or
squares.

From: Stephanie Alexander, The


Cook’s Companion, Viking/Penguin,
Ringwood, Victoria, 1996, p. 349.
32

From Algorithms to Programs

Problem
Algorithm: A sequence
of instructions describing
how to do a task (or
process)

C, Java Program
33

Components of an Algorithm
• Variables and values
• Instructions
• Sequences
• Procedures
• Selections
• Repetitions
• Documentation
34

Values

• Represent quantities, amounts or measurements


• May be numerical or alphabetical (or other things)
• Often have a unit related to their purpose
• Example:
– Recipe ingredients
35

Preheat oven for 200° C


Almond and Honey Slice
Line a 30 cm  20 cm baking tray with
baking paper, and then with pastry
1/2 quantity Shortcrust Pastry Bake blind for 20 minutes, then remove
185 g unsalted butter weights and foil
100 g castor sugar Turn oven up to 220° C.
5 tablespoons honey Bring remaining ingredients to a boil,
50 ml cream stirring.
50 ml brandy or any other liqueur Spread evenly over pastry.
or spirit
Bake until topping is bubbling and has
300 g flaked almonds
caramelised evenly, about 15
minutes.
Cool before cutting into fingers or
squares.

From: Stephanie Alexander, The


Cook’s Companion, Viking/Penguin,
Ringwood, Victoria, 1996, p. 349.
36

Preheat oven for 200° C


Almond and Honey Slice
Line a 30 cm  20 cm baking tray with
baking paper, and then with pastry
1/2 quantity Shotcrust Pastry Bake blind for 20 minutes, then remove
185 g unsalted butter weights and foil
100 g castor sugar Turn oven up to 220° C.
5 tablespoons honey Bring remaining ingredients to a boil,
50 ml cream stirring.
50 ml brandy or any other liqueur Spread evenly over pastry.
or spirit Bake until topping is bubbling and has
300 g flaked almonds caramelised evenly, about 15
minutes.
Cool before cutting into fingers or
squares.

From: Stephanie Alexander, The


Cook’s Companion, Viking/Penguin,
Ringwood, Victoria, 1996, p. 349.
37

Variables

• Are containers for values – places to store


values
• Example:
Variable Values

10 cookies
This jar
50 grams of sugar
can contain
3 slices of cake
etc.
38

Restrictions on Variables

• Variables may be restricted to contain a specific


type of value
39

Components of an Algorithm

 Values and Variables


• Instruction (a.k.a. primitive)
• Sequence (of instructions)
• Procedure (involving instructions)
• Selection (between instructions)
• Repetition (of instructions)
• Documentation (beside instructions)
40

Instructions (Primitives)
• Some action that is simple...
• ...and unambiguous...
• ...that the system knows about...
• ...and should be able to actually do
41

Instructions – Examples

• Take off your shoes


Directions to perform
• Count to 10 specific actions on values
• Cut along dotted line and variables.
• Knit 1
• Purl 2
• Sift 10 grams of arsenic
42

Instructions -- Application

• Some instructions can only be applied to a specific


type of values or variables
• Examples:
43

Instructions (Primitives) --
Recommendations

• When writing an algorithm, make each instruction


simple and unambiguous
• Example:

Cut chicken into pieces and Cut chicken into pieces.


brown the pieces on all sides Heat olive oil in a casserole dish.
in a casserole dish in hot Brown the chicken pieces in the
olive oil. casserole dish.
44

Instruction (Primitives)

• WhenAwriting an algorithm,
“sequence” of make the instructions
simple and unambiguous.
simple instructions
• Example:

Cut chicken into pieces and brown Cut chicken into pieces.
the pieces on all sides in a Heat olive oil in a casserole dish.
casserole dish in hot olive oil.
Brown the chicken pieces in the
casserole dish.
45

Conclusion
• An algorithm must:
– Be lucid, precise and unambiguous
– Give the correct solution in all cases
– Eventually end.
46

Developing an algorithm
• To help the initial analysis, the problem
should be divided into 3 separate
components:
1. Input: a list of the source data provided to the
problem
2. Output: a list of the outputs required
3. Processing: a list of actions needed to produce the
required outputs.
47

Example 1. Add three numbers

 A program is required to read three


numbers, add them together and print
their total.
48

Solution:

1. Underline the nouns and adjectives used in the


specification  establish the input, output
component and any object that are required.

A program is required to read three


numbers, add them together and print
their total.
49

• Defining diagram

Input Processing Output

Number1 total
Number2
Number3
50

2. Underline the verbs and adverbs used in the


specification  establish the action required.

A program is required to read three


numbers, add them together and print
their total.
51

• Defining diagram

Input Processing Output

Number1 Read three numbers total


Number2 Add numbers together
Number3 Print total number
52

3. Writing down the processing steps in an


algorithm,

Read three numbers


Add numbers together
Print total number
53

Example 2. Find average temperature

• A program is required to prompt the


terminal operator for the maximum and
minimum temperature readings on a
particular day, accept those readings
as integers, and calculate and display
to the screen the average temperature,
calculated by (maximum temperature +
minimum temperature)/2.
54

Step 1
• A program is required to prompt the
terminal operator for the maximum and
minimum temperature readings on a
particular day, accept those readings
as integers, and calculate and display
to the screen the average temperature,
calculated by (maximum temperature +
minimum temperature)/2.
55

• Defining diagram

Input Processing Output


Max_temp Avg_temp
Min_temp
56

Step 2
• A program is required to prompt the
terminal operator for the maximum and
minimum temperature readings on a
particular day, accept those readings
as integers, and calculate and display
to the screen the average temperature,
calculated by (maximum temperature +
minimum temperature)/2.
57

• Defining diagram

Input Processing Output


Max_temp Prompt for temperatures Avg_temp
Min_temp Get temperatures
Calculate average temperature
Display average temperature
58

Assignment1.
Compute mowing time
• A program is required to read from the
screen the lenght and widht of a
rectangular house block, and the lenght
and width of the rectangular house that
has been built on the block. The
algorithm should then compute and
display the mowing time required to cut
the grass around the house, at the rate
of two square metres per minute.

You might also like