1/12/2018
CHAPTER 1
INTRODUCTION TO PROGRAMMING
Problem solving
CONCEPTS
with computers…
LEARNING OUTCOMES INTRODUCTION TO PROGRAMMING
Explain the concepts of problem-solving and structured
Computer programming is writing computer
programming. instructions to tell the computer step-by-step how to
Recognize 7 steps in program development process. process data and carry out other basic operations
Introduction to developing an Algorithm with systematically3.
Pseudocode and Flowchart.
The basic operations of computers include:
Differentiate between variables and constants.
Introduction to data types. - Receive inputs
Differentiate between character, numeric and logical - Make decisions
data types.
- Repeat operations
- Display results the outputs
References:
References:
Problem Solv ing and Programming Concepts (9th Edition) . Maureen Sprankle, Jim Hubbard, Pearson Education Limited 2012. 3. Computer Science for Matriculation Semester 2. Yew Kwang Hooi, Oxford Fajar 2014.
Simple Program Design. A step by step approach (5th Edition). Lesley Anne Robertson. Cengage Learning 2006.
CONTENTS Introduction to Programming (cont)
The executable file that stores the set of instructions is
called a computer program.
7 steps of program development process Programming helps us to solve many problems that
Constants and variables require speed, memory and precision:
(a) Speed – repetitive tasks can be done at lightning
Local and global variables
speed.
Meaningful data names
(b) Memory – total recall of all stored data and
Data types information during a search.
(c) Precision – a computer does not make careless
mistake
References:
3. Computer Science for Matriculation Semester 2. Yew Kwang Hooi, Oxford Fajar 2014.
1
1/12/2018
Introduction to Programming (cont)
Hence, computer programs are used to make repetitive
and boring tasks fast and automatic. 7 STEPS OF PROGRAM
Examples:
DEVELOPMENT PROCESS
(a) A banking system automatically updates the database
every midnight.
(b) A spreadsheet program can help user find statistical
figures automatically. It also generates charts using the
wizards.
(c) Computers at point-of-sales at shopping outlets retrieve
product information after the cashier scans the barcode.
References:
3. Computer Science for Matriculation Semester 2. Yew Kwang Hooi, Oxford Fajar 2014.
7 STEPS OF PROGRAM DEVELOPMENT
Introduction to Programming (cont) PROCESS
Not all problems can be solved by computer programs:
1. Define the problem
(a) Computer programs are best suited for problems which
have clearly defined steps, are repetitive and use 2. Outline the solution
electronic information. 3. Develop an algorithm (based on the outline)
(b) Problems which are not suitable are those that are based 4. Test the algorithm (for correctness)
on intuition and creativity. 5. Code the algorithm (using a specific programming
language)
6. Run the program (on the computer)
7. Document & Maintain the program
References:
3. Computer Science for Matriculation Semester 2. Yew Kwang Hooi, Oxford Fajar 2014.
Programming Languages 1 DEFINE THE PROBLEM
A programmer writes codes of a program using a
suitable language. To help with initial analysis, the problem should be
divided into three separate components:
Five generations of programming languages:
• the inputs
1. 1GL (machine language)
• the outputs
2. 2GL (assembly language) • the processing steps to produce the required outputs
3. 3GL (structured programming, object-oriented
programming) E.g. C (used in our syllabus) Use IPO chart (Input Process Output Chart) to help
4. 4GL (non-procedural programming) separate and define the three components.
5. 5GL (constraint-based programming)
References:
3. Computer Science for Matriculation Semester 2. Yew Kwang Hooi, Oxford Fajar 2014.
2
1/12/2018
1 DEFINE THE PROBLEM (CONT) 2 OUTLINE THE SOLUTION (CONT)
Example (step-by-step to solve the problem) :
IPO Chart Get the price of product purchased by the customer
Get the discount rate
INPUT section contains all input data to be Calculate the discounted amount
processed in solving the problem. (discount_amount=price*discount_rate)
Calculate the payment after discount
The PROCESS section contains all processing:
(payment=price-discount_amount)
A list of actions needed to produce the required outputs.
Display the payment amount to the customer
The OUTPUT includes all required outputs as
designated by the problem and/or the user.
3 DEVELOP THE OUTLINE INTO AN
1 DEFINE THE PROBLEM (CONT) ALGORITHM
Example: Shop A is offering a 20% discount The solution outline developed in Step 2 is
for all products. Calculate the payment for expanded into an algorithm.
the customers. A program must be systematically and properly
IPO Chart designed before coding begins.
This design process results in the construction of
Input Process Output
an algorithm.
price 1. Prompt and Get price payment
discount_rate 2. Calculate payment
3. Display payment
4. END
2 OUTLINE THE SOLUTION WHAT IS AN ALGORITHM?
This initial outline is usually a rough draft of the An algorithm is like a recipe: it lists the steps
solution and may include: involved in accomplishing a task.
• The major processing steps involved
• The major subtasks (if any) It is a set of precise steps that describe exactly the
• The user interface (if any) tasks to be performed and the order in which they
• The major control structures (e.g. repetition loops) are to be carried out to produce the desired output
• The major variables and record structures from a given input.
• The mainline logic
3
1/12/2018
WHAT IS AN ALGORITHM? FLOW CHART
An algorithm (instructions) must:
Be lucid, precise and unambiguous • A graphic illustration of an algorithm.
Give correct solutions in all cases
Eventually end
Be executable one step at a time
Be complete
Not assume
Not skip any steps
3 DEVELOP THE OUTLINE INTO AN ALGORITHM
TOOLS TO BUILD ALGORITHM (CONT)
Pseudocode Flowchart
Tools used to present algorithms : Calculate_payment Start
Pseudocode (more English-like) Set discount_rate = 0.20
Flowcharts Prompt and Get price discount_rate = 0.20
Nassi-Schneiderman diagrams (not used in our course)
payment = price – price *
Prompt and Get price
discount_rate
Display payment payment = price –
price*discount_rate
END
Display payment
End
4 TEST THE ALGORITHM FOR
PSEUDOCODE CORRECTNESS
Pseudocode This step is one of the most important in the
• Algorithm written in simple English (All development of a program, and yet it is the step
statements are written in simple English). most often forgotten.
• Each instruction is written on a separate line.
• Keywords and instructions are written from top The main purpose of desk checking (test the
to bottom, with only one entry and one exit. algorithm) is to identify major logic errors early, so
• Groups of statements may be formed into that they may be easily corrected.
modules, and that group is given a name.
(optional)
Early error identification is better because will save
time and cost.
4
1/12/2018
4 TEST THE ALGORITHM FOR CORRECTNESS
(CONT) 6 RUN THE PROGRAM ON THE COMPUTER
This step uses a program compiler and programmer-
designed test data to machine test the code for syntax errors
and logic errors.
Syntax errors
– any violation of rules of the language results in syntax error.
– E.g. End of statement marker: Many languages insist on a
semi-colon ‘;’ to indicate an end-of-statement, such as,
✘ print z ✔ print z;
Syntax: all programming languages have a set of rules on
what is, and is not allowed when forming a line of code. In
other words, all programming languages have a ‘grammar’.
4 TEST THE ALGORITHM FOR CORRECTNESS 6 RUN THE PROGRAM ON THE COMPUTER
(CONT) (CONT)
Logic errors
– These errors are related to logic of the program
execution.
– Logic errors occur when the code does not run in the way
it was intended because of the way it is written.
– Logic errors can be easy-to-spot blatant mistakes or
subtle problems that are extremely difficult to spot.
– E.g. Wrong operations in a mathematical formula to
calculate length of hypotenuse of a right-angle triangle.
✘ h = sqrt(a*a – b*b);
✔ h = sqrt(a*a + b*b);
5 CODE THE ALGORITHM INTO A 7 DOCUMENT AND MAINTAIN THE
SPECIFIC PROGRAMMING LANGUAGE PROGRAM
Only after all design considerations have been met Program documentation should not be listed as the
should you actually start to code the program into last step in the program development process, as it
your chosen programming language (e.g. C, C++ , is really an ongoing task from the initial definition of
Java, C#, Pascal, MS Visual Basic). the problem to the final test result
Documentation involves both external
documentation and internal documentation that
may have been coded in the program
5
1/12/2018
INTERNAL AND EXTERNAL DOCUMENTATION CONSTANTS AND VARIABLES
Internal documentation A constant is a value – that is, a specific
• Remarks or comments written with the alphabetical and/or numeric value – that never
instructions to explain what is being done in the changes during the processing of all the
program. instructions in a solution.
• Necessary so that the program can be easily
E.g. #define PI 3.14159265
understood by another programmer.
External documentation
• Manuals or help menus written about the In contrast, the value of a variable may change
solutions. during processing. In many languages, variables
• For users of the program. are called identifiers.
CONSTANTS AND VARIABLES LOCAL AND GLOBAL VARIABLES
HOW DO WE STORE DATA IN A PROGRAM ? LOCAL AND GLOBAL VARIABLES
Data can be stored within a program as a single Global declaration
variable, such as an integer or a character, or a Variables declared at this section is visible to
group items (sometimes called an aggregate), such all parts of the program.
as an array, a structure, or a file.
Local declaration
Variables declared in a certain function.
Visible only to the functions that contain
them.
6
1/12/2018
EXAMPLES OF INCORRECT VARIABLE NAMES
Data Item Incorrect Problem Correction
Variable Name
MEANINGFUL DATA NAMES
Hours worked hours worked Space between hours_worked
words
Name of Client cn Does not define client_name
data item
Rate of pay pay-rate Using pay_rate
mathematical
operator
DATA NAMING CONVENTION EXERCISE: INCORRECT VARIABLE NAMES
Name a variable according to what it represents (meaningful
Data Item Incorrect Variable Problem Correction
names). Name
Do not use spaces in a variable name.
Start a variable with a letter. Quantity per Quantity/customer
customer
Do not use any mathematical operator in a variable name.
6% sales tax 6%_sales_tax
Be consistent when using upper and lower case characters.
Client address Client_address_for_cli
Do not use system reserved words.
ent_of_XYZ_Corporati
on_in_California
Hours worked Hour worked
Break time break
IMPORTANCE OF NAMING CONVENTION
Allows several programmers to work on the same
project without conflict in using variable names.
Allows program to be easily read due to DATA TYPES
consistency of variable names within a company.
Codes can be easily maintained.
Software performs more efficiently.
Increase performance expectation.
Produce clean, well-written programs.
7
1/12/2018
DATA TYPES 1. DATA TYPE - NUMERIC
• Data are unorganized facts.
• At the beginning of a program, the programmer must
• Numeric data
clearly define the form or type of data to be collected for
the variables created. • Integer
• Float
• The data types can be:
• Primitive Data Types, or Integer: whole number, such as 5297 or -367 which can
• Composite Data Types be positive or negative.
Float: real numbers, which are whole numbers plus
decimal parts. E.g. 3.671234
1. PRIMITIVE DATA TYPES 2. DATA TYPE – CHARACTER/ALPHANUMERIC
• A primitive data item is one containing a single • ALL single digit numbers, letters, and special characters
variable that is always treated as a unit. available in computer. (placed within quotation marks)
• E.g. ‘A’, ‘a’, ‘1’, ‘@’, ‘#’, ‘+’
• A data type consists of a set of data values and a
set of operations that can be performed on those • Uppercase and lowercase letters are considered
values. different characters.
• The most common elementary data types are: • Variables declared as characters cannot be used
* integer * character * for calculations. E.g. ‘A’+ ‘1’ = ???
boolean
* float * double • One or more characters can be combined into a
“string”. E.g. : “a”, “abc”, “Hello World 123 !!”
2. COMPOSITE DATA TYPES 3. DATA TYPE – LOGICAL/BOOLEAN
• The data items that it contains are its components, • Hold only two values – true or false.
which may be primitive data items or another data
structure.
• Implementation in programming languages
may differ. E.g. ‘T’, ‘F’, ‘yes’, ‘no’, 0, 1, etc.
• The most common data structures are:
* Records
• Mainly used as a control flag or a switch.
* File (for permanent storage)
E.g.
* Array
credit_ok = true
* String
cheque_cleared = “Y”
8
1/12/2018
3. DATA TYPE: EXAMPLES
RULES FOR DATA TYPES
Most commonly used data types: numeric (integer
and float), character (including string), and logical.
A programmer designates the data type during
float programming process.
Numeric data types are used for numeric item
calculations. Other numeric items should be
‘A’ ‘a’ ‘M’ ‘z’ ‘k’ designated in character or string data types even if
‘1’ ‘5’ ‘7’ ‘8’ ‘0’
‘+’ ‘=‘ ‘(‘ ‘%’ ‘$’ data are all numbers. E.g. zip code.
3. DATA TYPE: EXAMPLES (CONT)
DATA VALIDATION
• Data should always undergo a validation check before it
is processed by a program.
• Different types of data require different checks – for
example:
* Correct type
* Correct range
* Correct length
* Completeness
* Correct date
3. DATA TYPE: EXAMPLES (CONT)
WHY MUST INPUT BE VALIDATED?
• Risks of data entry errors are high due to:
• Large volume of data entered.
• Human error keying in data.
• Invalid input leads to inaccurate output.
• E.g., salary reported incorrectly if a datum is
entered as 23000 instead of 32000.
• Input errors can cause program interruptions.
• E.g., spaces entered for numeric field used in
arithmetic operation can cause errors.
9
1/12/2018
SUMMARY
The steps in program development were
introduced and briefly described below:
1. Define the problem
2. Outline the solution
3. Develop the outline into an algorithm
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
10