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

Ict 155 Intro To Programming

The document provides information on computer programming and related concepts. It is authored by R D Appiah and covers the following topics in 3 or fewer sentences: Programming involves writing instructions, called codes, to tell a computer how to solve problems. A computer program is a set of step-by-step instructions that tell a computer how to perform a task. Coding refers to entering commands that become a computer program. Programming languages are sets of predefined words and rules used to create instructions for computers. Examples of programming languages include Basic, Fortran, C, C++, Java, and Visual Basic. Programming languages can be categorized as low-level or high-level, by generation, or by programming paradigm.

Uploaded by

Ike Mensah
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

Ict 155 Intro To Programming

The document provides information on computer programming and related concepts. It is authored by R D Appiah and covers the following topics in 3 or fewer sentences: Programming involves writing instructions, called codes, to tell a computer how to solve problems. A computer program is a set of step-by-step instructions that tell a computer how to perform a task. Coding refers to entering commands that become a computer program. Programming languages are sets of predefined words and rules used to create instructions for computers. Examples of programming languages include Basic, Fortran, C, C++, Java, and Visual Basic. Programming languages can be categorized as low-level or high-level, by generation, or by programming paradigm.

Uploaded by

Ike Mensah
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 86

Instructor: R D Appiah

Computer Programming:
Programming is the art of writing lines of
instructions (sometimes referred to as codes)
that tell the computer how to solve a problem or
carry out a task.
Computer Programme:
A computer programme is a set of step-by-step
instructions that tell a computer how to solve a
problem or carry out a task.

R D Appiah
Coding:
Coding refers to entering a list of commands
that become a computer programme.

Some Characteristics of a Computer


Programme:
• A computer programme is typically stored as a
file and transferred into the RAM when needed.
• A computer programme can also be
embedded in computer hardware – e.g in ROM
chip.
R D Appiah
Programming Languages (PLs):
1. A programming language is a set of
predefined words that are combined into a
programme according to predefined rules (or
syntax).

2. A programming language is a set of


keywords and grammar rules designed for
creating instructions that a computer can
ultimately process or carry out.

R D Appiah
Examples of PLs:
Basic Fortran
C FORTH
C++ LISP
Pascal APL
Java Visual Basic
COBOL C# (pron. C sharp)
8088 Assembly Smalltalk

R D Appiah
Categories of PLs:
Criteria 1. Programming Languages can be
divided into two: Low-Level and High-Level
Languages.
Criteria 2. Programming Languages can
also be categorized by generations: First,
Second, Third, Forth and Fifth Generations.
Criteria 3. Programming Languages are
also categorized by paradigms: Procedural,
Object-Oriented, Declarative, Functional &
Event-Driven Paradigms.
R D Appiah
Low-Level Languages: These require a
programmer to write instructions for specific
computer hardware elements like the
processor, registers and the RAM. Instructions
here are written in 0s and 1s (i.e. in binary).
High-Level Languages: These make the
programming process easier by replacing
difficult commands in low-level programming
with easy-to-understand commands such as
PRINT and WRITE.
Also, multiple low-level commands are replaced
by a single high-level command.
R D Appiah
Generations of Languages

First Generation of PLs: These were the


first programming languages available to
programmers, where commands were/ are
represented as a series of 1s and 0s. Machine
languages are examples of First Generation
PLs.

R D Appiah
Second Generation of PLs: Here,
programmers use abbreviated command words
rather than 1s and 0s in machine languages (an
improvement over First Generation of PLs.
Assembly Languages are examples of Second
Generation of PLs.
Third Generation of PLs: This marked the
entry point into the high-level programming era.
They use easy-to-remember command words
for instructions. Examples include COBOL and
Fortran, which were used for business and
scientific applications.
R D Appiah
Forth Generation of PLs: In an attempt to come
out with high-level languages which more closely
resemble human languages or natural languages,
than the third generation languages do, scientist
developed the Forth-Generation of PLs. Example is
the SQL (Structured Query Language).

Fifth Generation of PLs: Researchers in Japan


started work on developing a programming
language that focuses on the use of facts and rules
to describe a problem – and the results were
classified by some experts as a Fifth Generation of
PLs. Example is Prolog.
R D Appiah
Programming Paradigm:

•This is the way in which a computer


language looks at the problem to be
solved.
• Some programming languages support a
single paradigm while others support
many paradigms (usually referred to as
multi-paradigm languages)

R D Appiah
Programming Paradigm Types:

Procedural Paradigm: This emphasizes


linear steps that provide the computer with
instructions on how to solve a problem or
carry out a task.

Examples include: BASIC, Pascal, C,


COBOL, FORTRAN, Ada.

R D Appiah
Object-Oriented & Event-Driven
Paradigm: These formulate programmes
as a series of objects and methods that
interact to perform a specific task.

Examples include: Smalltalk, C++, Java,


Visual Basic, C#.

R D Appiah
Declarative Paradigm: This focuses on
the use of facts and rules to describe a
problem.

Examples include: Prolog.

R D Appiah
Functional Paradigm: This emphasizes
the evaluation of expressions, called
functions.

Examples include: Lisp, Scheme, Haskell.

R D Appiah
TRANSLATION.
• Programmes today are normally written in one
of the high-level languages.
• To run the programme on a computer, the
programme needs to be translated into the
machine language of the computer (ie the
target computer/ platform/ machine) on which it
will run.
• The programme in a high-level language is
called the source programme or source
codes.
R D Appiah
• The translated programme in machine
language is called object programme.

METHODS OF TRANSLATION

The two methods used for translation are:

• Compilation and

• Interpretation.

R D Appiah
Compilation: A compiler normally
translates the entire source programme into the
object programme – before executing it.

Interpretation: Some computer languages


use an interpreter to translate the source
programme into the object programme.

Interpretation, thus, refers to the process of


translating each line of the source programme
into the corresponding line of the object
programme and executing the line.
R D Appiah
The Translation Process:
The translation process involves the
following stages/ phases:

Lexical Syntax Semantic Code


Analyzer Analyzer Analyzer Generator

Source Object
File File

R D Appiah
Lexical Analyzer:
A lexical analyzer reads the source codes,
symbol by symbol, and creates a list of tokens
in the source language.

A token is the smallest individual unit in any


programming language.

For example, the five symbols w, h, i, l, e are


read and grouped together as the token while
in the C, C++ and Java languages.
R D Appiah
Syntax Analyzer:

A syntax analyzer is the means by which a set


of tokens are used to form instructions.

For example, the tokens “x”, ”=”, ”0” are used to


create the assignment statement: “x = 0” in the
C language.

R D Appiah
Semantic Analyzer:

The semantic analyzer checks the sentences


created by the syntax analyzer to ensure that
they contain no ambiguity.

Most computer languages are unambiguous –


which means that this stage is either omitted in
a translator, or its duty is minimal.

R D Appiah
Code Generator:

After unambiguous instructions are created by


the semantic analyzer, each instruction is
converted to a set of machine language
instructions for the computer on which the
programme will run.

This task is accomplished by the Code


Generator.

R D Appiah
Algorithm:

Definition: An ordered set of unambiguous


steps that produces a result and terminates in a
finite time.
NOTE:
• Algorithms are generally designed so as to
be independent of programming languages.

• Algorithms usually accept input data and


create output data.
R D Appiah
Designing and Expressing an Algorithm:
Purpose: The purpose of an algorithm is to
provide a way to document one’s ideas for
programme design.
Steps:
The several ways in which an algorithm can be
expressed include:
• Structured English
• Pseudocodes and
• Flowcharts.
R D Appiah
Structured English:
This is a subset of the English language with a
limited selection of sentence structures that
reflect processing activities.

Pseudocodes:
Is an English-language-like representation of an
algorithm.

• There is no standard for pseudocode!


R D Appiah
• Some people use a lot of detail, others use
less.

• Some people incorporate their favourite codes


while others use syntax like those found in
programming languages.

This course emphasizes on the use of


algorithms and pseudocodes in describing and
expressing solutions to computer based
problems.

R D Appiah
Flowchart:
• Flowchart is a graphical representation of the
way a computer should progress from one
instruction to the next when it performs a task.

• Flowcharts are constructed from a set of


standardized symbols, called Flowchart
Symbols.

• Most algorithms can be represented using


flowcharts.
R D Appiah
Example1

Problem: To calculate the price of an item


in a particular state in the US, the following
criteria is employed: The state’s sales tax is 4%;
the city’s sales tax is 1.5%; for luxury item such
as cars over $50, 000 there is a 10% luxury tax.

Task: Design an algorithm that calculates


the sales tax and the price of a car sold in the
US state above.

R D Appiah
A sample algorithm is as follows:
1. Assume that:

• sellingPrice is the selling price of an item in the


state before any tax is imposed;
• salesTax represents the total tax imposed on an
item before being sold;
• stateSalesTax is the tax imposed by the state;
• citySalesTax is the tax collected by the city;
• luxuryTax represents the tax imposed if the item is
considered luxury;
• amountDue is the final selling price on an item in
the state.
R D Appiah
A sample algorithm:

2. Get the selling price of the item (before tax).

3. Determine whether the item is a luxury item


or not.

4. Find the state’s tax using the formula:


stateSalesTax = sellingPrice * (4/100)

5. Find the city’s tax using the formula:


citySalesTax = sellingPrice * (1.5/100)
R D Appiah
6. Find the luxury tax using the formula:
if( item is a luxury item)
luxuryTax = sellingPrice * (10/100)
otherwise
luxuryTax = 0
7. Find salesTax using the formula:
salesTax = stateSalesTax + citySalesTax
+
luxuryTax
8. Find amountDue using the formula:
amountDue = sellingPrice + salesTax
R D Appiah
Example2

Design an algorithm for the following programme:

Problem: A computer programme that


accepts as input given lengths expressed in feet
and inches. The programme should then
convert and output the lengths in centimetres.
Assume that the given lengths in feet and
inches are integers.

R D Appiah
A sample algorithm:
1. Let ft and inch be the components of the
length in feet and inches respectively.
2. Display: Prompt the user to enter the
distance in feet and inches as integers.

3. Input: Get the data – ft and inch, as the


input values.
4. Echo the input – in other words, output on
the screen what the programme read as
input, for certainty.
R D Appiah
5. Find the total length in inches using the
following formula:

total_inches = (12 * ft) + inch


6. Display: Output the total length in inches.

7. Convert the total length (in inches) to total


length (in centimetres) using the following
formula:

total_centimetres = total_inches * 2.54


R D Appiah
8. Display: Output the final length in
centimetres.
NOTE:
• In example 2, the degree of clarity of the
algorithm was enhanced through such
emphases on Input (where the programme is
expected to read in data) and Output
(through display, where the programme gives
Out information)
• These are to make the pseudocodes and the
algorithm as a whole unambiguous.
R D Appiah
Self Assessment 1: Write an algorithm that
takes as input, the length and breadth of a
rectangle and then calculates its area.
Self Assessment 2: Write an algorithm that
accepts as input, a numeric grade (integer) and
changes it to an appropriate letter grade.
Use the following grading system:
90 ≤ score ≤ 100 A
80 ≤ score ≤ 89 B
70 ≤ score ≤ 79 C
60 ≤ score ≤ 69 D
0 ≤ score ≤ 59 E
R D Appiah
Self Assessment 3

Scenario: 10 school children were tasked to fill a


container, that has a volume capacity of 200 litres, with
water. Each child was given a gallon of volume 2.5
litres. At any point in time, all the children could arrive
to
empty their gallons of water into the container, BUT
only in a one-after-the-other fashion.

Problem: Design an algorithm for a computer


programme, that monitors the container and then
announces to the children, the status of the container.
R D Appiah
Some Common Concepts

R D Appiah
Identifiers
Most computer programmes are made up of
featured data items and elements, usually
referred to as objects.
In order to uniquely recognize and control these
objects in programming settings, objects are
assigned names, through identifiers.
Identifiers, thus, allow a programmer to name
objects in a programme.
This also helps the compiler to keep track of
where objects are physically located.
R D Appiah
Data Types
A data type defines a set of values and a set of
operations that can be applied to those values.
The set of values for each type is known as the
domain for that particular data type.
At the highest level, most programming
languages define two categories of data types:

• Simple data types and

• Composite data types.


R D Appiah
Simple Data Types
A simple data type (sometimes called an
atomic type, fundamental type, scalar type,
or built-in type) is a data type that cannot be
further broken into smaller data types.
Several simple data types have been defined to
include:
An Integer type: Is a whole number, that is, a
number without a fractional part.
The range of values an integer can take
depends on the programming language. Some
Languages support several integer sizes.
R D Appiah
A real type: Is a number with a fractional part.
A character type: Is a symbol in the underlying
character set used by the language, for
example, ASCII or Unicode.

A boolean type: Is a type with only two values,


true or false.

R D Appiah
Composite Data Types
A composite data type is a set of elements in
which each element is a simple type or a
composite type.
Most languages define the following composite
types:
1. An array: A set of elements each
of the same type.
2. A record: A set of elements in
which the elements can be of different
types.
R D Appiah
Variables
Variables are names for memory locations.
Every memory location in a computer has a
unique address, called memory address;
which the computer uses internally.
Importance of Variables
1. Physically, the programmer does not know
the relative addresses of data items in
memory and through variables, the
programmer gets indirect access to the
computer’s memory resources.
R D Appiah
2. Secondly, a data item may occupy more than
one location in memory, which makes it
inconvenient for a programmer to control -
and through variables, such internal details
are hidden from the programmer.

We say that through variables, as


substitutes for memory addresses, a
programmer is freed to concentrate on
the level at which the programme
executes.

R D Appiah
Normally, variables are created and managed
so as to hold data items of a particular type.

Variable Declaration.
As part of the process of creating variables,
variable declaration alerts the computer that
a variable with a given name and type will be
used in the programme.
In response, the computer reserves the
required storage area and names it
accordingly.
R D Appiah
Example: The following illustrates the
declaration of the variables response, num
and result:-
1. In C, C++ and Java:
char response;
int num;
double result;

2. In Visual Basic:
Dim response As String
Dim num As Integer
Dim result As Double
R D Appiah
In the C, C++ and Java example, response is
declared as of type character; num of type
integer and result of type real

In the second example, response is declared


to be of the type String; num of the type
Integer and result to be of the type double-
precision floating point number.

In the examples above, response, num and


result are the names of the variables declared.

R D Appiah
Variable Initialization
This is the process whereby declared
variables are assigned values before they are
used in the programme.

For example, variables can be declared and


initialized at the same time:

char response = ‘g’;


int num = 98;
double result = 456.899;
R D Appiah
Constants
A constant, like a variable, is a named location
that can store a value, but the value cannot be
changed after it has been defined at the
beginning of the programme.

For instance, if there is the need to alter the


value of a constant used in a programme, we
only need to change just one line at the
beginning of the programme !

R D Appiah
Consider an example in a C, or C++
programme: The tax rate to be utilized in a
programme can be defined at the beginning
and used during the programme.
Illustration:
const float taxRate = 2.09;
. . .
cost = price * taxRate;
Note also that a constant, like a variable, has a
type and must be defined when the constant is
declared.
R D Appiah
Input and Output
Input:
Data is input by either a statement or a
predefined function.

For example, a function called scanf is used in


the C language to read data from the keyboard,
formats it, and stores it in a variable, as follows:

scanf(“%d”, &num)
R D Appiah
• When the programme encounters this
instruction, it waits for the user to type an
integer.

•The programme then stores the value in the


variable called num.
Output:
Data is also output by either a statement or a
predefined function.
For example, the C language uses a function
called printf to display strings on the monitor.
R D Appiah
The following example displays the value
contained in the variable num, at the end of a
string:
printf(“The Value of the Number is: %d”, num);

Expressions
Operator:
An operator is a language-specific token that
requires an action to be taken.
R D Appiah
Examples include:
Arithmetic Operators in C, C++ and Java
Operato Definition Example
r
+ Addition 3+4
- Subtraction 4-5
* Multiplication Num * 4
/ Division Sum/count
% Modulo Operator 7%2
++ Increment (adds 1 to the value) Count ++
-- Decrement (subtract 1 from the Count --
R D Appiah value)
Relational Operators in C, C++ and Java:
They are used to compare data to see if a
value is greater than, less than, or equal to
another.
Operato Definition Example
r
< Less than Num1 < 4
<= Less than or equal to Num 1 <= 4
> Greater than Num 2 > 8
>= Greater than or equal to Num2 >= 8
== Equal to Num1 == num2
!= Not equal to Count != num2
R D Appiah
Logical Operators:
They combine Boolean values (true or false) to
get a new value.
The C language uses the following three
logical operators:

Operat Definition Example


or
! Not ! (num1 < num2)
&& And (num1 < 5) && (num2>10)
|| Or (num1 < 5) || (num2>10)
R D Appiah
Statements
• A statement causes an action to be
performed by the programme.
• Usually, a statement translates directly into
one or more executable computer instructions.

Many languages define several types of


statements, such as:

• Assignment statements
• Compound statements
• Control statements
R D Appiah
Assignment Statements
An assignment statement assigns a value to a
variable.
We can also say that an assignment statement
stores the value in the variable, which has
already been created in the declaration section
of a programme
In algorithms, we can use the symbol
to define assignment.

R D Appiah
Most programming languages like C, C++, and
Java use the symbol = for assignment.
Other programming languages, like Ada and
Pascal, the symbol := is used for assignment.
The following illustrates the declaration
followed by assignment statements involving
variables and operators in C and C++:
int count, x, y;
char ch;

ch = ‘Y’;
count = x + 34;
R D Appiah
count = (x + y)/10;
Compound Statements
In programming, a compound statement is a
unit of code consisting of zero or more
statements.
A compound statement is also known as a
block.
A compound statement allows a group of
statements to be treated as a single unit.
Normally, a compound statement consist of an
opening brace, a statement section,
followed by a closing brace.
R D Appiah
Illustration:

if( x == 1)
{
x++;
y = x + 24;
}

The portion of the construct above, in bold, is


a compound statement.

R D Appiah
Control Statements
Control statements are statements that specify
the sequence in which a programme is
executed.
Most programming languages have three
types of control statements:
1. Sequence Control Statement

2. Selection Control Statement

3. Repetition Control Statement


R D Appiah
Sequence Control Statements
These are used to change the order in which
instructions are carried out by directing the
computer to execute an instruction elsewhere
in the programme.
Illustrative Example:

Print “This is the first line.”


GOTO mySkip
Print “This is the second line.”
mySkip: Print “All Done !”
End
R D Appiah
In the previous example, by executing the
GOTO command, the computer is directed to
a different part of the programme, labelled
mySkip.

The example can be Illustrated using a


flowchart presentation, as shown on the next
slide:

R D Appiah
Start

Print “This is the first line”

GOTO mySkip

Print “This is the first line”

mySkip

Print “All Done !”

End

R D Appiah
Selection Control Statements
These are used to tell the computer what to
do, based on whether a condition is TRUE
or FALSE.
A simple example of a selection control
structure is the IF … THEN … ELSE
command.
Example: Consider the following programme
construct, in which a selection control is
used to test a number – and based on the
outcome, a particular output statement is
printed on the screen:
R D Appiah
Input “Enter a number from 1 to 40: ”; num
If num > 10 Then
Print “The number is greater than 10.”
Else
Print “The number is 10 or less.”
End

The following diagram illustrates how a


computer follows instructions in a selection
decision structure, as depicted in the above
example:
R D Appiah
Start

Input a number between 1 and 40

NO Is
YES
number
> 10

Print “The number is Print “The number is


10 or less” greater than 10”

End
R D Appiah
Repetition Control Statements
These are used to direct the computer to
repeat one or more instructions until a
certain condition is met or satisfied.
The section of code that repeats is usually
referred to as a loop or an iteration.

Some of the most widely used repetition


commands are:
• The FOR … NEXT loop
• The DO … UNTIL loop and
• WHILE … WEND loop
R D Appiah
The keywords FOR, DO, or WHILE marks the
beginning of a loop
The keywords NEXT, UNTIL, or WEND marks
the end of a loop.
To execute a loop, the computer repeats one
or more commands until some condition
indicates that the loop should stop.
The following diagram illustrates how a
computer executes a series of commands in a
repetition structure or in a loop:

R D Appiah
Start Illustrating a loop in
programming

START LOOP

Print “WELCOME HOME”

NO LOOP
DONE ?

YES

R D Appiah
End
Example1 using the FOR … NEXT Loop

For N =1 To 10
Print “There is no place like home”
Next N
End
Above is a simple programme in basic using
the For … Next command to print the
message “There is no place like home” ten
times.
R D Appiah
Example2 using the FOR … NEXT Loop

for(x=1; x ≤ 10; x++)


printf(“There is no place like home”);

Example2 illustrates how the same task can


be accomplished in the C programming
language. Thus, executing the above loop in C
will print out ten times, the statement “There is
no place like home”
R D Appiah
One very important application of loops is in
the handling and processing of a special
variable type called an array.
Arrays
• These are special variable types used to hold
or store a group of related data items all of
the same type.
• Each of the data items is called an element
of the array.
Application(s) of arrays:
Arrays are very useful in many situations; and
the following describe some of them:
R D Appiah
1. In sorting a list of items either in an
ascending or descending order.
2. In processing a long list of numbers, as in
performing such operations like summing
up the numbers, searching for the
maximum and minimum numbers in a list.
3. In accepting a list of data items that
requires further processing, especially
where such processing may involve all such
data items at the same time.
4. In finding an average score of a set of data;
as in student scores, temperatures, etc.
R D Appiah
Self Assessment:

List 10 different scenarios, in real life, where


you think the use of an array will be
Appropriate and beneficial.
Array Name and Array Elements
Just as in other ordinary variables, arrays must
be uniquely identified in a programme.

Arrays, thus, are given names which are


usually specified during their declarations.
R D Appiah
For example, the following illustrates the
declaration of an array in Visual Basic:
Dim scores(15)

Dim scores(15) As Integer


The first declaration creates an array called
scores; and it is big enough to hold up to 15
elements.
Here, the array scores can be used to store
data of any type.
R D Appiah
In the second declaration, the array scores is
specified to hold data of type integer.
We can refer to the elements in the array as
the first element, second element, and so
forth until we get to the last element.
Normally, an element is represented by the
name of the array followed by a number
enclosed in a pair of square brackets.
The number (referred to as an index) within
the square brackets is used to indicate the
position of an element within the array.
R D Appiah
For example:
scores(0) refers to the first element, scores(7)
refers to the eighth element, and on.
Assigning Values To Array’s Elements
We can have the following statements, all of
which assign values to the indicated elements
within the array scores:

scores(0) = 23
scores(4) = 90
scores(10) = 44
R D Appiah
Subprogrammes
Generally speaking, this is a very important
concept more in procedure-oriented
programming paradigms than it is in object-
oriented programming paradigms.
In procedure-oriented programming, the main
computer programme is divided into “smaller”
programmes, referred to as subprogrammes.
Each subprogramme is so designed to handle
or to solve a specific problem – which
represents a well-defined task.
R D Appiah
Thus, a subprogramme is considered to be a
smaller programme within a bigger/ main
programme, to perform a specific task.
Some advantages of subprogrammes:
1. They make programming easier
2. They help in making a programme more
organized and structured
3. They help programmers to avoid repeating
writing same source codes over and over
again.
4. Also, detecting errors in a subprogramme is
easier than in the main programme.
R D Appiah
Recursion
This is a programming concept and technique
used mostly in advanced programming.
Recursion occurs in a computer programme if
the programme calls itself within its own
structure or definition in handling a task.

A classic example is the calculation of the


factorial of a number.
E.g.
4! = 4*3*2*1
R D Appiah
To solve the previous example recursively with
a computer programme, we will have the
following:
4! = 4 * 3!
From a closer look, one can say that “in finding
a value for 4 factorial, the computer calls on 3
factorial.
In other words, we have a programme called
factorial on the left-hand side of the
assignment statement(represented by !)
calling itself on the right-hand side
of the assignment statement.
R D Appiah
Thus, recursion occurs whenever a programme
calls itself within the same expression or
assignment statement.

R D Appiah

You might also like