MCE 312
Introduction to Computer
Programming
Engr. Adeyinka Adedigba
Department of Mechatronics Engineering,
School of Electrical and Electronics Engineering,
Federal University of Technology, Minna.
Outline of Topics
• Categories of software
• Programs and programming languages
• Syntax and semantics
• Compilers and interpreters
• Programs and program execution
• Program development Cycle
• Control structure
• Debugging
Software Categories
• System SW
– Programs written for computer systems
• Compilers, operating systems, …
• Application SW
– Programs written for computer users
• Word-processors, spreadsheets, & other
application packages
A Layered View of the Computer
Application Programs
Word-Processors, Spreadsheets,
Database Software, IDEs,
etc…
System Software
Compilers, Interpreters,Preprocessors,
etc.
Operating System, Device Drivers
Machine with all its hardware
Operating System (OS)
∙ Provides several essential services:
– Loading & running application programs
– Allocating memory & processor time
– Providing input & output facilities
– Managing files of information
Programs
• Programs are written in programming languages
– PL = programming language
– Pieces of the same program can be written in different
PLs
• Languages closer to the machine can be more efficient
• As long as they agree on how to communicate
• A PL is
– A special purpose and limited language
– A set of rules and symbols used to construct a
computer program
– A language used to interact with the computer
Computer Languages
– Machine Language
• Uses binary code
• Machine-dependent
• Not portable
• Assembly Language
– Uses mnemonics
– Machine-dependent
– Not usually portable
• High-Level Language (HLL)
– Uses English-like language
– Machine independent
– Portable (but must be compiled for different platforms)
– Examples: Pascal, C, C++, Java, Fortran, . . .
Machine Language
• The representation of a computer program which is
actually read and understood by the computer.
– A program in machine code consists of a sequence of machine
instructions.
• Instructions:
– Machine instructions are in binary code
– Instructions specify operations and memory cells involved in the
operation
Example: Operation Address
0010 0000 0000 0100
0100 0000 0000 0101
0011 0000 0000 0110
Assembly Language
• A symbolic representation of the machine language of a
specific processor.
• Is converted to machine code by an assembler.
• Usually, each line of assembly code produces one
machine instruction (One-to-one correspondence).
• Programming in assembly language is slow and
error-prone but is more efficient in terms of hardware
performance.
• Mnemonic representation of the instructions and data
• Example:
Load Price
AddTax
Store Cost
High-level language
• A programming language which use statements
consisting of English-like keywords such as "FOR",
"PRINT" or “IF“, ... etc.
• Each statement corresponds to several machine
language instructions (one-to-many correspondence).
• Much easier to program than in assembly language.
• Data are referenced using descriptive names
• Operations can be described using familiar symbols
• Example:
Cost := Price + Tax
Syntax & Semantics
• Syntax:
– The structure of strings in some language. A
language's syntax is described by a grammar.
– Examples:
• Binary number
<binary_number> = <bit> | <bit> <binary_number>
<bit> =0|1
• Identifier
<identifier> = <letter> {<letter> | <digit> }
<letter> =a|b|...|z
<digit =0|1|...|9
• Semantics:
– The meaning of the language
Syntax & Grammars
• Syntax descriptions for a PL are
themselves written in a formal language.
– E.g. Backus-Naur Form (BNF)
• The formal language is not a PL but it can
be implemented by a compiler to enforce
grammar restrictions.
• Some PLs look more like grammar
descriptions than like instructions.
Compilers
• Compiler
– A program that converts another program from
some source language (or high-level
programming language / HLL) to machine
language (object code).
– Some compilers output assembly language
which is then converted to machine language by
a separate assembler.
– Is distinguished from an assembler by the fact
that each input statement, in general,
correspond to more than one machine
instruction.
Compilation into Assembly L
Source Assembly
Program Compiler Language
Assembly Assembler Machine
Language Language
Compilation
Source Target
Program Compiler Program
Input Target Program Output
• Compiler translates source into target (a machine
language program)
• Compiler goes away at execution time
• Compiler is itself a machine language program,
presumably created by compiling some other high-level
program
• Machine language, when written in a format understood
by the OS is object code
Interpretation
Source
Program
Interpreter Output
Input
• The interpreter stays around during execution
• It reads and executes statements one at a time
Compilation vs. Interpretation
• Compilation:
– Syntax errors caught before running the program
– Better performance
– Decisions made once, at compile time
• Interpretation:
– Better diagnostics (error messages)
– More flexibility
– Supports late binding (delaying decisions about
program implementation until runtime)
• Can better cope with PLs where type and size of
variables depend on input
– Supports creation/modification of program code on
the fly (e.g. Lisp, Prolog)
Mixture of C & I
Source Intermediate
Program Translator Program
Intermediate
Program
VM Output
Input
• Many programming languages implement this
• Interpreter implements a Virtual Machine (VM).
JAVA
For portability:
Java Compiler
bytecode
ML Interpreter
For flexibility: Just In Time (JIT) compiler translates
bytecode into ML just before execution
Programs
• Source program
– The form in which a computer program,
written in some formal programming
language, is written by the programmer.
– Can be compiled automatically into object
code or machine code or executed by an
interpreter.
– Python source programs have extension
‘.py’
Compilers & Programs
• Object program
– Output from the compiler
– Equivalent machine language translation of the
source program
– Files usually have extension ‘.obj’
• Executable program
– Output from linker/loader
– Machine language program linked with necessary
libraries & other files
– Files usually have extension ‘.exe’
What is a Linker?
• A program that pulls other programs together so
that they can run.
• Most programs are very large and consist of
several modules.
• Even small programs use existing code provided
by the programming environment called libraries.
• The linker pulls everything together, makes sure
that references to other parts of the program
(code) are resolved.
Running Programs
• Steps that the computer goes through to run a
program:
Memory
Machine language
program
(executable file)
Input Data Data entered CPU
during execution
Computed results
Program Output
Program Execution
• Steps taken by the CPU to run a program
(instructions are in machine language):
1. Fetch an instruction
2. Decode (interpret) the instruction
3. Retrieve data, if needed
4. Execute (perform) actual processing
5. Store the results, if needed
Program Errors
• Syntax Errors:
– Errors in grammar of the language
• Runtime error:
– When there are no syntax errors, but the program
can’t complete execution
• Divide by zero
• Invalid input data
• Logical errors:
– The program completes execution, but delivers
incorrect results
– Incorrect usage of parentheses
Program Development Cycle
• Many programmers follow a sequence of
Steps to create their programs.
1. Analyze – Define the Problem
2. Design – Plan a Solution for the Problem
3. Write the code
4. Testing and debugging
5. Write a complete documentation
Program Development Cycle
• Many programmers follow a sequence of Steps to
create their programs.
1. Analyze – Define the Problem
– Make sure that you understand what the program should
do. What should the user be able to enter? How? How
does the program come up with an answer? What does
the program output? How?
• User – a person who uses a computer program.
• End User – the user that the program was made for.
2. Design – Plan a Solution for the Problem
– Develop a PRECISE sequence of steps to solve the
problem
• An algorithm is a precise sequence of steps to solve a problem.
Develop an Algorithm
• Imagine you want a program that tells a
user how many stamps they need in order
to mail a certain number of pages.
• You need one stamp for every 5 pages
– 6 pages = 2 stamps
– 12 pages = 3 stamps
–…
• Write an algorithm (the steps needed) to
solve this problem
Program Development Cycle –
Design (Continued)
• Typically a program follows three general
steps
1. Input
2. Processing (Formulas)
3. Output
Program Development Cycle –
Design (Continued)
• Are those three steps enough?
• What about if the user enters “Banana” instead of a number of
sheets?
• The program does not know how to find the number of stamps
required to mail “Banana” number of sheets
• In order for the program to run without crashing, our algorithm must
make sure that the user inputs some valid data.
– There are two main ways of doing this:
1. Prevention – Making sure that the user is not physically able to enter in invalid data.
2. Validation – Allowing the user to enter invalid data, but checking it to make sure it is valid
before processing.
• So, there are really 4 general steps most programs follow:
1. Input
2. Read Input
3. Validate Input
2. Process
3. Output
Develop an Algorithm
• OK, now with THAT information, try developing
the algorithm
• One good algorithm developed could look like
this:
1. Request the number of sheets of paper from the user;
call it Sheets (Input/Read)
2. Make sure Sheets is a positive whole number
(Input/Validation)
3. Divide Sheets by 5 (Processing)
4. Round the result from step 3 up to the highest whole
number; call it Stamps (Processing)
5. Reply with the number Stamps (Output)
Programming Tools
• Flowcharts – A chart that consists of symbols
connected by arrows. Within each symbol is a phrase
presenting the activity at that step. The shape of the
symbol indicates the type of operation that is to occur.
• Hierarchy Charts – A chart that shows the overall
program structure. These charts describe what each
part, or module, does and how they are related. These
modules intentionally omit details of how they work.
• Pseudocode – an abbreviated plain English version of
actual computer code. Kind of a mix between English
and code. THERE IS NO OFFICIAL SYNTAX TO
PSEUDOCODE.
Flow Charts
• Flow Line - indicates the
flow of logic
• Terminal – indicates the
start or end of a task
• Input/Output – used for
input or output operations.
What is to be input or
output should be in the
figure.
Flow Charts
• Processing - used to show a
processing step. The instructions
are displayed in the figure.
• Decision – used to show when a
decision needs to be made. Lines
for yes and no come out of it. The
question is displayed in the figure.
• Connector – Used to join flow
lines.
Stamps Flowchart
Start
Read
Sheets
Display Is sheets a
Error N positive
whole
Message o number?
Y
Set Stamps
e
= Sheets/5
s
Round Stamps to
nearest whole
number
Display
Stamps
End
Hierarchy Chart
Postage
Stamp
Program
Calculate Display
Input
Stamps Stamps
Round Stamps to
Read Validate Set Stamps the next whole
Sheets Sheets = Sheets/5 number
Program Development Cycle
3. Write the Code – Implement a solution
– The instructions in a programming language
collectively called code.
– Your code should be a translation of your algorithm
developed into the programming language.
• In this class we use python and C++, but there are many
other programming languages: C, C#, Ruby, Java, Visual
Basic, etc.
– This is the major focus of this course, but note that
you need to be able to think algorithmically in order to
do this.
• Meaning, you need to be able to logically solve the problem in
order to write a program for it.
Program Development Cycle
4. Testing and Debugging – Locate and
remove any errors in the program
– Testing is the process of finding errors in a
program
– Debugging is the process of removing errors
in a program.
• An error in a program is called a bug.
– We will talk more specifically about the kinds
of errors that can occur in a program once
we start programming.
Program Development Cycle
5. Complete All Documentation – Organize the
material that describes the program.
– Documentation is any material whose purpose is
to allow another person or programmer to use or
understand the program
– Two kinds of documentation:
1. External Documentation – Material outside of the code
files that describe the program.
2. Internal Documentation – Lines inside of a code file that
do nothing except describe details of the program.
What is an Algorithm?
• Steps used to solve a problem
• Problem must be
– Well defined • Steps must be
– Fully understood – Ordered
by the programmer – Unambiguous
– Complete
40
Program Development
1. Understand the problem
2. Represent your solution (your algorithm)
– Pseudocode
– Flowchart
3. Implement the algorithm in a program
4. Test and debug your program
41
Step 1: Understanding the
Problem
• Input
– What information or data are you given?
• Process
– What must you do with the information/data?
– This is your algorithm!
• Output
– What are your deliverables?
42
“Weekly Pay” Example
• Create a program to calculate the
weekly pay of an hourly employee
– What is the input, process, and output?
• Input: pay rate and number of hours
• Process: multiply pay rate by number of
hours
• Output: weekly pay
43
Step 2: Represent the Algorithm
• Can be done with flowchart
or pseudocode
• Flowchart
– Symbols convey different
types of actions
• Pseudocode
– A cross between code and
plain English
• One may be easier for you
– use that one 44
Step 2A: Pseudocode
• Start with a plain English description,
then…
1. Display “Number of hours worked: ”
2. Get the hours
3. Display “Amount paid per hour: ”
4. Get the rate
5. Compute pay = hours * rate
6. Display “The pay is $” , pay
45
Flowchart Symbols
Start
Start Symbol Input/Output
End
End Symbol Decision Symbol
Data Processing Flow Control Arrows
Symbol
46
Step 2B: Flowchart
Start Get the rate
Display
“Number pay = hours *
of hours rate
worked: ”
Display “The
Get the
pay
hours is $” , pay
Display
“Amount
paid per hour: End
” 47
Steps 3 and 4: Implementation
and Testing/Debugging
• We’ll cover implementation in detail next
class
• Testing and debugging your program
involves identifying errors and fixing them
– We’ll talk about this later today
48
Algorithms and Language
• Notice that developing the algorithm
didn’t involve any programming language
at all
– Only pseudocode or a flowchart was needed
– An algorithm can be coded in any language
• All languages have 3 important control
structures we can use in our algorithms
49
Control Structures
Control Structures
• Structures that control how the program
“flows” or operates, and in what order
• Sequence
• Decision Making
• Looping
51
Sequence
• One step after another, with no branches
• Already wrote one for “Weekly Pay”
problem
• What are some real life examples?
– Dialing a phone number
– Purchasing and paying for groceries
52
Decision Making
• Selecting one choice from many based
on a specific reason or condition
– If something is true, do A … if it’s not, do B
• What are some real life examples?
– Walking around campus (construction!)
– Choosing where to eat lunch
53
Decision Making: Pseudocode
• Answer the question “Is a number
positive?”
– Start with a plain English description
1. Display “Enter the number: ”
2. Get the number (call it num)
3. If num > 0
4. Display “It is positive”
5. Else
6. Display “It is negative”
54
Decision Making: Flowchart
Display “Enter Get the
Start the number: ” number
TRUE num FALSE
>0
Display Display
“It is “It is
positive” negative”
End
55
Looping
• Doing something over and over again
• Used in combination with decision making
– Otherwise we loop forever
• This is called an “infinite loop”
• What are some real life examples?
– Doing homework problem sets
– Walking up steps
56
Looping: Pseudocode
• Write an algorithm that counts from 1-20
– Start with a plain English description
1. Set num = 1
2. While num <= 20
3. Display num
4. num = num + 1
5. (End loop)
57
Looping: Flowchart
Start num = 1
There’s an error in this
flowchart… do you see
it?
num TRUE Display num = num +
>= 20 num 1
FALSE
End
58
Looping: Flowchart
Start num = 1
num TRUE Display num = num +
<= 20 num 1
FALSE
End
59
Debugging
A Bit of History on “Bugs”
• US Navy lab – September 9, 1947
• Grace Hopper and her colleagues
were working on the Harvard Mark
II
– Or trying to… it wasn’t working right
• They found a literal bug inside the machine
– Taped the bug (a moth)
into their log book
61
Errors (“Bugs”)
• Two main classifications of errors
• Syntax errors
– Prevent Python from understanding what to
do
• Logical errors
– Cause the program to run incorrectly, or to
not do what you want
62
Syntax Errors
• “Syntax” is the set of rules followed by a
computer programming language
– Similar to grammar and spelling in English
• Examples of Python’s syntax rules:
– Keywords must be spelled correctly
True and False, not Ture or Flase or Truu
– Quotes and parentheses must be closed:
("Open and close")
63
Syntax Error Examples
• Find the syntax errors in each line of code
below:
1 prnit("Hello")
2 print("What"s up?")
3 print("Aloha!)
4 print("Good Monring")
64
Syntax Error Examples
• Find the syntax errors in each line of code
below:
1 prnit("Hello")
2 print("What"s up?")
3 print("Aloha!)
4 print("Good Monring")
not actually
a syntax
error
65
Logical Errors
• Logical errors don’t bother Python at all…
they only bother you!
• Examples of logical errors:
– Using the wrong value for something
currentYear = 2013
– Doing steps in the wrong order
• “Close jelly jar. Put jelly on bread. Open jelly
jar.”
66
Exercise
• Write an algorithm that asks a user for
their name, then responds with “Hello
NAME”
• You can use a flowchart or pseudocode
Start
Input/Output Decision
End
Data Flow Control
67
Processing
Exercise #2
• Write an algorithm that asks a user for
their grade, and tells them their letter
grade.
A: 100 - 90 C: <80 - 70 F: <60 - 0
B: <90 - 80 D: <70 - 60
Start
Input/Output Decision
End
Data Processing Flow Control
68
Up Next
• Introduction to Python Programming
Language