computer programing python, Lecture notes of Computer Programming

Unit Code: SPH409 Unit Name: Computer Programming Lecturer: Dr. Naftali Kimani Lecture: No 1 1 Flow charts and algorithms. Algorithms: This is a logical step-by-step procedure to solve the problem. It can be presented by natural languages, pseudo code and flowcharts, etc. It is the first step in solving a mathematical or computer problem. In a computer problem, algorithms, help us easily understand a program.

Typology: Lecture notes

2017/2018

Uploaded on 10/11/2018

robin-mamoss
robin-mamoss 🇰🇪

1 document

1 / 46

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
KENYATTA UNIVERSITY
DEPARTMENT OF PHYSICS
September 19, 2017
SPH 409: COMPUTER PROGRAMMING
Dr. N. K. Kimani.
Sept, 2017
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e

Partial preview of the text

Download computer programing python and more Lecture notes Computer Programming in PDF only on Docsity!

KENYATTA UNIVERSITY

DEPARTMENT OF PHYSICS

September 19, 2017

SPH 409: COMPUTER PROGRAMMING

Dr. N. K. Kimani.

Sept, 2017

Unit Code: SPH

Unit Name: Computer Programming

Lecturer: Dr. Naftali Kimani

Lecture: No 1

1 Flow charts and algorithms.

Algorithms : This is a logical step-by-step procedure to solve the problem. It can be pre- sented by natural languages, pseudo code and flowcharts, etc. It is the first step in solving a mathematical or computer problem. In a computer problem, algorithms, help us easily understand a program.

An algorithm must posses the following properties:

  • finiteness: The algorithm must always terminate after a finite number of steps.
  • definiteness: Each step must be precisely defined; the actions to be carried out must be rigorously and unambiguously specified for each case.
  • input: An algorithm has zero or more inputs, taken from a specified set of objects.
  • output: An algorithm has one or more outputs, which have a specified relation to the inputs.
  • effectiveness: All operations to be performed must be sufficiently basic that they can be done exactly and in finite length.

Type of Algorithms

The algorithm and flowchart, classification to the three types of control structures. They are:

  1. Sequence structure
  2. Branching (Selection) structure
  3. Loop (Repetition) structure
  4. Combined structure

These three control structures are sufficient for all purposes.

  • The sequence is exemplified by sequence of statements place one after the other – the one above or before another gets executed first. In flowcharts, sequence of statements is usually contained in the rectangular process box.

Common Elements of Algorithms

  • acquire data (input)

G some means of reading values from an external source; most algorithms require data values to define the specific problem (e.g., coefficients of a polynomial)

  • computation

G some means of performing arithmetic computations, comparisons, testing logical conditions, and so forth...

  • selection

G some means of choosing among two or more possible courses of action, based upon initial data, user input and/or computed results

  • iteration

G some means of repeatedly executing a collection of instructions, for a fixed num- ber of times or until some logical condition holds

  • report results (output)

G some means of reporting computed results to the user, or requesting additional data from the user

Flow Chart: This is a graphical or pictorial representation of an algorithm with the help of different symbols, shapes and arrows in order to demonstrate a process or a program. The main purpose of a flowchart is to analyze different processes which is often used as a program planning tool to visually organize the step-by-step process of a program.

Advantages of using Flowcharts

These advantages are as follows:

  1. Communication: A Flowchart can be used as a better way of communication of the logic of a system and steps involve in the solution, to all concerned particularly to the client of system.
  2. Effective analysis: A flowchart of a problem can be used for effective analysis of the problem.
  3. Documentation of Program/System: Program flowcharts are a vital part of a good program documentation. Program document is used for various purposes like know- ing the components in the program, complexity of the program etc.
  4. Efficient Program Maintenance: Once a program is developed and becomes opera- tional it needs time to time maintenance. With help of flowchart maintenance become easier.
  5. Coding of the Program: Any design of solution of a problem is finally converted into computer program. Writing code referring the flowchart of the solution become easy.

Standard symbols used in a flowchart:

The table below describes all the symbols that are used in making flowchart

Symbol Purpose^ Description Flow line Used to indicate the flow of logic by connecting symbols. Terminal(Stop/Start) Used to represent start and end of flowchart. Input/Output Used for input and output operation.

Processing Used for arithmetic operations and data- manipulations.

Decision Used to represent the operation in which there are two alternatives, true and false.

On-page Connector Used to join different flowline

Off-page Connector Used to connect flowchart portion on different page.

Examples:

Example 1: Find the area of a circle of radius R.

  • Input to the Algorithm: Radius r of the Circle.
  • Expected output: Area of the Circle

Algorithm:

Step 1: Start

Step 2: Read or input the radius R of the circle

Step 3: Area ← π × R × R

Step 4: Print Area

Step 5: End

Example 3: Print 1 to 20

Algorithm:

Step 1: Initialize X as 0,

Step 2: Increment X by 1,

Step 3: Print X,

Step 4: If X is less than 20 then go back to step 2.

Flowchart:

Start

Initialize X < 0

Increment X by 1

Print X

X < 20

END

YES

NO

Example 4: Convert Temperature from Fahrenheit (°F) to Celsius (°C)

  • Inputs to the algorithm: Temperature in Fahrenheit
  • Expected output: Temperature in Celsius

Algorithm:

Step 1: Read temperature in Fahrenheit,

Step 2: Calculate temperature with formula C←^5 / 9 ×(F−32),

Step 3: Print C,

Step 4: End

Flowchart:

Start

Read F

C=5 9(F - 32)*

Print C

END

Example 5: Find the largest among three numbers entered by user

Algorithm:

Step 1: Start

Step 2: Declare variables a,b and c.

Step 3: Read variables a,b and c.

Step 4: If a>b

If a>c

Display a is the largest number.

Else

Display c is the largest number.

Else

If b>c

Display b is the largest number.

Else

Display c is the greatest number.

Step 5: Stop

Fibonacci series is defined as a sequence of numbers in which the first two numbers are 1 and 1, or 0 and 1, depending on the selected beginning point of the sequence, and each subsequent number is the sum of the previous two. So, in this series, the nth^ term is the sum of (n-1)th^ term and (n-2)th^ term.

Mathematically, the nth^ term of the Fibonacci series can be represented as:

tn = tn− 1 + tn− 2

The Fibonacci numbers upto certain term can be represented as: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144.... or 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144....

2 Types of computer programming languages.

Different kinds of languages have been developed to perform different types of work on the computer. Basically, languages can be divided into two categories according to how the computer understands them.

Two Basic Types of Computer Language

  • Low-Level Languages: A language that corresponds directly to a specific machine
  • High-Level Languages: Any language that is independent of the machine

There are also other types of languages, which include

  • System languages: These are designed for low-level tasks, like memory and process management
  • Scripting languages: These tend to be high-level and very powerful
  • Domain-specific languages: These are only used in very specific contexts
  • Visual languages: Languages that are not text-based
  • Esoteric languages: Languages that are jokes or are not intended for serious use

These languages are not mutually exclusive, and some languages can belong to multiple categories. The terms low-level and high-level are also open to interpretation, and some languages that were once considered high-level are now considered low-level as languages have continued to develop.

2.1 Low-Level Languages

Low-level computer languages are either machine codes or are very close. A computer cannot understand instructions given to it in high-level languages or in English. It can only understand and execute instructions given in the form of machine language i.e. binary. There are two types of low-level languages:

  • Machine Language: a language that is directly interpreted into the hardware
  • Assembly Language: a slightly more user-friendly language that directly corresponds to machine language

Machine Language

Machine language is the lowest and most elementary level of programming language and was the first type of programming language to be developed. Machine language is basically the only language that a computer can understand and it is usually written in hex. In fact,

2.2 High-Level Languages

High-level computer languages use formats that are similar to English. The purpose of developing high-level languages was to enable people to write programs easily, in their own native language environment (English).

High-level languages are basically symbolic languages that use English words and/or math- ematical symbols rather than mnemonic codes. Each instruction in the high-level language is translated into many machine language instructions that the computer can understand.

Advantages

  • High-level languages are user-friendly
  • They are similar to English and use English vocabulary and well-known symbols
  • They are easier to learn
  • They are easier to maintain
  • They are problem-oriented rather than machine-based
  • A program written in a high-level language can be translated into many machine lan- guages and can run on any computer for which there exists an appropriate translator
  • The language is independent of the machine on which it is used i.e. programs devel- oped in a high-level language can be run on any computer text

Disadvantages

  • A high-level language has to be translated into the machine
  • The object code generated by a translator might be inefficient compared to an equiv- alent assembly language program

Types of High-Level Languages

Many languages have been developed for achieving a variety of different tasks. Some are fairly specialized, and others are quite general. These languages, categorized according to their use, are:

  1. Algebraic Formula-Type Processing

These languages are oriented towards the computational procedures for solving mathemat- ical and statistical problems.

Examples include:

  • BASIC (Beginners All Purpose Symbolic Instruction Code)
  • FORTRAN (Formula Translation)
  • PL/I (Programming Language, Version 1)
  • ALGOL (Algorithmic Language)
  • APL (A Programming Language)
  1. Business Data Processing

These languages are best able to maintain data processing procedures and problems in- volved in handling files.

Some examples include:

  • COBOL (Common Business Oriented Language)
  • RPG (Report Program Generator)
  1. String and List Processing These are used for string manipulation, including search patterns and inserting and deleting characters.

Examples are:

  • LISP (List Processing)
  • Prolog (Program in Logic)
  1. Object-Oriented Programming Language

In Object Oriented Programming, the computer program is divided into objects.

Examples are:

  • C++
  • Python
  • Java
  1. Visual Programming Language

These programming languages are designed for building Windows-based applications.

Examples are:

  • Visual Basic
  • Visual Java
  • Visual C

data structures. Selecting one data structure type over the other should be done carefully by considering the relationship among the data elements that needs to be stored.


Graph vs Tree

Graph and Tree are used in data structures. There are certainly some differences between Graph and Tree. A set of vertices having a binary relation is called a graph whereas tree is a data structure that has a set of nodes linked to each other.

Graph

A graph is a set of items that are connected by edges and each item is known as node or vertex. In other words, a graph can be defined as the set of vertices and there is a binary relation between these vertices.

In implementation of a graph, the nodes are implemented as objects or structures. The edges can be represented in different ways. One of the ways is that each node can be asso- ciated with an incident edges array. If the information is to be stored in nodes rather than edges then the arrays acts as pointers to nodes and also represent edges. One of the advan- tages of this approach is that additional nodes can be added to the graph. Existing nodes can be connected by adding elements to arrays. But there is one disadvantage because time is required in order to determine whether there is an edge between the nodes.

Other way to do this is to keep a two dimensional array or matrix M that has Boolean val- ues. The existence of edge from node i to j is specified by entry Mij. One of the advantages of this method is to find out if there is any edge between two nodes.

Tree

Tree is also a data structure used in computer science. It is similar to the structure of the tree and has a set of nodes that are linked to each other.

A node of a tree may contain a condition or value. It can also be a tree of its own or it can represent a separate data structure. Zero or more nodes are present in a tree data structure. If a node has a child then it is called parent node of that child. There can be at most one parent of a node. The longest downward path from the node to a leaf is the height of the node. The depth of node is represented by the path to its root.

In a tree, the topmost node is called root node. The root node has no parents as it is the top most one. From this node, all tree operations begin. By using links or edges, other nodes can be reached from the root node. The bottom-most level nodes are called leaf nodes and they don’t have any children. The node that has number of child nodes is called inner node or internal node.

Difference between graph and tree:

  • A tree can be described as a specialized case of graph with no self loops and circuits.
  • There are no loops in a tree whereas a graph can have loops.
  • There are three sets in a graph i.e. edges, vertices and a set that represents their rela- tion while a tree consists of nodes that are connected to each other. These connections are referred to as edges.
  • In tree there are numerous rules spelling out how connections of nodes can occur whereas graph has no rules dictating the connection among the nodes.

Arrays vs Linked Lists

Arrays are the most commonly used data structure to store collection of elements. Most programming languages provide methods to easily declare arrays and access elements in the arrays. Linked list, more precisely singly- linked list, is also a data structure that can be used to store collection of elements. It is made up of a sequence of nodes and each node has a reference to the next node in the sequence.

One important property of an array is that entire array is allocated as a single block of memory and each element gets its own space in the array. Once an array is defined, its size is fixed. So if you are not sure about the size of the array at compile time, you would have to define a large enough array to be in the safe side. But, most of the time we are actually going to use less number of elements than we have allocated. So a considerable amount of memory is actually wasted. On the other hand if the “large enough array” is not actually large enough, the program would crash.

A linked list allocates memory to its elements separately in its own block of memory and the overall structure is obtained by linking these elements as links in a chain. The data field holds the actual data stored and the next field holds the reference to the next element in the chain. The first element of the linked list is stored as the head of the linked list. A linked list with three elements stores its data and all elements except the last one store a reference to the next element. Last element holds a null value in its next field. Any element in the list can be accessed by starting at the head and following the next pointer until you meet the required element.

Even though the arrays and linked lists are similar in the sense that both of them are used to store collection of elements, they incur differences due to the strategies they use to allocate memory to its elements. Arrays allocate memory to all its elements as a single block and the size of the array has to be determined at runtime. This would make the arrays inefficient in situations where you don’t know the size of the array at compile time. Since a linked list allocates memory to its elements separately, it would be much efficient in situations in which you don’t know the size of the list at compile time. Declaration and accessing elements in a linked list would not be straight forward compared to how you directly access elements in an array using its indices.


  • The hashmap cannot have the duplicate keys in it that is why there keys must only be mapped with only the single value. But the hashtable allows the duplicate keys in it.
  • The hashmap contains an iterator which is basically fail-safe but the hashtable con- tains an enumerator, which is not fail-safe.
  • The access to hashtable is synchronized on the table while the access to the hashmap is not synchronized.

4 Characteristics of a good computer program

Every computer requires appropriate instruction set (programs) to perform the required task. The quality of the processing depends upon the given instructions. If the instructions are improper or incorrect, then it is obvious that the result will be superfluous.

A good programming language must be simple and easy to learn and use.It should provide a programmer with a clear,simple and unified set of concepts that can be grasped eas- ily.The overall simplicity of a programme strongly affects the readability of the programs written in that language and programs that are easier to read and understand are easier to maintain.It is also easy to develop and implement a compiler or an interpreter for a simple language.However,the power needed for the language should not be sacrificed for simplicity.

A good computer program should have following characteristics:

  • Portability: Portability refers to the ability of an application to run on different platforms (operating systems) with or without minimal changes. Due to rapid devel- opment in the hardware and the software, nowadays platform change is a common phenomenon. Hence, if a program is developed for a particular platform, then the life span of the program is severely affected.
  • Readability: The program should be written in such a way that it makes other programmers or users to follow the logic of the program without much effort. If a program is written structurally, it helps the programmers to understand their own program in a better way. Even if some computational efficiency needs to be sacrificed for better readability, it is advisable to use a more user-friendly approach, unless the processing of an application is of utmost importance.
  • Efficiency: Every program requires certain processing time and memory to process the instructions and data. As the processing power and memory are the most precious resources of a computer, a program should be laid out in such a manner that it utilizes the least amount of memory and processing time.
  • Structural: To develop a program, the task must be broken down into a number of subtasks. These subtasks are developed independently, and each subtask is able to perform the assigned job without the help of any other subtask. If a program is developed structurally, it becomes more readable, and the testing and documentation process also gets easier.
  • Flexibility: A program should be flexible enough to handle most of the changes with- out having to rewrite the entire program. Most of the programs are developed for a certain period and they require modifications from time to time. For example, in case of payroll management, as the time progresses, some employees may leave the company while some others may join. Hence, the payroll application should be flex- ible enough to incorporate all the changes without having to reconstruct the entire application.