0% found this document useful (0 votes)
0 views

Principles of Programming

The document outlines the principles of programming, detailing the process of writing, testing, debugging, and maintaining source code. It explains the characteristics and types of programming languages, the importance of syntax and semantics, and the role of algorithms in problem-solving. Additionally, it discusses the use of flowcharts and pseudo code as tools for planning and visualizing algorithms.

Uploaded by

quansaha085
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Principles of Programming

The document outlines the principles of programming, detailing the process of writing, testing, debugging, and maintaining source code. It explains the characteristics and types of programming languages, the importance of syntax and semantics, and the role of algorithms in problem-solving. Additionally, it discusses the use of flowcharts and pseudo code as tools for planning and visualizing algorithms.

Uploaded by

quansaha085
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 86

PRINCIPLES OF PROGRAMMING

introduction
What is programming?

Computer programming (programming or


coding) is the process of writing, testing,
debugging/troubleshooting, and
maintaining the source code of computer
programs
What is programming?
Programming is a process!!
Steps:
1. Writing of source code-refers to the
constructing of the program code. It
involves typing of the code most of the
time.
2. Testing of source code-the purpose of
testing is to verify how well or otherwise
your program is working and to locate
what errors are impeding its work
What is programming?
3. Debugging of source code-debugging is
done to locate and correct errors that
prevent the program from working

4. Maintenance –to prevent future problems


that may come up in the source code

The purpose of programming is to create a


program that exhibits a certain desired
behavior (customization)
Source Code
In computer science, source code is any collection of
statements or declarations written in some human-
readable computer programming language.

Source code allows the programmer to communicate


with the computer using a reserved number of
instructions.

The code may be a modification of an existing source


or something completely new

This source code is written in a programming


language.
programming language
A programming language is a machine-
readable artificial language designed to express
computations that can be performed by a
machine, particularly a computer.

A programming language is a set of instructions


and a series of lexical conventions specifically
designed to order computers what to do

Programming languages can be used to create


programs that specify the behavior of a machine,
to express algorithms precisely, or as a mode of
human communication.
Programming Languages
 Programming languages:
A language used to communicate with the computer
Examples: Visual Basic, C#, C++, Java

 Machine language (or machine code):


Instructions are written in 0s and 1s
Only way to communicate directly with the
computer

 Assembly languages:
A language which use mnemonics for instructions

 Mnemonics:
alphabetic abbreviations for instructions
Lempogo Forgor © 2011. All Rights
Reserved
Programming Languages
(continued)
 Assembler:
program that converts assembly language
instructions into machine code
 High-level languages:
Instructions resemble English language
Require an interpreter or compiler to convert
high-level language to machine code
 Interpreter:
translates high-level instructions line-by-line as
the program runs
 Compiler:
translates entire program into machine code
before running the program
Lempogo Forgor © 2011. All Rights
Reserved
Level of Programming
language
When choosing a programming language to
make a project, many different considerations
can be taken. First, one must decide what is
known as the level of the programming
language

The level determines how near to the


hardware the programming language is
Level of Programming
language
In the lower level languages, instructions are
written thinking directly on interfacing with
hardware

In "high level" ones a more abstract or


conceptual code is written.

Generally, high level code is more portable, that


means it can work in more different machines
with a smaller number of modifications, whereas
a low level language is limited by the peculiarities
of the hardware which it was written for
Level of Programming
language
A higher or lower level of programming is
to be chosen for a specific project
depending on the type of program that is
being developed

For example, when a hardware driver is


developed for an operating system
obviously a very low level is used for
programming. While when big applications
are developed usually a higher level is
chosen
Level of Programming
language
The C++ language is in a middle position,
since it can interact directly with the
hardware almost with no limitations, and
can as well abstract lower layers and work
like one of the most powerful high level
languages.
Characteristics of programming
languages

Function: A programming language is a


language used to write computer programs,
which involve a computer performing some
kind of computation or algorithm and possibly
control external devices such as printers,
robots,and so on.

Target: Programming languages differ from


natural languages in that natural languages
are only used for interaction between people,
while programming languages also allow
humans to communicate instructions to
Characteristics for constituting a
programming language
Constructs: Programming languages may
contain constructs for defining and
manipulating data structures or controlling
the flow of execution.

Expressive power: It classifies languages


by the computations they are capable of
expressing.
Properties of good programming
languages
The basic instructions appear in just about every
language:
input: Get data from the keyboard, a file, or some
other device.
output: Display data on the screen or send data to
a file or other device.
math: Perform basic mathematical operations like
addition and multiplication.
conditional execution: Check for certain
conditions and execute the appropriate sequence of
statements.
repetition: Perform some action repeatedly, usually
with some variation.
Compilers and interpreters
A compiler is a computer program that
transforms source code written in a
computer language (the source language)
into another computer language (the target
language,.

The name "compiler" is primarily used for


programs that translate source code from a
high-level programming language to a
lower level language.
Compilers and interpreters
In computer science, an interpreter
normally means a computer program that
executes, i.e. performs, instructions written
in a programming language.
An interpreter may be a program that either
 executes the source code directly
 translates source code into some efficient
intermediate representation (code) and
immediately executes this
 explicitly executes stored precompiled
code[1] made by a compiler which is part
of the interpreter system
A compiled language is a programming
Compiled versus interpreted languages

language whose implementations are


typically compilers (translators which
generate machine code from source code)

an interpreted language is a programming


language whose implementation often
takes the form of an interpreter
Compiled versus interpreted
languages
Higher-level programming languages are
generally divided for convenience into
compiled languages and interpreted
languages. However, in practice there is
rarely anything about a language that
requires it to be exclusively compiled, or
exclusively interpreted
Programming language Syntax
In computer science, the syntax of a
programming language is the set of rules
that define the combinations of symbols
that are considered to be syntactically
correct programs in that language.

 The syntax of a language defines its


surface form
Semantics
In computer science, where it is considered
as an application of mathematical logic,
semantics reflects the meaning of
programs or functions.

In this regard, semantics permits programs


to be separated into their syntactical part
(grammatical structure) and their semantic
part (meaning).
Semantics
Semantics for computer applications falls into three
categories:
 Operational semantics: The meaning of a construct is
specified by the computation it induces when it is executed
on a machine. In particular, it is of interest how the effect of
a computation is produced.

 Denotational semantics: Meanings are modelled by


mathematical objects that represent the effect of executing
the constructs. Thus only the effect is of interest, not how it
is obtained.

 Axiomatic semantics: Specific properties of the effect of


executing the constructs as expressed as assertions. Thus
there may be aspects of the executions that are ignored.
Syntax versus semantics
The syntax of a language describes the
form of a valid program, but does not
provide any information about the meaning
of the program or the results of executing
that program.
The meaning given to a combination of
symbols is handled by semantics
Not all syntactically correct programs are
semantically correct.
Syntax and semantics
Many syntactically correct programs are
nonetheless ill-formed, per the language's
rules; and may (depending on the language
specification and the soundness of the
implementation) result in an error on
translation or execution.
 In some cases, such programs may exhibit
undefined behavior.
Even when a program is well-defined within
a language, it may still have a meaning
that is not intended by the person who
wrote it.
Syntax and semantics
Using natural language as an example, it
may not be possible to assign a meaning to
a grammatically correct sentence or the
sentence may be false:
"Colorless green ideas sleep furiously." is
grammatically well-formed but has no
generally accepted meaning.
"John is a married bachelor." is
grammatically well-formed but expresses a
meaning that cannot be true.
How Do Programmers Solve
Problems?

You cannot solve a problem unless you


understand it

You cannot understand a problem


unless you analyze it

Most important components of any


problem are the problem’s output and
its input
Lempogo Forgor © 2011. All Rights
Reserved
Lempogo Forgor © 2011. All Rights
Reserved
Step 1 – Analyze the Problem
Identify output
What does the user want to see printed on
paper, displayed on the screen, or stored in a
file?

Identify input
What information will the computer need to
know to print, display, or store the output
items?

Analysis step is most difficult problem-solving


step
Lempogo Forgor © 2011. All Rights
Reserved
Step 1 – Analyze Problem ONE
As a Marketing Executive in
Zenith Bank, Kwadjo receives
an annual commission which is
calculated by multiplying his
annual sales by a commission
rate.

He therefore wants a program


Lempogo Forgor © 2011. All Rights
that will both calculate and
Reserved
Step 1 – Analyze Problem ONE
Input?
Annual Sales
Commission Rate

Output?
Annual Commission

Lempogo Forgor © 2011. All Rights


Reserved
Step 1 – Analyze Problem TWO
Mr. Jimah is Paid at the end
of every week. He is
expecting to receive a pay
raise next week. However,
he is not sure of the actual
percentage.

He therefore wants a


Lempogo Forgor © 2011. All Rights
program that will calculate
Reserved
Step 1 – Analyze Problem Two
Input?
Current Pay
Percentage of Raise

Output?
New Pay

Lempogo Forgor © 2011. All Rights


Reserved
Step 2 – Plan the Algorithm
Pseudo code
False code, not standardized
Cannot be understood by a computer
Used by programmers when planning
an algorithm

Flowchart
Uses standardized symbols to
visually depict an algorithm
Lempogo Forgor © 2011. All Rights
Reserved
Step 2 – Plan Algorithm One
 Input?
Annual Sales
Commission Rate
 Output?
Annual Commission

algorithm
1. enter the annual sales and commission
rate
2. calculate the annual commission by
multiplying the annual sales by the
commission rate Lempogo Forgor © 2011. All Rights
Reserved
Step 2 – Plan the Algorithm
(continued)
 Flowchart symbols
Oval: start/stop symbol
Parallelogram: input/output symbol
Rectangle: process symbol

 Flowlines
Connect symbols

 Processing item:
intermediate value that algorithm uses when
processing input into output
Lempogo Forgor © 2011. All Rights
Reserved
Lempogo Forgor © 2011. All Rights
Lempogo Forgor © 2011. All Rights
Reserved
Lempogo Forgor © 2011. All Rights
Reserved
Lempogo Forgor © 2011. All Rights
Reserved
Algorithm
Desk-checking (hand-tracing)
Programmer reviews algorithm while seated
at his or her desk

Valid data
Data that algorithm is expecting user to
enter

Invalid data
Data that algorithm is not expecting user to
enter
Lempogo Forgor © 2011. All Rights
Reserved
Lempogo Forgor © 2011. All Rights
Reserved
Lempogo Forgor © 2011. All Rights
Reserved
Algorithm
In mathematics, computing, linguistics, and related
subjects, an algorithm is an effective method for
solving a problem using a finite sequence of
instructions.

Algorithms are used for calculation, data processing,


and many other fields.

Each algorithm is a list of well-defined instructions for


completing a task.

Starting from an initial state, the instructions describe


a computation that proceeds through a well-defined
series of successive states, eventually terminating in a
final ending state.
Computer algorithms

In computer systems, an algorithm is


basically an instance of logic written in
software by software developers to be
effective for the intended "target"
computer(s), in order for the software on
the target machines to do something.
Computer algorithms
 An algorithm is merely the sequence of
steps taken to solve a problem.

The steps are normally


 sequence
 selection
iteration
 a case-type statement.
Pseudo code
Pseudo code is a compact and informal
high-level description of a computer
programming algorithm that uses the
structural conventions of a programming
language, but is intended for human
reading rather than machine reading.

Pseudo-code typically omits details that are


not essential for human understanding of
the algorithm, such as variable
declarations, system-specific code and
subroutines.
Pseudo- code
 The programming language is augmented with
natural language descriptions of the details, where
convenient, or with compact mathematical notation

 The purpose of using pseudo code is that it is easier


for humans to understand than conventional
programming language code

 It is commonly used in textbooks and scientific


publications that are documenting various algorithms,
and also in planning of computer program
development, for sketching out the structure of the
program before the actual coding takes place
Pseudo- code
No standard for pseudo code syntax exists,
as a program in pseudo code is not an
executable program.

 Pseudo code resembles, but should not be


confused with, skeleton programs including
dummy code, which can be compiled
without errors.

Flowcharts can be thought of as a graphical


alternative to pseudo code.
Pascal style pseudo-code example:
<variable> = <expression>

if <condition>
do stuff;
else
do other stuff;

while <condition>
do stuff;

for <variable> from <first value> to <last value> by <step>


do stuff with variable;

function <function name>(<arguments>)


do stuff with arguments;
return something;

<function name>(<arguments>) // Function call


More pseudo-code Examples

1.. If student's grade is greater than or


equal to 60
Print "passed"
else
Print "failed"
Principles of programming
Flowcharts
Flowcharts
A flowchart is a common type of chart, that
represents an algorithm or process,
showing the steps as boxes of various
kinds, and their order by connecting these
with arrows.

 Flowcharts are used in analyzing,


designing, documenting or managing a
process or program in various fields
Flowcharts
 There are many different types of flowcharts.

Sterneckert divides four more general types of flowcharts:

 Document flowcharts, showing a document flow through


system

 Data flowcharts, showing data flows in a system

 System flowcharts showing controls at a physical or


resource level

 Program flowchart, showing the controls in a program within


a system
Flowcharts symbols
A typical flowchart from older Computer Science
textbooks may have the following kinds of
symbols

Start and end symbols

Represented as circles, ovals or rounded


rectangles, usually containing the word "Start"
or "End", or another phrase signaling the start or
end of a process, such as "submit enquiry" or
"receive product".
Flowcharts
Arrows

Showing what's called "flow of control" in


computer science.

An arrow coming from one symbol and ending


at another symbol represents that control
passes to the symbol the arrow points to.
Flowcharts
Processing steps

Represented as rectangles. Examples: "Add


1 to X"; "replace identified part"; "save
changes" or similar.

Usually used to represent a process .


Flowcharts
Input/Output

Represented as a parallelogram. Examples:


Get X from the user; display X.

Used to express input or output


Flowcharts
 Conditional or decision

 Represented as a diamond (rhombus). These typically


contain a Yes/No question or True/False test.

 This symbol is unique in that it has two arrows coming out


of it, usually from the bottom point and right point, one
corresponding to Yes or True, and one corresponding to No
or False.

 The arrows should always be labeled.


Flowcharts
A number of other symbols that have less
universal currency, such as:
A Document represented as a rectangle
with a wavy base;

Describes input and output from a


document
A Manual input represented by
parallelogram, with the top irregularly
sloping up from left to rig

An example would be to signify data-entry


from a form;
A Manual operation represented by a
trapezoid with the longest parallel side at
the top, to represent an operation or
adjustment to process that can only be
made manually.
Flowcharts
A Data File represented by a cylinder.
Flowcharts examples
Flowchart examples
Flowcharts
Flowcharts may contain other symbols,
such as connectors, usually represented as
circles, to represent converging paths in
the flowchart.

Circles will have more than one arrow


coming into them but only one going out.
Some flowcharts may just have an arrow
point to another arrow instead. These are
useful to represent an iterative process
(what in Computer Science is called a loop).
Flow charts
 A loop may, for example, consist of a connector where
control first enters, processing steps, a conditional with
one arrow exiting the loop, and one going back to the
connector.

 Off-page connectors are often used to signify a


connection to a (part of another) process held on another
sheet or screen.

 It is important to remember to keep these connections


logical in order.

 All processes should flow from top to bottom and left to


right.
Principles of prgramming

variables
Variables And Data types
 In computer programming, a variable is an identifier
(usually a letter, word, or phrase) that is linked to a value
stored in the system's memory or an expression that can
be evaluated.

 For instance, a variable might be called "totalcount" and


contain a number.

 Variables are names given to the storage locations in the


memory of a computer and are used to hold data
temporarily.

For example, they can be used to store the result of some
calculation, or some text.
Variables
As the name suggests, the value of a
variable keeps on changing, that is, it is
variable.

The value of the variable is lost as soon as


a program terminates.

In imperative programming languages,


values can generally be accessed or
changed at any time.
Variables
Depending on the type system of a
programming language, variables may only
be able to store a specified data type (e.g.
integer or string).

Alternatively a data type may be associated


only with the current value, allowing a
single variable to store anything supported
by the programming language.
Working with variables
There are many types of data that we come
across in our daily life.
For example, we need to handle data such as
names, addresses, money, date, stock quotes,
statistics and more everyday.

 Similarly in C++ , we have to deal with all sorts


of of data, some can be mathematically
calculated while some are in the form of text or
other forms.

C++ divides data into different types so that it is


Fundamental data types

When programming, we store the variables in our


computer's memory, but the computer has to
know what kind of data we want to store in them,
since it is not going to occupy the same amount
of memory to store a simple number than to
store a single letter or a large number, and they
are not going to be interpreted the same way

The memory in our computers is organized in


bytes. A byte is the minimum amount of memory
that we can manage in C++.
Fundamental data types
Common data types may include:
integers,
floating-point numbers (decimals), and
alphanumeric (strings).

A data type also represents a constraint placed


upon the interpretation of data in a type system,
describing representation, interpretation and
structure of values or objects stored in computer
memory. The type system uses data type
information to check correctness of computer
programs that access or manipulate the data
Fundamental data types
A byte can store a relatively small amount
of data: one single character or a small
integer (generally an integer between 0
and 255).

In addition, the computer can manipulate


more complex data types that come from
grouping several bytes, such as long
numbers or non-integer numbers.
DATA TYPES
Name Description Size* Range*

signed: -128 to 127


char Character or small integer. 1byte
unsigned: 0 to 255

signed: -32768 to 32767


short int (short) Short Integer. 2bytes
unsigned: 0 to 65535
signed: -2147483648 to
int Integer. 4bytes 2147483647
unsigned: 0 to 4294967295
signed: -2147483648 to
long int (long) Long integer. 4bytes 2147483647
unsigned: 0 to 4294967295
Boolean value. It can take one of
bool 1byte true or false
two values: true or false.

float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)

Double precision floating point


double 8bytes +/- 1.7e +/- 308 (~15 digits)
number.

Long double precision floating


long double 8bytes +/- 1.7e +/- 308 (~15 digits)
point number.

wchar_t Wide character. 2 or 4 bytes 1 wide character


Identifiers
 In computer science, Identifiers (IDs) are lexical tokens
that name entities. The concept is analogous to that of
a "name." Identifiers are used extensively in virtually all
information processing systems.

 In computer languages, identifiers are tokens (also


called symbols) which name language entities. Some of
the kinds of entities an identifier might denote include
variables, types, labels, subroutines, and packages.

 Naming entities makes it possible to refer to them,


which is essential for any kind of symbolic processing.

.
Identifiers
A valid identifier is a sequence of one or
more letters, digits or underscore
characters (_).

Neither spaces nor punctuation marks or


symbols can be part of an identifier.

 Only letters, digits and single underscore


characters are valid.
In addition, variable identifiers always have
to begin with a letter
Identifiers
Another rule that you have to consider when
inventing your own identifiers is that they cannot
match any keyword of the programming language
nor your compiler's specific ones, which are
reserved keywords.

The C++ language is a "case sensitive" language.


That means that an identifier written in capital
letters is not equivalent to another one with the
same name but written in small letters.

Thus, for example, the RESULT variable is not the


same as the result variable or the Result variable.
Declaration of variables
 In order to use a variable in a program, we must first
declare it specifying which data type we want it to be.

 The syntax to declare a new variable is to write the


specifier of the desired data type (like int, bool,
float...)followed by a valid variable identifier.

 For example:

int a;

float mynumber;
Declaration of variables
These are two valid declarations of
variables.

1. 1. The first one declares a variable of type int with


the identifier a.
2. 2. The second one declares a variable of type float
with the identifier mynumber.

Once declared, the variables a and


mynumber can be used within the rest of
their scope in the program.
Declaration of variables
 If you are going to declare more than one variable of
the same type, you can declare all of them in a
single statement by separating their identifiers with
commas.
For example:
int a, b, c;
 This declares three variables (a, b and c), all of them of
type int, and has exactly the same meaning as:
 int a;
 int b;
 int c;
Declaration of variables
 The integer data types char, short, long and int can be
either signed or unsigned depending on the range of
numbers needed to be represented.

 Signed types can represent both positive and negative


values, whereas unsigned types can only represent positive
values (and zero).

 This can be specified by using either the specifier signed or


the specifier unsigned before the type name. For example:

unsigned short int NumberOfSisters;


signed int MyAccountBalance;
Declaration of variables
By default, if we do not specify either
signed or unsigned most compiler settings
will assume the type to be signed,
therefore instead of the second declaration
above we could have written:

int MyAccountBalance;
Scope of variables
All the variables that we intend to use in a
program must have been declared with its
type specifier in an earlier point in the code,
like we did in the previous code at the
beginning of the body of the function main
when we declared that a, b, and result were of
type int.

A variable can be either of global or local


scope.

A global variable is a variable declared in the


main body of the source code, outside all
functions, while a local variable is one
Scope of variables
Scope of variables
Global variables can be referred from
anywhere in the code, even inside
functions, whenever it is after its
declaration.

The scope of local variables is limited to the


block enclosed in braces ({}) where they
are declared.

For example, if they are declared at the


beginning of the body of a function (like in
function main) their scope is between its

You might also like