Docsity

Procedural Programming Fundamentals: Algorithms, Data Types, and Operators, Lecture notes of Programming Languages

Partial preview of the text

Download Procedural Programming Fundamentals: Algorithms, Data Types, and Operators and more Lecture notes Programming Languages in PDF only on Docsity!

c structured programming notes

programming(mku)

DIT1302 / CIT2103 – INTRODUCTION TO STRUCTURED PROGRAMMING

LESSON ONE

What is structured programming?

This is a style in programming paradigm of dividing a problem into sub- problems, and sub – problems into sub-sub- problems, and so on, ( top down design ) then solving each sub-sub – problems individually to produce sub sub-solutions, and combining the sub-solutions to form the solution (bottom up design). Therefore, a complex problem is broken up and made more understandable, and thus easier to solve.

Each sub-solution is implemented as a function (or groups of related functions/modules ). Another name of a function is a procedure, and therefore, this style is also known as procedural style of programming.

The most common techniques used in structured programming to solve all problems are called constructs. Sequence, selection, and repetition constructs. These constructs are also called control structures. Using these three basic control structures, it is possible to write standardized programs, which are easy to read and understand.

The final computer program (consisting of all the function) will be the solution.

Why do we use structured programming?

➢ Structured programming breaks up a problem into sub- problems and this makes problems more understandable and therefore easy to solve. ➢ The solution to the problem is also modifiable in future. Having sections of something always makes the whole thing modifiable. ➢ Structured programming also makes the program more efficient. When having many sub – solutions(functions), we can at one time load. ➢ Having small sections of a program running saves memory space and also CPU’S.

Other programming paradigms ➢ Another programming paradigm popular nowadays is the object-oriented programming style. ➢ This style uses the concept of classe s and objects in programming, but also uses functions to implement these concepts. Therefore, it applies structured programming. ➢ Still another programming paradigm is event driven programming whereby programs procedures respond to events from the user. ➢ Events include mouse button’s click or double click, mouse, dragging, keyboard key press, etc. ➢ Structured programming is universal starting level of learning programming.

Constants Inputs Processes/computation outputs End

Area = Length * Width Pseudo codes do not follow exact rules of writing statements unlike program statements, but require that a statement Pseudo codes do not follow exact rules of writing statements unlike program statements, but require that a statement is clear, meaningful, and representative of the exact logic of solving the problem. For example, we could have written the immediate above statement to compute the area as Let Area= (Length * Width) Thus, we add the word Let, as well as brackets. b) Flowchart symbols These are symbols used to design a program, and are alternative to pseudo codes. They are a diagrammatic way of representing the program’s logic. There are many flowchart symbols used in the design of programs. The mostly used symbols are shown below; Commonly used flowchart symbols Symbol Meaning

Begin/End or Start/Stop

Process/computations (e.g. calculations, assignments)

Input, Output

Shows Logic flow

False

True

Decision making (test condition inside. If it is true, follow the down side arrow. Else, follow the right-side arrow)

Qualities of a good algorithm

  • It should be clear, precise and easy to follow. This is important in avoiding errors, as well as making the design modifiable by future programmers.
  • A program’s design should also show the exact logic of the program. For the calculation that need to be done, it should show the appropriate sequence of formulae.
  • It should also be general , i.e. not specific to a programming language. Thus, the design should be understandable to a programmer of any programming language, such that it can be converted into a program using any programming language.

For example, the pseudo code statement for outputting the value of variable x (of integer type) could be written as

Output x This statement is understandable to a programmer of any language. A C programmer is able to understand this algorithm statement and convert it into the C statement. printf(“%d”, x);

Similarly, a C++ programmer’s statement for the same will be

Count<<x;

condition?

EXERCISE

a) Design and write a program to compute the sum of two integer values. b) Design and write a program to compute the average of three numbers. c) Design and write program to compute the area and circumference of a circle. N.B More examples will be given by your tutor in class so do miss it…….

Basic programming terms.

1. Data Can be define as raw facts that the computer needs in its processing. It is the details that are needed to process something (the information). 2. Information processed data. 3. Processing is the conversion of data into information. It involves activities such as; - Computing a particular value out of a given set of data. - Sorting a set of data. - Rearranging of a set of data. - Searching for a value in a set of data, etc.

Examples of what processing involves

Data Processing Information

Two numbers Computing the sum of the numbers

The sum

A set of numbers Computing the mean of the numbers

The mean

The Radius of a circle Computing the area The circle’s area

Unsorted set of data Sorting the data The sorted set of data

Unarranged set of data Arranging the data The arranged set of data

A set of data Searching for a value in the set

The position of the value in the set.

A set of data Computing the Variance of numbers

The Variance

Employee’s details e.g. basic pay, grade, etc.

Computing the net pay The net pay

4. A Computer A Computer is an electronic device for doing data processing. It is a hardware tool that follows Instructions in it that instructs it on how exactly to do processing. Computer is just a hardware tool that will do nothing unless instructed on what to do. It requires instruction that instruct it on what to do. The term computer is however used to refer to both the hardware and these instructions. Computer also does data storage. 5. Inputs and Outputs; Inputting and Outputting The data that the computer receives from the user (through the inputs device e.g. keyboard) is called inputs, while what is displayed to the user (through the outputs device e.g. monitor) is called the outputs. Receiving inputs from the user is called Inputting, while displayed the outputs to the user is knows as **Outputting.

  1. Programming personnel** a) A computer Programmer- This is the person who develops computer programs. In large scale programming, the programmer is however assisted by. b) A system analyst -who obtains user requirements from the intended user of the program (e.g. what outputs the user expects), analyzes the problem, write the requirements of how the system should work ( system requirements what inputs are required to produce the outputs), and produces the design of the program. c) A Database developer -designs the database in case the program is to be linked to database. d) A clerk -helps the programmer in clerical works eig hties the actual program into computer, carries out testing of the program, document the program etc. e) A Software engineer- is a very important person in software development who is responsible for ensuring the software being produced certifies the required standards. The engineer also supervises and co-ordinates the overall process of software development including analysis, design, program writing, testing and maintenance. f) An analyst programmer does the combined work of both the system analyst and the programmer. 7. A computer program is a set of coded instructions given to the computer, and represents a logical solution to a problem. It directs a computer in performing various operations/tasks

c) Output the area and the circumference. EXAMPLE 2 In Computing the variance of the set of numbers, the steps might be; a) Inputs all the numbers; b) Process the data (list of numbers) as i. Calculate the mean of the numbers using appropriate formula. ii. Compute the variance using the appropriate formula; c) Output the variance.

EXAMPLE 3 In computing the net pay of an employee, the steps might be; a) Input the basic salary, the grade, etc.; b) Process the inputs as i. Computes the deductions; ii. Compute the allowances; iii. Compute the net pay (basic salary-deductions+ allowances); c) Output the net pay.

These steps are implemented as instruction or statements in the program. The program should consist of a sequence of statements that instruct the computer on the exact steps, formulae and logic of solving the problem.

Examples of software used in organization

  1. Tailor Made programs These are programs written specifically for a particular area of application in a particular organization. Such a program is designed to be used only in a particular organization for that area application. Examples
  • Payroll system
  • School/College/University Management System
  • Accounting programs
  • Point of sale programs (used in supermarket)
  • Any program that is written to be used for a particular application in an organization.

The organization may either hire its own programmers to writes the programs or outsource this work to a software development company.

  1. General software

These are programs meant to be used for wide variety of applications and can be used by any type of organization. They are also known as application packages. An application packages contain set of programs for doing general work under a broad area of application. These packages are typically commercial programs i.e. are produced by software development companies for sale. i.e.

  • Word processor.
  • Spreadsheet.
  • Database.
  • Presentation.
  • Multimedia programs etc.

Classification of programming languages

Programming languages are basically classified into:

a. Low Level Programming languages i. Machine level languages (1st Generation languages) ii. Assembly level languages (2nd Generation Languages) b. High Level Programming languages i. General-purpose high-level languages ii. Specific purpose high level languages iii. Commercial languages iv. Scientific languages.

1. The Machine Language. (1st Generation languages)

Machine language is written using machine codes (binary digits) that consist of 0’s & 1’s.

The computer can readily understand Machine code instructions without any translation.

A programmer is required to write his program in strings of 0’s & 1’s, calculate & allocate the core memory locations for his data and/or instructions. Different CPU’s have different machine codes, e.g., codes written for the Intel Pentium processors may differ from those written for Motorola or Cyrix processors. Therefore, before interpreting the meaning of a particular code, a programmer must know for which CPU the program was written.

A machine code instruction is made up of 2 main parts;

(i). An Address ( operand ): It specifies the location (address) of the computer memory where the data to be worked upon can be found.

  1. The CPU can easily understand machine language without translation.
  2. They have a closer control over the hardware, are highly efficient & allow direct control of each operation.
  3. They are therefore suitable for writing Operating system software Game programs , which require fast & efficient use of the CPU time.
  4. The program instructions can be executed by the hardware (processor) much faster. This is because; complex instructions are already broken down into smaller simpler ones.
  5. They require less memory space.
  6. They are stable, i.e., they do not crash once write.

Disadvantages of Low-level languages

Very few computer programs are actually written in machine or Assembly language because of the following reasons;

  1. Low-level languages are difficult to learn, understand, and write programs in them.
  2. Low-level language programs are difficult to debug (remove errors from).
  3. The programs are very long; hence, writing a program in a low-level language is usually tedious & time consuming
  4. The programs are difficult to develop, maintain, and are also prone to errors (i.e., it requires highly trained experts to develop and maintain the programs)
  5. Low level languages are machine-dependent (specific), hence non-portable. This implies that, they are designed for a specific machine & specific processor, and therefore, cannot be transferred between machines with different hardware specifications.
  6. They have a collection of very detailed & complex instructions that control the internal circuiting of the computer. Therefore, it requires one to understand how the computer codes internally.
  7. Relating the program & the problem structures is difficult, and therefore cumbersome to work with.
  8. It is not easy to revise the program, because this will mean re-writing the program again. 3. High Level Language High level languages were developed after low level languages with the aim of making programmers work easier. HLL are also referred (High level) because they are near to the human beings’ languages like English words are used to represent instructions so as to make programming easier. These words include if, else, while, for, do, begin, end etc. the language is user- friendly. A program is made such that it’s very easy for the user to use, and for the programmer to write or modify. The language is thus easier to use in writing programs.

Classification of high-level languages

High level languages can be classified as follows.

a) Commercial languages They are meant for commercial applications. An example is COBOL (Common Business Oriented Languages). b) Scientific languages. They are meant for scientific applications. They include FORTRAN(FORmulaTRANlation), ALGOL(ALGorithmic Oriented Language). c) Special Purpose languages These include CSL- for simulation application, ADA- for real time application, SQL (Structured Query Languages)- for Database querying, prolog- for programming in logic. d) General Purpose Languages. These are multi-purpose languages that can cope with different types of applications. They include: ❖ BASIC (Beginners All Purpose Symbolic Instruction Code). A language used since many years ago, and which has been very simple for beginners of programming to learn. Another language Visual Basic, was developed out of this language. Visual Basic is a windows-based application popular for creating user- friendly graphical user interface applications. It is event based, meaning that the program reacts to user’s events including mouse click, key press, form load, etc. it is popular with creation of business-oriented computer application. Another language that operates very similar to Visual Basic is Delphi. ❖ Pascal – A language popular for training of beginners of programming because of its nearness to English language, thus easy to learn. ❖ C Language- a popular high level, yet ’low level’ language that also provides for programming at hardware level (low level). its popular with development of the system software e.g. operating systems. ❖ C++ Language- it is an extension of C Language to provide for object-oriented programming is a technique of grouping related things together into classes into a class, and specifying the type of data that can be stored for any of the objects and the operation that can be applied to each object. Any occurrence of class (a member of the group) is an object. ❖ Java- an object-oriented programming language that is popular for creation on networks.

Advantages of HLL ❖ HLL are simple to use. ❖ They are machine independent i.e. the program can be executed by different types of computer hardware.

Each language needs its own translator. Generally, there are 3 types of language translators:

1. Assembler. 2. Interpreter. 3. Compiler. Note. Interpreters & Compilers translate source programs written in high-level languages to their machine language equivalents. 1. Assembler

An Assembler translates programs written in Assembly language into machine language that the computer can understand and execute.

Functions of an Assembler.

1). It checks whether the instructions written are valid, and identifies any errors in the program. The Assembler will display these errors as well as the complete source and object programs. If the program has no errors, the job control will let it run immediately, or save the object program so that it may run it later without translating it again.

2). It assigns memory locations to the names the programmer uses. E.g., the Assembler keeps a table of these names so that if an instruction refers to it, the Assembler can easily tell the location to which it was assigned.

3). It generates the machine code equivalent of the Assembly instructions. Usually, the Assembler generates a machine code only when no errors are detected. Some of the errors include;

- Typing mistakes. - Using the wrong format for an instruction. - Specifying a memory location outside the range 0 – 2047.

Note. The Assembler cannot detect Logic errors. The programmer knows of these errors only when the program is run & the results produced are incorrect (not what the programmer expected). The programmer must therefore, go through the program & try to discover why an incorrect result was being produced.

2. Interpreter

An Interpreter translates a source program word by word or line by line. This allows the CPU to execute one line at a time. The Interpreter takes one line of the source program, translates it into a machine instruction, and then it is immediately executed by the CPU. It then takes the next line, translates it into a machine instruction, and then the CPU executes it, and so on.

The translated line is not stored in the computer memory. Therefore, every time the program is

needed for execution, it has to be translated.

3. Compiler

A compiler translates the entire/whole source program into object code at once, and then executes it in machine language code. These machine code instructions can then be run on the computer to perform the particular task as specified in the high-level program.

The process of translating a program written in a high-level source language into machine language using a compiler is called Compilation.

For a given machine, each language requires its own Compiler. E.g., for a computer to be able translate a program written in FORTRAN into machine language; the program must pass through the FORTRAN compiler (which must ‘know’ FORTRAN as well as the Machine language of the computer).

The object code file can be made into a fully executable program by carrying out a Linking process, which joins the object code to all the other files that are needed for the execution of the program. After the linking process, an executable file with an .EXE extension is generated. This file is stored on a storage media.

Points to note.

 The job of a Compiler is much more difficult than that of an Assembler in that, a single statement in a high-level language is equivalent to many machine instructions.

 The format of an Assembly instruction is fairly fixed, while high-level languages give a lot of freedom in the way the programmer writes statements.

Functions of a compiler. A Compiler performs the following tasks during the compilation process:

1). It identifies the proper order of processing, so as to execute the process as fast as possible & minimize the storage space required in memory. 2). It allocates space in memory for the storage locations defined in the program to be executed. 3). It reads each line of the source program & converts it into machine language. 4). It checks for Syntax errors in a program (i.e., statements which do not conform to the grammatical rules of the language). If there are no syntax errors, it generates machine code equivalent to the given program. 5). It combines the program (machine) code generated with the appropriate subroutines from the library. 6). It produces a listing of the program, indicating errors, if any.

LESSON THREE: Data Types, Variables and Operators

Data Type

C++ and C provides several different types of numeric variables. You need different types of

variables because different numeric values have varying memory storage requirements and differ

in the ease with which certain mathematical operations can be performed on them. Small integers

(for example, 1, 199, and -8) require less memory to store, and your computer can perform

mathematical operations (addition, multiplication, and so on) with such numbers very quickly. In

contrast, large integers and floating-point values (123,000,000 or 0.000000871256, for example)

require more storage space and more time for mathematical operations. By using the appropriate

variable types, you ensure that your program runs as efficiently as possible.

Variable Type Keyword (size)Bytes Required Range

character char 1 -128 to 127 Integer Int 2 -32768 to 32767 Short integer Short 2 -32768 to 32767 Long integer Long 4 -2,147,483,648 to 2,147,438, Unsigned character Unsigned char 1 0 to 255 Unsigned integer Unsigned int 2 0 to 65535 Unsigned short Integer unsigned short

2 0 to 65535

Unsigned long integer

unsigned long 4 0 to 4,294,967,

float float 4 3.4E-38 to 3.4E+ Double Double 8 1.7E-308 to 1.7E+ Long double Long double 8 1.7E-308 to 1.7E+

char data type stores characters e.g. alphabets (a-z, A-Z), digit (0-9)- but can’t be used in

expression i.e. are considered non-values in this case, or special literals e.g. ?,-,*,{.

I nt data type stores whole numbers (or integers). An int type variable occupies four bytes.

float data type stores numbers with fraction parts. float occupies four bytes.

Double data type stores numbers with fractional parts just like float. but can store a very large

value e.g. trillion for example, if you try to input 1,000,000,000,000 into a float type variable,

you will get errors unlike when you input into a double type variable.

long keyword it is used with int or double. The data type long int, can store very large integer,

while long double can store even large numbers with fraction parts than double data type.

Short keyword halves the storage space allocated for an int-type variable. You can for example

declare a variable of type short int, and this is so as to spare the memory.

VARIABLES, CONSTANTS AND DATA TYPES

a. Variables A variable is a programming concept of a location in the memory for storing a value that may change from time to time. However, the values that can be stored in a variable must be of the same data type. A program must store the values it is using for computation in variables or other advanced storage locations.

b. Declaration of variables Declaring a variable instructs the computer to allocate a memory space for storing a value of that type. A variable must be declared many times in the same section of the program (in the main () function or in any other function). The syntax for declaring a variable is Type Name; Example The following statement instructs the computer to declare a variable named x, for storing an integer (whole number) int x;

Declaring many variables You can declare many variables using the same statement. In this case, you separate variables with commas. For example, the following statement declares variables named a, b and c of float type. These variables can store numbers with decimal points. This is alternative to writing three statements. float a;