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

Computer & Programming Fundamentals Unit-3

Focp notes

Uploaded by

radhii.kaa22
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Computer & Programming Fundamentals Unit-3

Focp notes

Uploaded by

radhii.kaa22
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT-III

3.0 NATURAL LANGUAGE:


A natural language or ordinary language is any language that has evolved naturally in
humans through use and repetition without conscious planning or premeditation. Natural
languages can take different forms, such as speech or signing. They are distinguished from
constructed and formal languages such as those used to program computers or to study
logic.

3.1 COMPUTER LANGUAGES | TYPES OF COMPUTER


LANGUAGES

Around the world language is a source of communication among human beings. Similarly,
in order to communicate with computer user also needs to have a language, that should be
understandable by the computers. For the purpose different languages are developed for
performing different types of work on the computer.

Mainly there are two types of computer languages.

3.1.1 LOW LEVEL COMPUTER LANGUAGES

These are machine codes or close to it. Computer cannot understand instruction given in
high level languages or in English. It can only understand and execute instructions given in
the form of machine languages i.e. the binary number 0 and 1. There are two types of low
level computer language.

3.1.1.1 Machine Language

The lowest and most elementary language and was the first type of programming language
to be developed. Mache language is basically the only language which computer can
understand. In fact, a manufacturer designs a computer to obey just one language, its
machine code, which is represented inside the computer by a string of binary digits (bits) 0
and 1. The symbol 0 stands for the absence of an electric pulse and 1 for the presence of an
electric pulse. Since a computer is capable of recognizing electric signals, therefore, it
understands machine language.

The set of binary codes which can be recognize by the computer is known as the machine
code instruction set. A machine language instruction consists of an operation code one or
more operands. The operation code specifies that operation that is to be performed e.g.
read, record etc. the operands identify the quantities to be operated on e.g. the numbers to
be added or the locations where data are stored. But, it is almost impossible to write
programs directly in machine code. For this reason, programs are normally written in
assembly or high level languages and then are translated in the machine language by
different translators.

Page 1 of 28
Advantages

1. It makes fast and efficient use of the computer


2. It requires no translator to translate the code i.e. directly understood by the computer.

Disadvantages

1. All operation codes have to be remembered


2. All memory addresses have to be remembered
3. It is hard to amend or find errors in a program written in the machine language
4. These languages are machine dependent i.e. a particular machine language can be used on
only one type of computer.

3.1.1.2 Assembly Languages

It was developed to overcome some of the many inconveniences of machine language.


This is another low level but a very important language in which operation codes and
operands are given in the form of alphanumeric symbols instead of 0’s and 1’s. These
alphanumeric symbols will be known as mnemonic codes and can have maximum up to 5
letter combinations e.g. ADD for addition, SUB for subtraction, START LABEL etc.
because of this feature it is also known as “Symbolic Programming Language”. This
language is very difficult and needs a lot of practice to master it because very small
English support is given. This symbolic language helps in compiler orientations. The
instructions of the assembly language will also be converted to machine codes by language
translator to be executed by the computer

Advantages

1. It is easier to understand and use as compared to machine language


2. It is easy to locate and correct errors
3. It is modified easily

Disadvantages

1. Like machine language it is also machine dependent


2. Since it is machine dependent, there programmer should have the knowledge of he hardware
also.

Page 2 of 28
3.1.2 HIGH LEVEL LANGUAGES

High level computer languages give formats close to English language and the purpose of
developing high level languages is to enable people to write programs easily and in their
own native language environment (English). High-level languages are basically symbolic
languages that use English words and/or mathematical symbols rather than mnemonic
codes. Each instruction in the high level language is translated into many machine
language instructions thus showing one-to-many translation.

 Problem-Oriented Language: These are languages used for handling specialized types of
data processing problems where programmer only specifies the input/output requirements
and other relative information of the problem, that are to be solved. The programmer does
not have to specify the procedure to be followed in solving that particular problem.
 Procedural Language: These are general purpose languages that are designed to express
the logic of a data processing problem.
 Non-procedural Language: Computer Programming Languages that allow users and
professional programmers to specify the results they want without specifying how to solve
the problem.

Selection of a Computer Language

There are many high-level languages in use today. The choice of language depends on type
and complexity of the problem.

1. Purpose e.g. business, educational, scientific.


2. Facilities provided e.g. meaningful variable names, control and data structures, error
checking facilities.
3. Ease of learning and use.
4. Portability - if a program is to he used on or in more than one system.
5. Popularity - availability of compilers/interpreters.
6. Documentation provided.
Page 3 of 28
3.1.2.1 Types of High Level Languages

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

Algebraic Formula-Type Processing. These languages are oriented towards the computational
procedures for solving mathematical and statistical problems. Examples are

1. BASIC (Basic All Purpose Symbolic Instruction Code)


2. FORTRAN (Formula Translation).
3. PL/1 (Programming Language, Version 1).
4. ALGOL (Algorithmic Language).
5. APL (A Programming Language).

Business Data Processing. These languages emphasize their capabilities for maintaining data
processing procedures and files handling problems. Examples are:

1. COBOL (Common Business Oriented Language)


2. RPG (Report Program Generator).

String and List Processing. These are used for string manipulation including search for
patterns, inserting and deleting characters. Examples are: LISP (List Processing).

Multipurpose Language. A general purpose language used for algebraic procedures, data
and string processing. Examples are:

1. Pascal (after the name of Blaise Pascal).


2. PL/1 (Programming Language, version 1).
3. C language.

Simulation: These may be written in algebraic or multipurpose languages. Examples are:

1. SPSS (Statistical Package System Simulator).


2. GPSS (General Purpose System Simulator).

Advantages: Following are the advantages of a high level language:

1. User-friendly (people based)


2. Similar to English with vocabulary of words awl symbols therefore it is easier to learn.
3. They require less time to write
4. They are easier to maintain
5. Problem oriented' rather than 'machine' based
6. Shorter than their low-level equivalents. One statement translates into many machine code
instructions.

Page 4 of 28
7. Program written in a high-level equivalent can he translated into many machine language
and therefore can run on every computer for which there exists an appropriate translator.
8. It is independent of the machine on which it used i.e. programs developed in high level
language can be run on any computer.

Disadvantages: There are certain disadvantages also In spite these disadvantages high-
level languages have proved their worth. The advantages out-weigh the disadvantages by
far, for most applications. These are:

1. A high-level language has to be translated into the -machine language by a translator and
thus a price in computer time is paid.
2. The object code generated by a translator might be inefficient compared to an equivalent
assembly language program

3.2 GENERATIONS OF COMPUTER LANGUAGES: -

A generation language may refer to any of the following:

1. The first generation languages, or 1GL, are low-level languages that are language.
Consists of a set of commands, which are represented as a series of 1s and 0s
corresponding to the instruction set that is hard wired into the security of a microprocessor.

2. The second-generation languages, or 2GL, are also low-level assembly languages.


They are sometimes used in kernels and hardware drives, but more commonly used for
video editing and video games.

3. The third-generation languages, or 3GL, are high-level languages, such as C, C++, Java,
JavaScript, and Visual Basic.

4. The fourth-generation languages, or 4GL, are languages that consist of statements


similar to statements in a human language. Fourth generation languages are commonly
used in database programming and scripts examples include Perl, PHP, Python, Ruby, and
SQL.

5. The fifth-generation languages, or 5GL, are programming languages that contain


visual tools to help develop a program. Examples of fifth generation languages include
Mercury, OPS5, and Prolog.

3.3 ASSEMBLER:
A computer will not understand any program written in a language, other than its machine
language. The programs written in other languages must be translated into the machine
language. Such translation is performed with the help of software. A program which
translates an assembly language program into a machine language program is called an
assembler. If an assembler which runs on a computer and produces the machine codes for
the same computer, then it is called self-assembler or resident assembler. If an assembler
Page 5 of 28
that runs on a computer and produces the machine codes for other computer, then it is
called Cross Assembler.

Assemblers are further divided into two types: One Pass Assembler and Two Pass
Assembler. One pass assembler is the assembler which assigns the memory addresses to
the variables and translates the source code into machine code in the first pass
simultaneously. A Two Pass Assembler is the assembler which reads the source code
twice. In the first pass, it reads all the variables and assigns them memory addresses. In the
second pass, it reads the source code and translates the code into object code.

3.4 COMPILER:
It is a program which translates a high level language program into a machine language program.
A compiler is more intelligent than an assembler. It checks all kinds of limits, ranges, errors etc.
But its program run time is more and occupies a larger part of the memory. It has slow speed.
Because a compiler goes through the entire program and then translates the entire program into
machine codes. If a compiler runs on a computer and produces the machine codes for the same
computer, then it is known as a self-compiler or resident compiler. On the other hand, if a compiler
runs on a computer and produces the machine codes for other computer then it is known as a cross
compiler.

3.5 INTERPRETER:
An interpreter is a program which translates statements of a program into machine code. It
translates only one statement of the program at a time. It reads only one statement of program,
translates it and executes it. Then it reads the next statement of the program again translates it and
executes it. In this way it proceeds further till all the statements are translated and executed. On the
other hand, a compiler goes through the entire program and then translates the entire program into
machine codes. A compiler is 5 to 25 times faster than an interpreter.
By the compiler, the machine codes are saved permanently for future reference. On the
other hand, the machine codes produced by interpreter are not saved. An interpreter is a
small program as compared to compiler. It occupies less memory space, so it can be used
in a smaller system which has limited memory space.

3.6 LINKER:
In high level languages, some built in header files or libraries are stored. These libraries are
predefined and these contain basic functions which are essential for executing the program. These
functions are linked to the libraries by a program called Linker. If linker does not find a library of a
function, then it informs to compiler and then compiler generates an error. The compiler
automatically invokes the linker as the last step in compiling a program.
Not built in libraries, it also links the user defined functions to the user defined libraries.
Usually a longer program is divided into smaller subprograms called modules. And these
modules must be combined to execute the program. The process of combining the modules
is done by the linker.

3.7 LOADER:
Loader is a program that loads machine codes of a program into the system
memory. In Computing, a loader is the part of an Operating System that is responsible for
loading programs. It is one of the essential stages in the process of starting a program.
Because it places programs into memory and prepares them for execution. Loading a
Page 6 of 28
program involves reading the contents of executable file into memory. Once loading is
complete, the operating system starts the program by passing control to the loaded
program code. All operating systems that support program loading have loaders. In many
operating systems the loader is permanently resident in memory.

3.8 CHARACTERISTICS OF A GOOD PROGRAMMING


LANGUAGE: -
There are some popular high-level programming languages, while there are others that
could not become so popular in-spite of being very powerful. There might be reasons for
the success of a language but one obvious reason is its characteristics. Several
characteristics believed to be important for making it good:

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 easily.
The overall simplicity of a 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. For
Example, BASIC is liked by many programmers because of its simplicity.

3.8.1 NATURALNESS:
A good language should be natural for the application area for which it is designed. That
is, it should provide appropriate operators, data structures, control structures and a natural
syntax to facilitate programmers to code their problems easily and efficiently. FORTRAN
and COBOL are good examples of languages possessing high degree of naturalness in
scientific and business application areas, respectively.

3.8.2 ABSTRACTION:
Abstraction means ability to define and then use complicated structures or operations in
ways that allow many of the details to be ignored. The degree of abstraction allowed by a
language directly affects its ease of programming. For Example, object-oriented languages
support high degree of abstraction. Hence, writing programs in object-oriented languages
is much easier. Object-oriented also support re usability of program segments due to this
feature.

3.8.3EFFICIENCY:
Programs written in a good language are translated into machine code efficiently, are
executed and require relatively less space in memory. That is, a good programming
language is supported with a good language translator (a compiler or an interpreter)
that gives due consideration to space and time efficiency.

3.8.4 STRUCTURED PROGRAMMING SUPPORT:


A good language should have necessary features to allow programmers to write their
programs based on the concepts of structured programming. This property greatly affects
the ease with which a program may be written, tested and maintained. Moreover, it forces
a programmer to look at a problem in a logical way so that fewer errors are created while
writing a program for the problem.
Page 7 of 28
3.8.5 COMPACTNESS:
In a good language, programmers should be able to express the intended operations
concisely without losing readability. Programmers generally do not like a verbose
language because they need to write too much. Many programmers dislike COBOL,
because it is verbose in nature (Lacks Compactness)

3.8.6 LOCALITY:
A good language should be such that while writing a program, a programmer need not
jump around the visually as the text of a program is prepared. This allows the programmer
to concentrate almost solely on the part of the program around the statement currently
being worked with. COBOL and to some extent C and Pascal lack locality because data
definitions are separated from processing statements, perhaps by many pages of code, or
have to appear before any processing statement in the function/procedure.

3.8.7 EXTENSIBILITY:

A good language should also allow extensions through a simply, natural and elegant
mechanism. Almost all languages provide subprogram definition mechanisms for the
purpose, but some languages are weak in this aspect.

3.8.8 SUITABILITY TO ITS ENVIRONMENT:

Depending upon the type of application for which a programming language has been
designed, the language must also be made suitable to its environment. For Example, a
language designed for a real-time application must be interactive in nature. On the other
hand, languages used for data-processing jobs like payroll, stores accounting etc. may be
designed to operative in batch mode.

The following are some of the important characteristics of a good programming language

1. The language must allow the programmer to write simple, clear and concise programs.
2. The language must be simple to use so that a programmer can learn it without any explicit
training.
3. The language must be platform independent. That is, the program developed using the
programming language can run on any computer system.
4. The Graphical User Interface (GUI) of the language must be attractive, user-friendly, and
self-explanatory.
5. The function library used in the language should be well documented so that the necessary
information about a function can be obtained while developing application.
6. Several programming constructs supported by the language must match well with the
application area it is being used for.
7. The programs developed in the language must make efficient use of memory as well as
other computer resources.
8. The language must provide necessary tools for development, testing, debugging, and
maintenance of a program. All these tools must be incorporated into a single environment

Page 8 of 28
known as Integrated Development Environment (IDE), which enables the programmer to
use them easily.
9. The language must be consistent in terms of both syntax and semantics.

3.9 PLANNING THE COMPUTER PROGRAM: PROBLEM


SOLVING

DEFINITION
The term problem solving is used in numerous disciplines, sometimes with different
perspectives, visuals, and often with different terminologies. For instance, it is a mental
process in psychology and a computerized process in computer science. Problems can also
be classified into two different types (ill-defined and well-defined) from which appropriate
solutions are to be made. Ill-defined problems are those that do not have clear goals,
solution paths, or expected solutions. On the contrary, well-defined problems have specific
goals, clearly defined solution paths, and clear expected solutions. These problems also
allow for more initial planning than ill-defined problems. [1] Solving problems sometimes
involves dealing with pragmatics (logic) and semantics (interpretation of the problem).
The ability to understand what the goal of the problem is, and what rules could be applied,
represents the key to solving the problem. Sometimes the problem requires abstract
thinking and coming up with a creative solution.
Problem solving is the act of defining a problem; determining the cause of the problem;
identifying, prioritizing and selecting alternatives for a solution; and implementing a
solution.

An organization needs to define some standard of problem solving, so that leadership can
effectively direct others in the research and resolution of issues.

In problem solving, there are four basic steps.

1. Define the problem

Diagnose the situation so that your focus is on the problem, not just its symptoms. Helpful
techniques at this stage include using flowcharts to identify the expected steps of a process
and cause-and-effect diagrams to define and analyze root causes.

2. Generate alternative solutions

Postpone the selection of one solution until several alternatives have been proposed.
Having a standard with which to compare the characteristics of the final solution is not the
same as defining the desired result. A standard allows us to evaluate the different intended
results offered by alternatives. When you try to build toward desired results, it’s very
difficult to collect good information about the process.

Considering multiple alternatives can significantly enhance the value of your final
solution. Once the team or individual has decided the “what should be” model, this target
standard becomes the basis for developing a road map for investigating alternatives.
Page 9 of 28
Brainstorming and team problem-solving techniques are both useful tools in this stage of
problem solving.

Many alternative solutions should be generated before evaluating any of them. A common
mistake in problem solving is that alternatives are evaluated as they are proposed, so the
first acceptable solution is chosen, even if it’s not the best fit. If we focus on trying to get
the results we want, we miss the potential for learning something new that will allow for
real improvement.

3. Evaluate and select an alternative

Skilled problem solvers use a series of considerations when selecting the best alternative.
They consider the extent to which:

 A particular alternative will solve the problem without causing other unanticipated
problems.
 All the individuals involved will accept the alternative.
 Implementation of the alternative is likely.
 The alternative fits within the organizational constraints.

4. Implement and follow up on the solution

Leaders may be called upon to order the solution to be implemented by others, “sell” the
solution to others or facilitate the implementation by involving the efforts of others. The
most effective approach, by far, has been to involve others in the implementation as a way
of minimizing resistance to subsequent changes.

Feedback channels must be built into the implementation of the solution, to produce
continuous monitoring and testing of actual events against expectations. Problem solving,
and the techniques used to derive elucidation, can only be effective in an organization if
the solution remains in place and is updated to respond to future changes.

Two phases involved in the design of any program:


(i) Problem Solving Phase
(ii) Implementation Phase

1. In the problem-solving phase the following steps are carried out:


←Define the problem
←Outline the solution
←Develop the outline into an algorithm
←Test the algorithm for correctness

2. The implementation phase comprises the following steps:


←Code the algorithm using a specific programming language
←Run the program on the computer
←Document and maintain the program
Structured Programming Concept

Page 10 of 28
Structured programming techniques assist the programmer in writing effective error free programs.
The elements of structured of programming include:
←Top-down development
←Modular design.
The Structure Theorem:
It is possible to write any computer program by using only three (3) basic control structures,
namely:
←Sequence
←Selection(if-then-else)
←Repetition (iteration, looping, Do While)
ALGORITHMS
An algorithm is a sequence of precise instructions for solving a problem in a finite amount of time.
Properties of an Algorithm:
← It must be precise and unambiguous
← It must give the correct solution in all cases
← It must eventually end.
Algorithms and Humans
Algorithms are not a natural way of stating a problem’s solution, because we do not normally state
our plan of action.

← We tend to execute as we think about the problem. Hence, there are inherent
difficulties when writing an algorithm.
← We normally tailor our plans of action to the particular problem at hand and not to
a general problem (i.e. a nearsighted approach to problem solving)
← We usually do not write out our plan, because we are usually unaware of the basic
ideas we use to formulate the plan. We hardly think about it – we just do it.
← Computer programmers need to adopt a scientific approach to problem solving, i.e.
writing algorithms that are comprehensive and precise.
←We need to be aware of the assumptions we make and of the initial conditions.
←Be careful not to overlook a step in the procedure just because it seems obvious.
←Remember, machines do not have judgment, intuition or commonsense!

Developing an Algorithm
←Understand the problem (Do problem by hand. Note the steps)
←Devise a plan (look for familiarity and patterns)
←Carry out the plan(trace)
←Review the plan(refinement)

Understanding the Algorithm

Page 11 of 28
Possibly the simplest and easiest method to understand the steps in an algorithm, is by using the
flowchart method. This algorithm is composed of block symbols to represent each step in the
solution process as well as the directed paths of each step. The most common block symbols are:

Symbol Represe Symbol Re


ntation pre
sen
tati
on
Start/Stop Decision

Process Connector

Input/Output Flow
Direction

Fig 3.1: Symbols used in algorithm

Problem Example
Find the average of a given set of numbers.

Solution Steps
1. Understanding the problem:
(i) Write down some numbers on paper and find the average manually, noting each step
carefully.
e.g. Given a list say: 5, 3, 25, 0, 9
(ii) Count numbers | i.e. How many?5
(iii) Add them up | i.e. 5 + 3 + 25 + 0 + 9 =42
(iv) Divide result by numbers counted | i.e. 42/5 =8.4

2. Devising a plan:
Make note of not what you did in steps (i) through (iv), but how you did it. In doing so, you will
begin to develop the algorithm.

How do we count the numbers?


Starting at 0 i.e. set COUNTER to 0 Look at 1st number, add 1 to COUNTER
Look at 2nd number, add 1 to COUNTER
and so on, until you reach the end of the list
Page 12 of 28
How do we add numbers?
Let SUM be the sum of numbers in list. Set SUM to 0 Look at 1st number, add number to SUM
Look at 2nd number, add number to SUM
and so on, until we reach end of list

How do we compute the average?


Let AVG be the average
then AVG = total sumofitems i.e. SUM
number of items COUNTER

3. Identifying patterns, repetitions and familiartasks.


Familiarity: Unknown number of items? i.e. n item

Patterns: look at each number in the list

Repetitions: Look at a number


Add number to sum Add 1 to counter

4. Carrying out the plan Check each step Consider special cases Checkresult
Check boundary conditions:
i.e. what if the list is empty? Division by 0?
Are all numbers within the specified range?
In this example, no range is specified - No special cases.
Check result by tracing the algorithm with a list of numbers e.g. 7, 12, 1, 5,13. If list is empty, we
do not want to compute average.

Therefore, before calculating AVG, check if COUNTER = 0


i.e. If COUNTER = 0 then AVG = 0 else AVG = SUM/COUNTER

5. Review the plan:


←Can you derive the result differently?
←Can you make the solution more general?
←Can you use the solution or method for another problem?
e.g. average temperature or average grades

Before we write out the algorithm in its proper form, let’s introduce the concept of a
VARIABLE.
A variable is a symbolic name assigned to a memory cell which stores a particular
value. e.g. COUNTER, SUM, AVG

A flowchart representation of the algorithm for the above problem can be as follows:

Page 13 of 28
Fig 3.2: Flowchart for the given problem

6. The AlgorithmicLanguage
During development of an algorithm, the language gradually progresses from English towards a
programming language notation. An intermediate notation called pseudocode is commonly used to
express algorithms.

Algorithmic Structure
Every algorithm should have the following sections, in the stated order:

Header : Algorithm’s name or title.

Declaration : A brief description of algorithm and variables.


i.e. a statement of the purpose.

Body : Sequence of steps

Terminator: End statement

How to write Pseudocode?


An algorithm can be written in pseudocode using six (6) basic computer operations:

A computer can receiveinformation.


Typical pseudocode instructions to receive information are: Read name
Get name
Read number1, number2
Page 14 of 28
A computer can output (print)information.
Typical pseudocode instructions are: Print name
Write "The average is", avg

A computer can perform arithmeticoperation


Typical pseudocode instructions: Add number to total, or Total = Total + Number Avg = sum/total

A computer can assign a value to a piece ofdata:


e.g. to assign/give data an initial value: Initialize total to zero
Set count to 0
To assign a computed value: Total = Price + Tax
A computer can compare two (2) pieces of information and select one of twoactions.
Typical pseudocode e.g.
IF number < 0 then
add 1 to neg_number
ELSE
add one to positive number
end-if

A computer can repeat a group ofactions.


Typical pseudocode e.g.
REPEAT until total = 50 read number writenumber
add 1 to total end-repeat
OR
WHILE total < = 50 do:
read number write number
end-while

Let’s review the plan and write out algorithm for the average problem in the specified format:

Algorithm Average
This algorithm reads a list of numbers and computes their average.
Let: SUM be the total of the numbers read COUNTER be the number of items in thelist AVG
be the average of all thenumbers

Set SUM to 0,
Set COUNTER to 0. (i.e. initialize variables)

While there is data do:


Read number
COUNTER = COUNTER + 1
(i.e. add 1 to COUNTER, storing result in COUNTER)
SUM = SUM + number
(i.e. add number to SUM, storing result in SUM)
end-while

if COUNTER = 0 then
AVG = 0

Page 15 of 28
else end-if Stop.

AVG = SUM/ COUNTER

EXAMPLE 2:
Design a program to read in the max. and min. temperature on a particular day and calculate and
print the average temp.

INPUT PROCESSING O
U
T
P
U
T
Read : Calculate avg_temp P
max_ r
temp, i
min_ n
temp t

a
v
g
_
t
e
m
p
Fig 3.3

Once the problem has been properly defined, making sure that no assumptions are made and every
action required is stated in the Processing column, we can proceed to develop the algorithm. To do
this, simply focus on the actions in the processing column, then write down the steps that specify
how to perform each action and in what sequence.

Sample solution for EXAMPLE 1


Algorithm Add _Numbers
Read Num1, Num2, Num3 Total = Num1 + Num2 + Num3 Print Total
Stop

Top-Down Design Approach (Modularization)

The modularization approach involves breaking a problem into a set of sub-problems, followed by
breaking each sub-problem into a set of tasks, then breaking each task into a set of actions.

Problem 1
Add 23 and 35
- no further refinement is required.

Problem 2
Turn on a light bulb
Sub-problem 1: locate bulb (one task, one action) Sub-problem 2: depress switch

Problem 3
Given a list of students’ test scores, find the highest and lowest score and the average score.
Sub-problem 1: read students’ scores Sub-problem 2: find highest score Sub-problem 3: find lowest
score

Sub-problem 1 can be considered as one action and therefore needs no further refinement.

Sub-problems 2 and 3 however can be further divided into a group of actions.

Advantages of the Top-Down Design Method

• It is easier to comprehend the solution of a smaller and less complicated problem


than to grasp the solution of a large and complexproblem.

• It is easier to test segments of solutions, rather than the entire solution at once. This
method allows one to test the solution of each sub-problem separately until theentire
solution has beentested.

• It is often possible to simplify the logical steps of each sub-problem, so that when
taken as a whole, the entire solution has less complex logic and hence easier todevelop.

• A simplified solution takes less time to develop and will be morereadable.

• The program will be easier tomaintain.

3.10 DEBUGGING: -

Debugging is the process of finding and resolving defects or problems within a computer
program that prevent correct operation of computer software or a system.

Debugging tactics can involve interactive debugging, control flow analysis, unit testing,
integration testing, log file analysis, monitoring at the application or system level, memory
dumps, and profiling.

3.10.1 Debugging process

Normally the first step in debugging is to attempt to reproduce the problem. This can be a
non-trivial task, for example as with parallel processes or some unusual software bugs.
Also, specific user environment and usage history can make it difficult to reproduce the
problem.

After the bug is reproduced, the input of the program may need to be simplified to make it
easier to debug. For example, a bug in a compiler can make it crash when parsing some
large source file. However, after simplification of the test case, only few lines from the
original source file can be sufficient to reproduce the same crash. Such simplification can
be made manually, using a divide-and-conquer approach. The programmer will try to
remove some parts of original test case and check if the problem still exists. When
debugging the problem in a GUI, the programmer can try to skip some user interaction
from the original problem description and check if remaining actions are sufficient for
bugs to appear.

After the test case is sufficiently simplified, a programmer can use a debugger tool to
examine program states (values of variables, plus the call stack) and track down the origin
of the problem(s). Alternatively, tracing can be used. In simple cases, tracing is just a few
print statements, which output the values of variables at certain points of program
execution.

3.11 PROGRAM DESIGN AND DEVELOPMENT

Program design is the process that an organization uses to develop a program. It is most
often an iterative process involving research, consultation, initial design, testing and
redesign. A program design is the plan of action that results from that process.

Five reasons to do program design and development


You want to make sure that:

1 There is really a need for the program;


2The design you are considering actually meets the needs of the intended participants;
3The program you are considering has been shown to be effective;
4The program has been appropriately adapted to fit your context; and
5The program is actually working for the participants.

Considering the context

Some programs work for some people in some situations. When considering a particular
program
design, you need to ask questions such as:
■Is the design intended for the program’s geographical situation (urban, rural, remote)?
■Is the design intended for the program’s population group, taking into account their
unique
needs?
■Is the design part of a larger program delivery system? Does a system exist to support the
program?
■Does the type of organization delivering the program make a difference to how it is
perceived
by potential participants?
■How readily can the design be adapted to our context?
■Does it appropriately consider aspects of diversity?

3.12 TYPES OF ERRORS IN PROGRAMMING: -


The programmer should know the fact that there is very less chances that a program will
run perfectly in first time. It doesn’t matter how nicely the designing is done and how
much care is taken while coding. One can’t say that the program would 100% error free.
So the programmer has to make efforts to detect and rectify any kind of errors that are
present in the program. But before detecting and removing errors it is much more
necessary that the programmer should know about the types of errors in programming.
The types of errors are classified into four categories.
These are: syntax errors, logical errors, run-time errors and latent errors.

Syntax Errors

Any violation of rules and poor understanding of the programming language results in
syntax errors. The compiler can detect such errors. If syntax errors are present in the
program then the compilation of the program fails and is terminated after showing the list
of errors and the line
number where the errors have occurred. In some cases the line number may not exactly
indicate the correct place of the error. In some other cases, a single syntax error can result
in a long list of errors. Correction of one or two errors in the program may remove the
entire list of errors.

Run-time Errors

Runtime errors are the errors that occur during the execution of the program. Some
examples are, dividing by zero error, insufficient memory for dynamic memory allocation,
referencing an out-of-range array element. These are not detected by compiler while
compilation process. A program with these kinds of errors will run but produce erroneous
results or may cause termination of program. Detection and removal of a run-time error is
a difficult task.

Logical Errors

As the name itself implies, these errors are related to the logic of the program. Logical
errors are also not detected by compiler and cause incorrect results. These errors occur due
to incorrect translation of algorithm into the program, poor understanding of the problem
and a lack of clarity of hierarchy of operators. Consider following C statement:
if (a==b)
printf(“Equaln”);
When a and b are float types values, they rarely become equal due to truncation errors. The
printf call may not be executed at all. A statement like while(a!=b) might create an infinite
loop.

Latent Errors
Latent Errors are the ‘hidden’ errors that occur only when a particular set of data is used.
Consider below example:

result = (a+b)/(c-d);
An error occurs only when c and d are equal because that will make remainder zero (divide
by zero error). Such errors can be detected only by using all possible combinations of data.

3.13 DOCUMENTATION

Documentation is a continuous process, beginning with the problem definition.


Documentation involves collecting, organizing, storing, and other-wise maintaining a
complete record of the programs and other documents associated with the data processing
system.

Internal documentation is written in a program as comments.

External documentation is written in a place where people who need to use the software
can read about how to use the software. External documentation can be broken down into
library documentation, which describes tools that a programmer can use, and user
documentation, which is intended for users of an application.

The Navy has established documentation standards to ensure completeness and uniformity
for computer system information between commands and between civilian and navy
organizations. SECNAVINST 5233.1 (Series) establishes minimum documentation
requirements.

Local minimum documentation requirements are usually established by the head of the
data processing department/division. At most commands this function is delegated to the
project manager. The key to the minimum amount of documentation required by local
commands should be the amount that is required for replacement personnel to understand
input, processing, and output for each program or system for which they will be
responsible. A documentation package should include:

1. A definition of the problem. Why was the program written? What were the objectives?
Who requested the program, and who approved it? These are the types of questions that
should be answered.

2. A description of the system. The system environment (hardware, software, and


organization) in which the program functions should be described (including systems
flowcharts). General systems specifications outlining the scope of the problem, the form
and type of input data to be used, and the form and type of output required should be
clearly defined.

3. A description of the program. Programming flowcharts, program listings, program


controls, test data and test results, storage dumps—these and other documents that describe
the program and give a historical record of problems and/or changes should be included.

4. Operator instructions. Items that should be included are computer switch settings,
loading and unloading procedures, and starting, running, and termination procedures.

Implementation

After the documentation has been completed, and the user has reviewed and accepted the
test output, the project request is submitted to upper manage-ment, usually the ADP
department head, for production approval. Once upper management has approved the
program, it can be put into production. If a program is to replace a program in an existing
system, it is generally wise to have a period of parallel processing; that is, the job
application is processed both by the old program and by the new program. The purpose of
this period is to verify processing accuracy and completeness. Once the program is in
production it may be necessary to make modifications to the program to satisfy changing
requirements. This is another important duty of the programmer, and it is not unusual to
find programmers spending 25 percent of their time on this program maintenance activity.
In some installations, there are programmers who do nothing but maintain production
programs.

SUMMARY

The first step in the solution of any problem involves a fundamental but often overlooked
concept—a thorough understanding of the problem. The second step in successful problem
solving involves creating a flowchart showing the steps required to solve the problem.

Flowcharting is a pictorial means of representing a procedural solution to a problem in


which different shaped symbols are used to represent opera-tions, data, flow, equipment
and so forth. There are two types of flowcharts— system (data) and programming. The
tools of flowcharting are: (1) fundamental symbols; (2) graphic symbols; (3) flowcharting
template; and (4) flowcharting worksheet.

The problem definition and flowchart development steps must be done prior to sitting
down to code the computer instructions to solve a problem. Regardless of the language
used, there are strict rules you must adhere to with regard to punctuation and statement
structure when coding a program. Once the program is coded, there are several phases that
must be done before it can be put into production. These are desk-checking, debugging,
testing, documentation and finally, implementation.

3.14 PROGRAMMING METHODOLOGIES: -


Programming refers to the method of creating a sequence of instructions to enable
the computer to perform a task. It is done by developing logic and then writing instructions
in a programming language. A program can be written using various programming
practices available. A programming practice refers to the way of writing a program and
is used along with coding style guidelines. Some of the commonly used programming
practices include top-down programming, bottom-up programming, structured
programming, and information hiding.
Fig 3.4: Programming Methodologies

3.14.1 TOP-DOWN PROGRAMMING


Top-down programming focuses on the use of modules. It is therefore also known as
modular programming. The program is broken up into small modules so that it is easy to
trace a particular segment of code in the software program. The modules at the top level
are those that perform general tasks and proceed to other modules to perform a particular
task. Each module is based on the functionality of its functions and procedures. In this
approach, programming begins from the top level of hierarchy and progresses towards the
lower levels. The implementation of modules starts with the main module. After the
implementation of the main module, the subordinate modules are implemented and the
process follows in this way. In top-down programming, there is a risk of implementing
data structures as the modules are dependent on each other and they nave to share one or
more functions and procedures. In this way, the functions and procedures are globally
visible. In addition to modules, the top-down programming uses sequences and the nested
levels of commands.

3.14.2 BOTTOM-UP PROGRAMMING


Bottom-up programming refers to the style of programming where an application is
constructed with the description of modules. The description begins at the bottom of the
hierarchy of modules and progresses through higher levels until it reaches the top. Bottom-
up programming is just the opposite of top-down programming. Here, the program
modules are more general and reusable than top-down programming.
It is easier to construct functions in bottom-up manner. This is because bottom-up
programming requires a way of passing complicated arguments between functions. It takes
the form of constructing abstract data types in languages such as C++ or Java, which can
be used to implement an entire class of applications and not only the one that is to be
written. It therefore becomes easier to add new features in a bottom-up approach than in a
top-down programming approach.
3.14.3 STRUCTURED PROGRAMMING
Structured programming is concerned with the structures used in a computer program.
Generally, structures of computer program comprise decisions, sequences, and loops.
The decision structures are used for conditional execution of statements (for example, 'if
statement). The sequence structures are used for the sequentially executed statements.
The loop structures are used for performing some repetitive tasks in the program.
Structured programming forces a logical structure in the program to be written in an
efficient and understandable manner. The purpose of structured programming is to make
the software code easy to modify when required. Some languages such as Ada, Pascal, and
dBase are designed with features that implement the logical program structure in the
software code. Primarily, the structured programming focuses on reducing the following
statements from the program.
1. 'GOTO' statements.
2. 'Break' or 'Continue' outside the loops.
3. Multiple exit points to a function, procedure, or subroutine. For example, multiple 'Return'
statements should not be used.
4. Multiple entry points to a function, procedure, or a subroutine.
Structured programming generally makes use of top-down design because program
structure is divided into separate subsections. A defined function or set of similar functions
is kept separately. Due to this separation of functions, they are easily loaded in the
memory. In addition, these functions can be reused in one or more programs. Each module
is tested individually. After testing, they are integrated with other modules to achieve an
overall program structure. Note that a key characteristic of a structured statement is the
presence of single entry and single exit point. This characteristic implies that during
execution, a structured statement starts from one defined point and terminates at another
defined point.

In structured programming design, programs are broken into different functions these
functions are also known as modules, subprogram, subroutines and procedures.

Each function is design to do a specific task with its own data and logic. Information can
be passed from one function to another function through parameters. A function can have
local data that cannot be accessed outside the function’s scope. The result of this process is
that all the other different functions are synthesized in an another function. This function is
known as main function. Many of the high level languages supported structure
programming.

Structured programming minimized the chances of the function affecting another. It


supported to write clearer programs. It made global variables to disappear and replaced by
the local variables. Due to this change one can save the memory allocation space occupied
by the global variable. Its organization helped to understand the programming logic easily.
So that one can easily understand the logic behind the programs. It also helps the new
comers of any industrial technology company to understand the programs created by their
senior workers of the industry. It also made debugging easier.

Functional abstraction was introduced with structured programming. Abstraction simply


means that how able one can or we can say that it means the ability to look at something
without knowing about its inner details. In structured programming, it is important to know
that a given function satisfies its requirement and performs a specific task. Weather How
that task is performed is not important.

3.14.3.1 Advantages of structured programming: -

The following are the different advantages of structured programming

1. It is user friendly and easy to understand.


2. Similar to English vocabulary of words and symbols.
3. It is easier to learn.
4. They require less time to write.
5. They are easier to maintain.
6. These are mainly problem oriented rather than machine based.
7. Program written in a higher level language can be translated into many machine languages
and therefore can run on any computer for which there exists an appropriate translator.
8. It is independent of machine on which it is used i.e. programs developed in high level languages can
be run on any computer.

3.14.3.2 Disadvantages of structured programming: -

The following are the disadvantages of structured programming:

1. A high level language has to be translated into the machine language by translator and thus a
price in computer time is paid.
2. The object code generated by a translator might be inefficient compared to an equivalent
assembly language program.
3. Data type are proceeds in many functions in a structured program. When changes occur in
those data types, the corresponding change must be made to every location that acts on
those data types within the program. This is really a very time consuming task if the
program is very large.

Information Hiding
Information hiding focuses on hiding the non-essential details of functions and code in a
program so that they are inaccessible to other components of the software. A software
developer applies information hiding in software design and coding to hide unnecessary
details from the rest of the program. The objective of information hiding is to minimize
complexities among different modules of the software. Note that complexities arise when
one program or module in software is dependent on several other programs and modules.
Information hiding is implemented with the help of interfaces. An interface is a medium of
interaction for software components that are using the properties of the software modules
containing data. The implementation of interfaces depends on the syntax and process.
Examples of interface include constants, data types, types of procedures, and so on.
Interfaces protect other parts of programs when a software design is changed.
Basis for
Linker Loader
Comparison
It generates the executable module of a It loads the executable module to the main
Basic
source program. memory.
It takes as input, the object code generated It takes executable module generated by a
Input
by an assembler. linker.
It combines all the object modules of a
It allocates the addresses to an executable
Function source code to generate an executable
module in main memory for execution.
module.
Absolute loading, Relocatable loading and
Type/Approach Linkage Editor, Dynamic linker.
Dynamic Run-time loading.

Basis for
Compiler Assembler
Comparison
Generates the assembly language code or directly the Generates the relocatable machine
Basic
executable code. code.
Input Preprocessed source code. Assembly language code.
The compilation phases are lexical analyzer, syntax
Assembler makes two passes over
Phases/ Passes analyzer, semantic analyzer, intermediate code
the given input.
generation, code optimization, code generation.
The relocatable machine code
The assembly code generated by the compiler is a
Output generated by an assembler is
mnemonic version of machine code.
represented by binary code.
Basis for
Top-down Approach Bottom-up Approach
comparison
Solves the fundamental low-level
Breaks the massive problem into smaller
Basic problem and integrates them into a larger
sub problems.
one.
Examine what data is to be encapsulated,
Process Sub modules are solitarily analyzed. and implies the concept of information
hiding.
Needs a specific amount of
Communication Not required in the top-down approach.
communication.
Redundancy Contain redundant information. Redundancy can be eliminated.
Structure/procedural oriented programming Object-oriented programming languages
Programming
languages (i.e. C) follows the top-down (like C++, Java, etc.) follows the bottom-
languages
approach. up approach.
Module documentation, test case creation,
Mainly used in Testing
code implementation and debugging.
3.15 IMPORTANT QUESTIONS

1. Define compiler, interpreter, assembler, linker and loader.


2. What are the characteristics of a good programming language?
3. What is machine language? How it differs from assembly language?
4. Explain the types of programming language with example.
5. Define the meaning of problem. Explain the concept of problem solving.
6. Differentiate between top-down and bottom-up programming language.
7. What are the advantages and disadvantages of structured programming?
8. Define algorithm. Also explain the merits and demerits of algorithms.
9. Explain the classification of errors in programming language.
10. Differentiate between logical error and syntax error.
11. What are latent errors? Explain with the help of an example.
12. Define debugging. What are the necessary steps for correction of different types of errors?
13. What is natural language? How it is different from programming language?
14. What steps should be considered before planning the computer program?
15. Explain the generations of programming language.

You might also like