Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Chapter 2 - Introduction to Programming (1)

Chapter Two of 'Introduction to Programming' covers the fundamentals of computer programming, including definitions of programming languages, types of programming languages, and programming paradigms. It outlines essential skills needed to be a programmer, reasons to study programming, and categorizes programming languages into machine, assembly, and high-level languages. Additionally, it discusses various programming paradigms such as imperative, procedural, object-oriented, and declarative programming.

Uploaded by

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

Chapter 2 - Introduction to Programming (1)

Chapter Two of 'Introduction to Programming' covers the fundamentals of computer programming, including definitions of programming languages, types of programming languages, and programming paradigms. It outlines essential skills needed to be a programmer, reasons to study programming, and categorizes programming languages into machine, assembly, and high-level languages. Additionally, it discusses various programming paradigms such as imperative, procedural, object-oriented, and declarative programming.

Uploaded by

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

Introduction to Programming 2016

Chapter Two

Introduction to Programming

Objectives: Software is written using a programming language. There are several programming
languages from which programmers could choose one. Software development has different phases that
could follow a certain paradigm.

At the end of this chapter, students should be able to:

• explain computer programming

• explain programming language

• identify the various types of programming languages

• identify the major programming paradigms

• identify the various software development life cycle models

What is computer programming?

In essence, the word programming refers to giving directions for the computer to accomplish a
task. Computer programming (often shortened to programming or coding) is the process of writing,
testing, debugging, and maintaining the source code of computer programs [1]. Programming is a skill
that can be acquired by a computer professional that gives him/her the knowledge of making the
computer perform the required operation or task [2, 3]. Writing computer programs means writing
instructions that will make the computer follow and run a program based on those instructions. Each
instruction is relatively simple, yet because of the computer's speed, it can run millions of instructions in a
second.

Programming Language: is a set of different categories of written symbols that instruct computer
hardware to perform specified operations required by the designer.

1
Introduction to Programming 2016
What Skills Do We Need to Be a Programmer?

For someone to be a programmer, in addition to basic skills in computer, he/she needs to have the
following major skills:

• Programming Language Skill: knowing one or more programming languages to talk to the computer
and instruct the machine to perform a task.

• Problem Solving Skill: skills on how to solve the real-world problem and represent the solution in an
understandable format.

• Algorithm Development Skill: the skill of coming up with the sequence of a simple and human-
understandable set of instructions showing the step of solving the problem. Those set of steps should not
be dependent on any programming language or machine.

In every programming language, there are sets of rules that govern the symbols to be used in the
programming language. This set of rules determines how the programmer can make the computer
hardware to perform a specific operation. These sets of rules are called syntax.

Reasons to Study Programming

• Increased capacity to express programming concepts

• Increased ability to learn new languages

• Understand the significance of implementation

• Increased ability to design new languages

• Mastering different programming paradigms

• To solve problem

2
Introduction to Programming 2016

What is a Programming Language?

Programming Language is a set of different categories of written symbols that instruct computer
hardware to perform specified operations required by the designer. Programming Language can be
dividing into three major categories.

a. Machine Languages

Within a computer, all data is represented by microscopic electronic switches that can be either off or on.
The off switch is designated by a 0, and the on switch is designated by a1. Because computers can
understand only these on and off switches, the first programmers had to write the program instructions
using nothing but combinations of 0s and 1s. For example, a program might contain the instruction 00101
10001 10000. Instructions written in 0s and 1s are called machine language or machine code. The
machine languages (each type of machine has its language) represent the only way to communicate
directly with the computer. As you can imagine, programming in machine language is very tedious and
error-prone and requires highly trained programmers.

The advantage of machine language is the fact that it is translation free and high speed and while its
disadvantage is that machine language is machine-dependent, complex, and error-prone.

b. Assembly Languages

Assembly language is close to a one-to-one correspondence between symbolic instruction and executable
machine code and was created to use letters instead of 0s and 1s. For example, most assembly languages
use the mnemonic ADD to represent an add operation and the mnemonic MUL to represent a multiply
operation. An example of an instruction written in an assembly language is ADD BX, AX. Programs
written in an assembly language require an assembler, which also is a program that converts the assembly
instructions into machine code the 0s and 1s the computer can understand.

3
Introduction to Programming 2016

The advantage of assembly language is that it is easy to understand and use, less error-prone. Its
disadvantages are its machine dependency and harder to learn natures.

c. High-Level Languages

High-level languages represent the next major development in programming languages. High-level
languages are a vast improvement over machine and assembly languages because they allow the
programmer to use instructions that more closely resemble the English language. An example of an
instruction written in a high-level language is,

grossPay = hours * rate.

Besides, high-level languages are more machine-independent than are machine and assembly languages.
As a result, programs written in a high-level language can be used in many different types of computers.
Programs are written in a high-level language usually requires a compiler, which also is a program, to
convert the English-like instructions into the 0s and 1s the computer can understand.

Advantages of high-level language are its readability, machine independence, easy debugging, easier
maintenance, and low development cost nature. Its disadvantages, on the other hand, are its poor control
in hardware and less efficiency

Generation of Programming Language

Programming languages are categorized into five generations, namely 1st, 2nd, 3rd, 4th, and

5th generation languages.

• These programming languages can also be categorized into two broad categories:

Low level and high-level languages.

• Low-level languages are machine specific or dependent.

• High-level languages like COBOL and BASIC are machine independent and can run on a variety of
computers.

4
Introduction to Programming 2016

• From the five categories of programming languages, first- and second-generation languages are low-
level languages and the remaining categories are high-level programming languages.

• The higher the level of a language, the easier it is to understand and use by programmers.

• Languages after the fourth generation are referred to as a very high-level language.

1. First Generation (Machine languages, 1940’s)


• Difficult to write applications with.

• Dependent on machine languages of the specific computer being used.

• Machine languages allow the programmer to interact directly with the hardware, and it can be
executed by the computer without the need for a translator.

• Is more powerful in utilizing the resources of the computer.

• They execute very quickly and use memory very efficiently.

2. Second Generation (Assembly languages, early 1950’s)


• Uses symbolic names for operations and storage locations.

• A system program called an assembler translates a program written in assembly language


to machine language.

• Programs written in assembly language are not portable. That is different computer
architectures have their machine and assembly languages.

• They are highly used in system software development.

3. Third Generation (High-level languages, 1950’s to 1970s)


• Uses English like instructions and mathematicians were able to define variables with
statements such as Z = A + B

• Such languages are much easier to use than assembly language.

• Programs written in high-level languages need

5
Introduction to Programming 2016

• The use of common words (reserved words) within instructions makes it easier to learn.

• All third-generation programming languages are procedural languages.

• In procedural languages, the programmer is expected to specify what is required and how to perform
it.

4. Fourth Generation (since the late 1970s)


• Have a simple, English language like syntax rules; commonly used to access databases.

• Fourth-generation languages have a minimum number of syntax rules. This saves time and free
professional programmers for more complex tasks.

• Some examples of 4GL are structured query languages (SQL), report generators, application
generators, and graphics languages.

5. Fifth Generation (1990’s)


• These are used in artificial intelligence (AI) and expert systems; also used for accessing databases.

• 5GLs are “natural” languages whose instruction closely resembles human speech.

• 5GLs require very powerful hardware and software because of the complexity involved in
interpreting commands in human language.
Type of Programming Paradigms

Paradigm can also be termed as method to solve some problem or do some task. A programming
paradigm is the process of writing code in an organized manner based on some specific
methodology/method using programming language. Each language is used as a tool for solving a problem
and has its own unique style that uses a programming paradigm. It is an approach to solve problem using
some programming language or also we can say it is a method to solve a problem using tools and
techniques that are available to us following some approach. There are lots for programming language
that are known but all of them need to follow some strategy when they are implemented and this
methodology/strategy is paradigms. Apart from varieties of programming language there are lots of
paradigms to fulfill each and every demand. They are discussed below:

6
Introduction to Programming 2016

1. Imperative programming paradigm: It is one of the oldest programming paradigms. When you go
shopping, you usually write down the name of the things you need to buy before reaching the mall.
Similarly, this paradigm consists of a list of programming statements.

They are first executed, and then the results are stored in a variable. It is more of a line-by-line instruction
given to the computer.

It performs step by step task by changing state. The main focus of this paradigm is on how to achieve the
goal. The paradigm consists of several statements and after execution of all the result is stored. Let we
understand imperative programming using a C++ program that gives us factorial of a number.

Example:

#include<iostream>

using namespace std;

int main(){

int fact=1;

fact*=1;

fact*=2;

fact*=3;

fact*=4;

fact*=5;

7
Introduction to Programming 2016
fact*=6;

fact*=7;

fact*=8;

cout<<"Factorial of 8 is: "<<fact;

return 0;

Output:

In this example, we give a line-by-line task to perform by the computer with proper instructions. This
type of paradigm takes the order of the steps into consideration because different arrangements can
produce different results.

Advantages:

Very simple to implement

It contains loops, variables etc.

Disadvantage:

Complex problem cannot be solved

Less efficient and less productive

Parallel programming is not possible

Examples of Imperative programming paradigm:

C: developed by Dennis Ritchie and Ken Thompson

8
Introduction to Programming 2016
Fortran: developed by John Backus for IBM

Basic: developed by John G Kemeny and Thomas E Kurtz

// average of five number in C

Int marks[5] = { 12, 32, 45, 13, 19 } int sum = 0;

Float average = 0.0;

for(int i = 0; i < 5; i++) {

sum = sum + marks[i];

average = sum / 5;

Imperative programming is divided into three broad categories: Procedural, OOP and parallel processing.
These paradigms are as follows:

 Procedural programming paradigm – This paradigm emphasizes on procedure in terms of under


lying machine model. There is no difference in between procedural and imperative approach. It
has the ability to reuse the code. This programming paradigm follows imperative programming
with procedural calls. These calls direct the system to perform the required tasks. Each procedure
or so-called function can have multiple commands to be executed. The function, once defined,
can be called as many times as needed to perform the same operation. Procedural programming is
considered the best for people starting to learn to code. Beginners can start with procedural
programming as it is simple, efficient, requires less memory, and is easier to keep track of control
flow. Factorial of n number is the best example of procedural programming paradigm.
Examples of Procedural programming paradigm:

C: developed by Dennis Ritchie and Ken Thompson

C++ : developed by Bjarne Stroustrup

Java : developed by James Gosling at Sun Microsystems

9
Introduction to Programming 2016
ColdFusion : developed by J J Allaire

Pascal : developed by Niklaus Wirth

C++

#include <iostream>

usingnamespace std;

int main()

int i, fact = 1, num;

cout <<"Enter any Number: ";

cin >> number;

for(i = 1; i <= num; i++) {

fact = fact * i;

cout <<"Factorial of "<< num <<" is: "<< fact << endl;

return0;

Then comes OOP,

 Object oriented programming – This is the most widely used and most popular programming
paradigm. Class, Abstraction, Encapsulation, Inheritance, and Polymorphism form the backbone
of Object-Oriented Programming (OOP).The program is written in this paradigm as a collection
of classes and object which are meant for communication. The smallest and basic entity is object
and all kind of computation is performed on the objects only. Objects can have data associated
with them called attributes and actions they can perform using methods. More emphasis is on
data rather procedure. It can handle almost all kind of real life problems which are today in
scenario.

10
Introduction to Programming 2016
Advantages:

Data security

Inheritance

Code reusability

Flexible and abstraction is also present

Examples of Object Oriented programming paradigm:

Simula : first OOP language

Java : developed by James Gosling at Sun Microsystems

C++ : developed by Bjarne Stroustrup

Objective-C : designed by Brad Cox

Visual Basic .NET : developed by Microsoft

Python : developed by Guido van Rossum

Ruby : developed by Yukihiro Matsumoto

Smalltalk : developed by Alan Kay, Dan Ingalls, Adele Goldberg

C++

// C++ program for the above approach

#include <bits/stdc++.h>

usingnamespace std;

// Class Signup

class Signup {

int userid;

11
Introduction to Programming 2016
string name;

string emailid;

char sex;

long mob;

public:

// Function to create and object using

// the parameters

void create(int userid, string name, string emailid,

char sex, long mob)

cout <<"Welcome to GeeksforGeeks\nLets create "

"your account\n";

this->userid = 132;

this->name = "Radha";

this->emailid = "radha.89@gmail.com";

this->sex = 'F';

this->mob = 900558981;

cout <<"your account has been created"<< endl;

};

12
Introduction to Programming 2016
// Driver Cpde

int main()

cout <<"GfG!"<< endl;

// Creating Objects

Signup s1;

s1.create(22, "riya", "riya2@gmail.com", 'F', 89002);

return0;

Java

Python3

C#

JavaScript

Output

GfG!

Welcome to GeeksforGeeks

Lets create your account

your account has been created

 Parallel processing approach – Parallel processing is the processing of program instructions by


dividing them among multiple processors. A parallel processing system posses many numbers of
processor with the objective of running a program in less time by dividing them. This approach
seems to be like divide and conquer. Examples are NESL (one of the oldest one) and C/C++ also
supports because of some library function.

13
Introduction to Programming 2016
2. Declarative programming paradigm: It is divided as Logic, Functional, and Database. In computer
science the declarative programming is a style of building programs that expresses logic of computation
without talking about its control flow. The programmer must specify what the program must accomplish
but need not specify how it must be implemented. The focus is on what needs to be done rather how it
should be done basically emphasizing on what code is actually doing. It just declares the result we want
rather how it has be produced. This is the only difference between imperative (how to do) and declarative
(what to do) programming paradigms. Getting into deeper we would see logic, functional and database.

 Logic programming paradigms – It can be termed as abstract model of computation. It would


solve logical problems like puzzles, series etc. The logic programming paradigm uses logic-based
statements to convey facts and rules. Logical inferences are made of instructions or logic
statements to do computation. Atomic statements are built using these predicate statements. In
logic programming we have a knowledge base which we know before and along with the
question and knowledge base which is given to machine, it produces result. In normal
programming languages, such concept of knowledge base is not available but while using the
concept of artificial intelligence, machine learning we have some models like Perception model
which is using the same mechanism. In logical programming the main emphasize is on
knowledge base and the problem. The execution of the program is very much like proof of
mathematical statement, e.g., Prolog
Let us take the statement, “abebe is human. All humans are animals . So abebe is an animal”.

So in prolog code:-

Human(abebe)
Animal(X) :-human(X)

To test the program, we can ask if Abebe is an animal.

?- animal(abebe)

 Functional programming paradigms– this paradigm is built upon mathematical functions. It


solves problems using these mathematical functions as program components. This programming
is used while working with concurrency and parallelism. The functional programming paradigm
has its roots in mathematics and it is language independent. The key principle of this paradigm is
the execution of series of mathematical functions. The central model for the abstraction is the
function which is meant for some specific computation and not the data structure. Data are

14
Introduction to Programming 2016
loosely coupled to functions. The function hides their implementation. Function can be replaced
with their values without changing the meaning of the program. Some of the languages like perl,
JavaScript mostly uses this paradigm.
Examples of Functional programming paradigm:

JavaScript : developed by Brendan Eich

Haskell : developed by Lennart Augustsson, Dave Barton

Scala : developed by Martin Odersky

Erlang : developed by Joe Armstrong, Robert Virding

Lisp : developed by John Mccarthy

ML : developed by Robin Milner

Clojure : developed by Rich Hickey

The next kind of approach is of Database.

 Database/Data driven programming approach – This programming methodology is based on


data and its movement. Program statements are defined by data rather than hard-coding a series
of steps. A database program is the heart of a business information system and provides file
creation, data entry, update, query and reporting functions. There are several programming
languages that are developed mostly for database application. For example SQL. It is applied to
streams of structured data, for filtering, transforming, aggregating (such as computing statistics),
or calling other programs. So it has its own wide application.
CREATE DATABASE databaseAddress;

CREATE TABLE Addr (

PersonID int,

LastName varchar(200),

FirstName varchar(200),

Address varchar(200),

15
Introduction to Programming 2016
City varchar(200),

State varchar(200)

);

Computational Problems

Computational problems are problems that can be solved step-by-step with a computer. These problems
usually have well-defined input, constraints, and conditions that output must satisfy. Below is a brief
explanation of the common computational problems.

A. Decision Problems

These are types of problems where the solution is a yes or a no answer. For example, given a natural
number N, the problem is `N` even? is a decision problem. Given a natural number N, the following are
typical examples of decision problem:

• Is N a prime number?

• Is N greater than 97?

• Is 5 a factor of N?

Some decision problems take more steps to solve than other decision problems. For instance, given a
natural number n, the decision problem “is N a prime number?” takes more steps than the computational
problem of “is Nan odd number?” To check if a natural number is odd or not, it is enough just to check
if the modulus of the give number and 2 (N%2) is 1 or not. If N%2 is 1, N is odd. Checking whether a
given natural number is prime or not, on the other hand, needs additional steps. A natural number N is
said to be a prime number if the number has only two factors, that is, its factors are 1 and N (the number
itself). Thus, the primarily test needs to check all the natural numbers in the range [2, N-1] if one of the
numbers in the range is a factor of the number. If one natural number is found, then the natural number N
is not a prime number.

B. Search Problem

These are types of computational problems where the solution of the problem consists of one or more
values that satisfy a given condition. For example, given a list of natural numbers, identifying the
maximum of the list could be a search problem.

16
Introduction to Programming 2016
C. Counting Problems

Counting problems are those where the answer is the number of solutions to a search problem

D. Optimization problem’s

The optimization problem is one where the solution is the "best" possible solution, where the "best" can
be defined differently. For instance, we may want to compute the fastest route from one location to
another.

Questions such as "what is the meaning of life?" "Do I look good in this outfit?" are not computational
problems because they do not have well-defined input, constraints, and conditions that the output must
satisfy.

Problem solving Techniques and Algorithm

Computer solves varieties of problems that can be expressed in a finite number of steps leading to a
precisely defined goal by writing different programs. A program is not needed only to solve a problem
but also it should be reliable, (maintainable) portable and efficient. In computer programming two facts
are given more weight:

 The first part focuses on defining the problem and logical procedures to follow in solving it.
 The second introduces the means by which programmers communicate those procedures to the
computer system so that it can be executed.
There are system analysis and design tools, particularly flowchart and structure chart, that can be used to
define the problem in terms of the steps to its solution. The programmer uses programming language to
communicate the logic of the solution to the computer. Before a program is written, the programmer must
clearly understand what data are to be used, the desired result, and the procedure to be used to produce
the result. The procedure, or solution, selected is referred to as an algorithm.

An algorithm is defined as a step-by-step sequence of instructions that must terminate and describe how
the data is to be processed to produce the desired outputs. Simply, algorithm is a sequence of instructions.
Algorithms are a fundamental part of computing. There are three commonly used tools to help to
document program logic (the algorithm). These are flowcharts, structured chart, and Pseudo code. We
will use the three methods here. Generally, flowcharts work well for small problems but Pseudo code is
used for larger problems.

17
Introduction to Programming 2016

Pseudo code

Pseudo code (derived from pseudo and code) is a compact and informal high-level description of a
computer algorithm that uses the structural conventions of programming languages, but typically omits
details such as subroutines, variables declarations and system-specific syntax. 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 may be easier for humans to
read than conventional programming languages, and that it may be a compact and environment-
independent generic description of the key principles of an algorithm. No standard for pseudo code
syntax exists, as a program in pseudo code is not an executable program. As the name suggests, pseudo
code generally does not actually obey the syntax rules of any particular language; there is no systematic
standard form, although any particular writer will generally borrow the appearance of a particular
language.

The programming process is a complicated one. You must first understand the program specifications, of
course, Then you need to organize your thoughts and create the program. This is a difficult task when the
program is not trivial (i.e. easy). You must break the main tasks that must be accomplished into smaller
ones in order to be able to eventually write fully developed code. Writing pseudo code will save you time
later during the construction & testing phase of a program's development.

Pseudo-code Structure

Input: READ, OBTAIN, GET and PROMPT

Output: PRINT, DISPLAY, and SHOW

Compute: COMPUTE, CALCULATE, and DETERMINE

Initialize: SET and INTIALIZE

Add one: INCREMENT

Example 1:

Original Program Specification: Write a program that obtains two integer numbers from the user
and displays the sum of the two numbers.

18
Introduction to Programming 2016
Pseudo code 1:

1. Prompt the user to enter the first integer

2. Prompt the user to enter a second integer

3. Compute the sum of the two user inputs

4. Display an output prompt that shows the answer as the sum

Pseudo code 2:

1. Read the values of the two numbers (A and B)

19
Introduction to Programming 2016

2. Compute the sum of A and B

3. Set the sum to C

4. Display the result (C)

Example 2:

Original program specification: Write a program that obtains a natural number from the user and display
the sum of all the digits of the number.

Pseudo code:

1. Start

2. Prompt the user to enter a natural number, N

3. Set sum to 0

4. Check if N is greater than 0

4.1. If N is greater than 0

4.1.1. Increment the sum by N modulo 10

4.1.2. Set N to N/10

4.1.3. Repeat step 4

4.2. If N is not greater than 0

4.2.1. Display the sum result

4.2.2. Terminate

Example 3:

Original Program Specification: Write a program that takes a natural number say N and displays the first
N natural numbers.

Pseudo-code:

20
Introduction to Programming 2016
1. Start

2. Read the number of natural numbers, N to display

3. Set the first natural number, I to 1

4. If I < N

4.1. Print I

4.2. Increment I by 1

21
Introduction to Programming 2016
4.3.Repeat step 4

5. Else

5.1.Stop

Example 4:

Original Program Specification: Write a pseudo program that checks whether a given natural number
is negative or not.

Pseudo-code:

1. Read a number x

2. If x is less than zero write a message negative

3. End If

4. Else write a message not negative

Example 5:

Original Program Specification: Write a program that computes the following sum:

Sum = 1+2+3+…. + 50

Pseudo-code:

1. Initialize sum to 0 and counter to 1

2. If the counter is less than or equal to 50

2.1. Add counter to sum

2.2. Increase counter by 1

2.3. Repeat step 2

3. Else

3.1. Display sum

3.2. Exit

22
Introduction to Programming 2016
Example 6:

Original program specification: write a program that takes two natural numbers from the user and
computes GCD (Greatest Common Divisor) of the two numbers.

23
Introduction to Programming 2016

Pseudo code:

1. Start

2. Read the two numbers M and N

3. Set the larger of M and N to M; and set the smaller of M and N to N

4. Compute the value of M mod N and set the value to R

5. Check if R is equal to 0

6. If R is 0

6.1.print N

6.2.Stop

7. If R is not 0

7.1.Set the value of M to N

7.2.Set the value of N

Repeat Step 3

Structured Charts

Structured chart depicts the logical functions to the solution of the problem using a chart. It provides an
overview that confirms the solution to the problem without excessive consideration to detail. It is high-level
in nature.

Example: Write a program that asks the user to enter a temperature reading in centigrade and then prints the
equivalent Fahrenheit value.

24
Introduction to Programming 2016
Input Process Output

Centigrade Prompt for centigrade value Fahrenheit

Read centigrade value

Compute Fahrenheit value

Display Fahrenheit value

CelsusToFarh

(main func)

centigard Fahrenheit
centigard

InPutCen CalcFar OutPutFar

Fahrenheit

Flowchart

A flowchart (also spelled flow-chart and flow chart) is a schematic representation of an algorithm or a
process . The advantage of flowchart is it doesn’t depend on any particular programming language, so that it
can used, to translate an algorithm to more than one programming language. Flowchart uses different
symbols (geometrical shapes) to represent different processes. The following table shows some of the
common symbols.

25
Introduction to Programming 2016

General Rules for Flowcharting

1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry
points. The exit point for all flowchart symbols is on the bottom except for the
Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides of the bottom
and one side.
4. Generally, a flowchart will flow from top to bottom. However, an upward flow can
be shown as long as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
a. From one page to another page.
b. From the bottom of the page to the top of the same page.
c. An upward flow of more than 3 symbols
26
Introduction to Programming 2016
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs
or subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.

Example 1: - Draw flow chart of an algorithm to add two numbers and display their result.

Algorithm description

1. Read the rules of the two numbers (A and B)


2. Add A and B
3. Assign the sum of A and B to C
4. Display the result ( c)
The flow chart is:

Start

Read A, B

C= A+B

Print C

End

Example 2: Write an algorithm description and draw a flow chart to check a number is negative or not.

Algorithm description.

1/ Read a number x

2/ If x is less than zero write a message negative

27
Introduction to Programming 2016
3/ Else write a message not negative

Sometimes there are conditions in which it is necessary to execute a group of statements repeatedly. Until
some condition is satisfied. This condition is called a loop. Loop is a sequence of instructions, which is
repeated until some specific condition occurs. A loop normally consists of four parts. These are:

Initialization: - Setting of variables of the computation to their initial values and setting the counter for
determining to exit from the loop.

Computation: - Processing

Test: - Every loop must have some way of exiting from it or else the program would endlessly remain in a
loop.

Increment: - Re-initialization of the loop for the next loop.

Example 3: - Write the algorithmic description and draw a flow chart to find the following sum.

Sum = 1+2+3+…. + 50

28
Introduction to Programming 2016
Algorithmic description

1. Initialize sum to 0 and counter to 1

1.1 If the counter is less than or equal to 50

• Add counter to sum

• Increase counter by 1

• Repeat step 1.1

1.2 Else

• Exit

2. Write sum

Qualities/Features/Properties of a Good Algorithm

29
Introduction to Programming 2016
For a particular algorithm to be regarded as a good algorithm that solves a particular
problem it must meet the following criteria:

30
Introduction to Programming 2016

1. Simplicity/Effectiveness: The algorithm must be simple and not complex to follow


in solving a particular problem. The operations performed by an algorithm should
be simple so that they can be done exactly and in a finite length of time by some
using pencil and paper.
2. Clarity/Definiteness: The algorithm should be clear and easy to read and
understand. In other words, the algorithm must be precisely defined and
unambiguous. If Mr. X performs the actions in an algorithm, Mr. Y should be able
to perform the same action in the same condition and obtain the same result.
3. Thoroughness: A thorough algorithm is one that considers all the possible cases
and situations that may arise in that particular problem. This can be achieved by
making use of variables in storing input. e.g., If you are developing an algorithm
that a banker will be using in their daily transactions; deposit, and withdraw, and
your algorithm did not consider alerting/sending the account owner, the balance
that remains in the account at each time any of the transaction is made, then we can
say that your algorithm is not thorough in whatever transaction made in the account,
except if the alert is not required.
4. Correctness: The algorithm being developed must be correct. This means that the
algorithm must produce the correct result/solution to the problem. However, if the
result is not correct, then the algorithm should be modified. If, however, the
algorithm could not produce the correct result/solution then we will say that the
algorithm did not solve the problem or that the algorithm is wrong.
5. Efficiency: This is the most important of all. This means that the algorithm should
be the best in the time consumed to solve the particular problem. The number of
computer resources that require solving the problem should be considered when
developing an algorithm. An algorithm that requires small memory space and less
time to solve a particular problem are better considered/Taking. This now follows
that if the total numbers of your class members are 1000 and were given the same
problem to develop an algorithm that will solve the problem. The uniqueness starts
with the use of variables. How? I may use x to represent 2 (i.e., x = 2), another
person may use c to represent the same 2 (i.e., c = 2), still, another may like to
phrase or even his name to represent the same value 2.

1
Introduction to Programming 2016

6. Finiteness: The actual steps executed when an algorithm is run should be


of a reasonable size. This means that the execution time of the algorithm
should be of reasonable length. The algorithm must be finite. If an old
computer could not boot before the user dies, then the computer is useless.
7. Input: An algorithm may have some input(s), from a specified device. This
input(s) may be from an external device (like a Hard disc, Flash drive) or
within the computer (e.g., keyboard, RAM). The most common input in an
algorithm includes Numbers – the integer’s numbers, real numbers, character,
etc.
8. Output: An algorithm must have an output(s). The output is always but not
limited to the result of the algorithm. The output may be displayed in the
visual displaying unit (VDU) or stored in the computer memory for another
program/algorithm to use. The algorithm that possesses all these qualities
should be chosen from millions of equivalent algorithms that solve the same
problem.

68
Introduction to Programming 2016

69

You might also like