0% found this document useful (0 votes)
283 views49 pages

CMP 211 - Computer Programming

This document discusses computer programming and algorithms. It provides an overview of: - The programming process, which involves analyzing problems, designing algorithms, and implementing solutions in code. - Common programming concepts like variables, conditionals, loops, functions, and object-oriented programming. - Ways to represent algorithms, including pseudocode, flowcharts, and programming languages. - The seven steps of problem solving: defining the problem, gathering information, establishing criteria, generating solutions, analyzing solutions, comparing solutions, and implementing a decision.

Uploaded by

veneraljedexx1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
283 views49 pages

CMP 211 - Computer Programming

This document discusses computer programming and algorithms. It provides an overview of: - The programming process, which involves analyzing problems, designing algorithms, and implementing solutions in code. - Common programming concepts like variables, conditionals, loops, functions, and object-oriented programming. - Ways to represent algorithms, including pseudocode, flowcharts, and programming languages. - The seven steps of problem solving: defining the problem, gathering information, establishing criteria, generating solutions, analyzing solutions, comparing solutions, and implementing a decision.

Uploaded by

veneraljedexx1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 49

CMP 211: COMPUTER PROGRAMMING I (3 UNITS)

PROGRAMMING METHODOLOGY

Computer programming is a process that leads from an original formulation of a computing


problem to executable programs. It involves activities such as analysis, understanding and
generically solving such problems resulting in an algorithm which is later translated into a
programming language where it is implemented. The purpose of programming is to find a
sequence of instructions that will automate performing a specific task or solve a given problem.
A program is a set of detailed instructions that tells the computer what to do.

Computer programming is divided into two phases:

 Problem Solving Phase (Make an ordered sequence of steps that solves a problem –
Algorithm).
 Implementation Phase (Implement using a programming language).

System Development Life Cycle

Most IT projects work in cycles. First, the need of the computer users must be analyzed. The task
is handled by a professional system analyst who asks users exactly what they would like the
system to do and draws out plans on how this can be implemented on a real computer based
system. The programmer takes the specification from the system analyst and converts it into
actual computer programs. At this point, testing by using inputs from the users so that what is
actually produced by the programmer should be what they asked for. Finally, Implementation;
and as users starts using the program, they will suggest new improvements and the whole process
starts all over again. The phases are normally:

 Problem Analysis
 Feasibility Studies
 Design
 Coding
 Testing and Debugging
 Implementation

PROBLEM CONCEPT

Programming is all about solving problems. What is a problem? Problem is an existing situation
in which what you want to happen is different from what actually is happening. Problem solving
begins with decision making. Decision making is a process that involves sound judgment, logical
reasoning and wise application of available resources.

Seven Problem Solving Steps

1. Identify the problem (who, what, when, where and why)


The first step in problem solving is recognizing and defining the problem. To determine the
problem, you must define both its scope and limitations. Its important to give enough time
in this step before continuing with the problem solving process. You can do this by asking
questions on whom the problem affects, what is affected, when the problem occurred,
where the problem is and how the problem occurred.
2. Gather information (facts, assumptions and interests)
Information gathering begins with defining the problem and continues throughout the
solving process. Gather information from primary sources including interviews and letters
of request for specific information, regulations, and policies. From these resources, you
will obtain facts which are verifiable pieces of information and gather assumptions as well
and try to confirm or deny the validity of your assumptions throughout the problem solving
process.
3. Develop Criteria (screening and evaluation)
Criterion is a standard, rule, or test by which you can judge something. Criteria are based
on facts or assumptions. Screen criteria to ensure they are suitable, feasible, acceptable,
distinguishable and complete. In evaluating criteria, include; the criterion name, define the
feature to be evaluated, state the unit of measurement and define the benchmark.
4. Generate Possible Solutions (suitable, feasible, acceptable and complete)
This is the phase for brainstorming in which ideas for solutions are sought even from team
members. Be open to as many options as possible, after considering various solutions,
summarize the potential solution.
5. Analyze possible solutions (Benchmark)
Analyze each solution to determine its merits and shortcomings. What are the pros and
cons? Use the screening criteria to make sure the proposed solution meets your minimum
requirements and then benchmark to decide whether the proposed solution will result in the
desired state.
6. Compare possible solutions (Determine the best solution)
Determine the best solution by comparing each possible solution against the others. Select
the solution that best solves the problem based on your evaluation criteria.
7. Make and implement the Decision: once the preferred solution has been identified, make
efforts for the implementation.

Steps in Programming

 Identify the problem


 Produce a general algorithm (one can use pseudocode& flowchart)
 Refine your steps until you get to an easy sequence.
 Develop the computer program. Test and run it on the computer

ALGORITHM DEVELOPMENT

Algorithm is a finite sequence of steps expressed for solving a problem. It is a process that
performs some sequence of operations in order to solve a given problem. Computer needs
precise and well-defined instructions for finding solution to problems. If there is any ambiguity,
the computer will not yield the right results. It is essential that all the stages of solution of a
given problem be specified in details, correctly and clearly moreover, the steps must also be
organized rightly so that a unique solution is obtained. They can be used for calculations, data
processing and many other fields. They are important because they serve as the systematic
procedures that computers require.

Reasons for using Algorithms

 Efficiency: certain types of problems occur often in computing. Efficient algorithms must
be used to solve such problems considering the time and cost factor involved in each
algorithm.
 Abstraction: it provides a level of abstraction in solving problems because many
seemingly complicated problems can be distilled into simpler ones for which well-known
algorithms exists.
 Reusability: algorithms are often reusable in many different situations. Since well-known
algorithm are the generalizations of more complicated ones, and since many complicated
problems can be distilled into simpler ones, solving them becomes possible.
Features of a good Algorithm

i. It should be simple
ii. It should be clear with no ambiguity
iii. It should head to unique solution of the problem
iv. It should involve a finite number of steps to arrive at a solution
v. It should have the capability to handle unexpected situation.
Methods of representing Algorithm
Algorithms can be expressed in many different notations, including natural languages, pseudo
code, flowcharts and programming languages.

Natural language can be ambiguous and verbal and are rarely used for complex or technical
algorithms. Pseudo code and Flowcharts are structured ways to express algorithms that avoid
ambiguities common in natural language statements while remaining independent of a particular
implementation language. Programming languages are primarily intended for expressing
algorithms in a form that can be executed by a computer but are often used to document
algorithm.

PSEUDOCODE

Pseudo code is an artificial and informal language that helps programmers develop algorithms. It
is the English-like representation of program logic. Pseudo code may be an informal English,
combinations of computer languages and spoken language. Whatever works for you.

Example 1:

Write an algorithm to determine a student’s final grade and indicate whether it is pass or fail. The
final grade is calculated as the average of four marks.

Pseudocode Solution:
 Input a set of 4 marks
 Calculate their average by summing and dividing by 4
 if average is below 60

 Print “FAIL”
 else
 Print “PASS
Detailed Algorithm
Step 1: Input M1, M2, M3, M4
Step 2: GRADE ← (M1+M2+M3+M4)/4
Step 3: if (GRADE < 60) then
Print “FAIL”
Else
Print “PASS”
End if
FLOWCHART
A Flowchart is graphical way to represent algorithm using standard symbols. It shows logic
solution, emphasizes individual steps and their interconnections. A flowchart must have a start
and stop. Steps in a flowchart must connect. You can’t leave a step “hanging” with no
connection. e.g. control flow from one action to the next.
FLOWCHART SYMBOLS

Alternatively, to distinguish input from output, the hybrid symbol can be used for only output
operations. However, either the parallelogram or the hybrid can represent output operations.
General Rules for flowcharting

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

The flowchart for Example 1 is shown below.

Example 2:

Write an algorithm and draw a flowchart to convert the length in feet to centimeter.

Pseudocode:

Input the length in feet (Lft)

Calculate the length in cm (Lcm) by multiplying LFT with 30


Print length in cm (LCM)

Example 3. Design an algorithm and the corresponding flowchart for adding the test
scores as given below:
26, 49, 98, 87, 62, 75
a) Algorithm
1. Start
2. Sum = 0
3. Get the first testscore
4. Add first testscore to sum
5. Get the second testscore
6. Add to sum
7. Get the third testscore
8. Add to sum
9. Get the Forth testscore
10. Add to sum
11. Get the fifth testscore
12. Add to sum
13. Get the sixth testscore
14. Add to sum
15. Output the sum
16. Stop
The algorithm and flowchart should always have a Start step at the beginning of the algorithm or
flowchart and at least one stop step at the end, or anywhere in the algorithm or flowchart. Since
we want the sum of six test score, then we should have a container for the resulting sum. In this
example, the container is called sum and we make sure that sum should start with a zero value
by step 2.
The problem with this algorithm is that, some of the steps appear more than once, i.e. step 5 get
second number, step 7, get third number, etc. One could shorten the algorithm as well as the
flowchart as follows:
1. Start
2. Sum = 0
3. Get a value
4. sum = sum + value
5. Go to step 3 to get next Value
6. Output the sum
7. Stop

This algorithm and its corresponding flowchart are a bit shorter than the first one. In this
algorithm, step 3 to 5 will be repeated, where a number is obtained and added to sum. Similarly,
the flowchart indicates a flow line being drawn back to the previous step indicating that the
portion of the flowchart is being repeated. One problem indicates that these steps will be
repeated endlessly, resulting in an endless algorithm or flowchart. The algorithm needs to be
improved to eliminate this problem. In order to solve this problem, we need to add a last value to
the list of numbers given. This value should be unique so that, each time we get a value, we test
the value to see if we have reached the last value. In this way our algorithm will be a finite
algorithm which ends in a finite number of steps as shown below. There are many ways of
making the algorithm finite.
The new list of numbers will be 26, 49, 498, 9387, 48962, 1, -1. The value –1 is a unique
number since all other numbers are positive.
1. Start
2. Sum = 0
3. Get a value
4. If the value is equal to –1, go to step 7
5. Add to sum ( sum = sum + value)
6. Go to step 3 to get next Value
7. Output the sum
8. Stop
Corresponding flowchart

Example 4.

Write an algorithm and draw a flowchart that will read the two sides of a rectangle and
calculate its area.
Pseudocode:
Input the width (W) and Length (L) of a rectangle
Calculate the area (A) by multiplying L with W
Print A
Example 5.
Write an algorithm and draw a flowchart that will calculate the roots of a
quadratic equation. ax2 + bx + c = 0

Hint: d = sqrt (b2 – 4ac ), and the roots are: x1 = (–b + d)/2a and x2 = (–b – d)/2a

Pseudocode:

Input the coefficients (a, b, c) of the quadratic equation


Calculate d
Calculate x1
Calculate x2
Print x1 and x2
BASIC CODING STRUCTURES

All computer programs can be coded using three logic structures (or programs) or combinations
of these structures:

1. Simple sequence

2. Selection

3. Repetition

The three structures are useful in a disciplined approach to programming because

1.The program is simplified. Only the three building blocks are used, and there is a single point
of entry into the structure and a single point of exit.

2. The three coding structures allow a program to be read from top to bottom making the logic of
the program more visible for checking and for maintenance.

Simple Sequence

The simple-Sequence structure consists of one action followed by another. In other words, the
flow of control is first to perform operation A and then to perform operation B. A simple
sequence is flowcharted as two process symbols connected by a flow line. This can be observed
in examples 2, 4, & 5.

Selection

The selection structure consists of a test for condition followed by two alternative decision paths
for the program to follow. The program selects one of the program control paths depending on

the test of the condition. After performing one of two paths, the program control returns to a
single point. This pattern can be termed IF .. ELSE because the logic can be stated (for condition
P and operations C and D): IF P (is true), perform C; ELSE perform D. A flowchart for the
selection structure consists of a decision symbol followed by two paths, each with a process
symbol, coming together following the operation symbols.

DECISION STRUCTURES
The expression A>B is a logical expression
it describes a condition we want to test
if A>B is true (if A is greater than B) we take the action on left
print the value of A
if A>B is false (if A is not greater than B) we take the action on right
print the value of B
IF–THEN–ELSE STRUCTURE
The structure is as follows
If condition then
true alternative
else
false alternative
endif

Example 6.Write an algorithm that reads two values, determines the largest value and prints the
largest value with an identifying message.
ALGORITHM
Step 1: Input VALUE1, VALUE2
Step 2: if (VALUE1 > VALUE2) then
MAX ← VALUE1
else
MAX ← VALUE2
endif
Step 3: Print “The largest value is”, MAX

NESTED IF STATEMENTS
One of the alternatives within an IF–THEN–ELSE statement may involve further IF–THEN–
ELSE statements.
Example 7
Write an algorithm that reads three numbers and prints the value of the largest number.

Detailed Algorithm
**Draw the flowchart for Example 6 above.
Example 8:
Write a Pseudo code for the algorithm whose flowchart is below. What does the algorithm
actually do?

Exercise: Write an algorithm and draw a flowchart for a program that prints even numbers in the
range of [1 – 100]

Iteration Logic (Repetitive flow)

The repetition structure can also be called a loop. In a loop, an operation or a set of operation is
repeated until some condition is satisfied. A typical flowchart of this logic can be seen below:

Algorithm example for iteration or repetition


Example 9

let us take 10 sets of numbers each set containing three. The problem is to get the biggest
number in each set and print it.

Algorithm

Step 1: Read the total number of sets

Step 2: Initialize the number of the set as N=1

Step 3: Read three numbers of a set say A, B, C.

Step 4: Compare A with B and choose the bigger.

Step 5: Compare the bigger number with C and Choose the biggest

Step 6: Print the biggest number,

Step 7: Increment the number of the set by 1 (N=N+1)

Step 8: Check whether we have exceeded 10. If not Go – To step 3. Otherwise.

Step 9: STOP

The Repetition structure can be implemented using


• Repeat Until Loop
• The While Loop
• The For Loop
The Repeat Until loop.
The syntax is
REPEAT
A statement or block of statements
UNTIL a true condition
Example 10: A program segment repeatedly asks for entry of a number in the range 1 to
100 until a valid number is entered.
REPEAT
DISPLAY “Enter a number between 1 and 100”
ACCEPT number
UNTIL number < 1 OR number > 100
The WHILE loop
The second type of iteration we will look at is the while iteration. This type of conditional
loop tests for terminating condition at the beginning of the loop. In this case no action is
performed at all if the first test causes the terminating condition to evaluate as false.

The syntax is
WHILE (a condition is true)
A statement or block of statements
ENDWHILE
Example 11: a program segment to print out each character typed at a keyboard until the
character ‘q’ is entered.
WHILE letter <> ‘q’
ACCEPT letter
DISPLAY “The character you typed is”, letter
ENDWHILE
The FOR Loop
The third type of iteration, which we shall use when the number of iterations is known in
advance, is a for loop. This, in its simplest form, uses an initialization of the variable as a
starting point, a stop condition depending on the value of the variable. The variable is
incremented on each iteration until it reaches the required value.
The pseudo-code syntax will be:
FOR (starting state, stopping condition, increment)
Statements
ENDFOR
Example 12: Write a program to calculate the sum and average of a series of numbers.
The pseudo-code solution is:
DISPLAY “How many numbers do you want to input”
ACCEPT count
SUM = 0
FOR (n = 1, n <= count, n + 1)
DISPLAY “Input the number from your list”
ACCEPT number
SUM = sum + number
ENDFOR
Average = sum / count
DISPLAY “The sum of the numbers is “, sum
DISPLAY “Average of the numbers is “, average
Exercise: draw the corresponding flowchart.
Program Design
Here the input in this phase is a specification of what the program is required to do. During the
phase, the design decisions are made as to how the program will meet these requirements and the
output of the phase is a description of the program in some form that provides a suitable basis for
subsequent implementation. The design phase is divided into two sub phases, one of architectural
design and the detailed design. The architectural design produces a description of the program at
a gross level; it is normally given in terms of the major components of the program and their
inter-relationships, the main algorithms that these components employ, and the major data
structure. The detailed design then refines the architectural design to the state where actual
implementation can begin.
Coding
After flowcharting or pseudo-coding the program logic, the next step is to write the program in
any desired programming language. A program which is written in the language of the computer
is called an object program and it is a collection of bits. It is not easy to write programs directly
in machine language codes (bits of 0 and 1). Sometimes Assembly language may be used; even
though it is easier to write compare to machine language, it is still very complicated. Source
program can also be written in codes covered in statements. Such code is called a high level
language. The source program is read into the computer as data and another program called a
compiler is employed to convert the source program into machine language instructions of the
object program. There are so many high level programming languages; amongst them are
BASIC, FORTRAN, Pascal, C, C++ etc.
Testing and Debugging
Testing means verifying correct behavior. This can be done at all stages of module development:
requirement analysis, interface design, algorithm design, implementation and integration with
other modules. Testing is done majorly prior before the implementation phase. Implementation
can also be tested using correctness proofs, code tracing, and peer reviews.
Implementation
This phase is the realization of the technical specification or algorithm as a program. At this
point the user starts using the program. Implementation varies depending on the type of
implementation preferred. The different implementation types include:
Parallel Running: Here the new system and the old system run side by side. Note that the old
system might be a manual process or an existing system that needed to be improved upon. The
same data are inputted and same processes are performed. Their outputs are compared to prove
the reliability of the new system. If the new system is found satisfactory, the old system is
replaced by the new system.
Direct Change Over: Here the new system replaces the old system directly. Although it looks
simple but it takes a lot of planning. All the files have to ready to load, all the workers need to
have been trained in advance and the system must have been properly tested.
Phased Implementation: This is a changeover process that takes place in stages. The system is
implemented and observed for just a sector in the organization per time but eventually all other
sectors will be phased in, and everything would be running as ought to
Documentation
Having tested the program and being satisfied that it is performing its functions. Program
documentation includes hardcopy or electronic manuals that enable users, program developers
and operators to interact successfully with a program user. Documentation now gives a
comprehensive procedural description of a program. It shows how the software is written.
Program documentation has the capability to sustain any later maintenance or development of
the program. It describes exactly what a program does by mentioning about requirements of the
input data and the effect of performing a programming task. Most common examples are the
instruction manuals for a software product, which is given to the end-users.
There is another type of program documentation that is written for the sake of the programmer
who writes the actual software and may have to modify it or use it as part of another program
which they will write in the future.
Outline:

 Software development methodology, fundamental design concepts and principles,


structured design, testing and debugging tools
 Introduction to problem solving methods and algorithm development, designing, coding,
debugging and documenting programs using techniques of a good programming language
style, programming language and programming algorithm development.

SOFTWARE DEVELOPMENT METHODOLOGY

Every profession has its standard protocols, formats and processes that should be followed by all
its professionals in executing their occupation. The purpose of this is to ensure consistency
among its professionals, and to a large extent – make whatever work done in that profession
easier to assess or evaluate. These protocols or formats point out errors and make better planning
done. Software engineering or development as a field is not excluded. There are certain
approaches to the field that make software engineering easier to work on. Those approaches
could be called software development methodology. It breaks down the development of
software into different stages. There is a number of software development methodologies
commonly used presently. They include but are not limited to waterfall (also known as
traditional methodology), iterative and incremental methodology, prototyping, rapid application
development etc.

Definition:

1. Software development methodology is “splitting of software development work into


distinct phases (or stages) containing activities with the intent of better planning and
management.” Software development methodology is also known by the following terms:
system development methodology, software development process, software process,
software development life cycle
2. According to IT knowledge portal, a software development methodology or system
development methodology in software engineering is a framework that is used to
structure, plan, and control the process of developing an information system.

Types of Software development methodology (with emphasis on 2)

1. Waterfall (Traditional) methodology


2. Prototyping methodology
3. Agile software development methodology
4. Rapid application development
5. Spiral model
6. Feature driven development
7. Scrum development methodology
8. Extreme programming methodology etc.

We would be considering two popular software development methodologies: Waterfall


methodology and Prototyping methodology.

1. Waterfall methodology: This is also known as linear-sequential life cycle model. This is a
popular software development methodology and is often considered the classic approach.
Waterfall development has distinct goals for each phase of development where each phase is
completed for the next one is started and there is no turning back. This model has at least 6
stages and they are Requirement gathering and analysis, System design, Implementation,
Testing, Deployment of System, and Maintenance. The output of one phase becomes the
input of the next sequential phase. It is important to note that each phase must be planned
thoroughly and there is no revision or going back to a stage once that stage is done. This
displays a glaring disadvantage – the system is too rigid but then again it is the earliest
known software development methodology and even at that has some really good
advantages. Even if other features are to be added at a later time, you ignore and can only
maintain the system. However, this approach has some advantages that you would be seeing
shortly. Consider the diagram below for perhaps better explanation.
Phase 1 – Requirement gathering and analysis: Discussions about what the client needs and
wants developed is done in this stage. All possible requirements of the system to be developed
are captured in this phase and documented in a requirement specification document. This is a
crucial stage because the system would be designed using (to the letter) the requirement
specification.

Phase 2 – System design: Here, the overall system architecture is developed based on the
requirement specification. Hardware and system requirements are specified also in this phase.

Phase 3 – Implementation: With inputs from system design, the system is first developed in
small programs called units, which are integrated in the next phase. Each unit is developed and
tested for its functionality which is referred to as Unit Testing.

Phase 4 – Integration and Testing: The units are integrated together and tested as a whole
entity now. Post integration the entire system is tested for any faults and failures.

Phase 5 – Deployment of system: As soon as all testing is done, the system is released for use to
the market or customer environment.

Phase 6 – Maintenance: General fixing of issues in the user/client environment and releases of
better working versions is done in this stage.

Pros of Waterfall model.

 Easy to understand and functional


 Simple enough to handle as model is rigid
 Saves significant amount of time
 Allows for easy testing and analysis
Cons of Waterfall model.

 Only matches precise needs


 Not applicable for maintenance projects
 Does not allow editing in the testing phase
 No option to know possible outcome of a project
 Not excellent for long and ongoing projects
2. Prototyping model: This model initiates developers towards making only the sample of the
proposed solution to validate or affirm its functional essence to the customers, and make
essential changes before creating the authentic final solution.
In fact, the best part of this methodology is that it tends to resolve a set of diversifying issues
occurring with the waterfall method. See the diagram below.
Pros of Prototyping model

 Gives clear idea about the functional process of the software


 Reduces the risk of failure in a software functionality
 Assists well in requirement gathering and the overall analysis
 Increased user involvement in the product even before its implementation.
 Since a working model of the system is displayed, the users get a better understanding of
the system being developed.
 Reduces time and cost as the defects can be detected much earlier.
 Quicker user feedback is available leading to better solutions.
 Missing functionality can be identified easily
Cons of Prototyping model
 More expensive to build
 Excessive involvement of client can affect processing
 Too many changes affect the workflow of the software
 Risk of insufficient requirement analysis owing to too much dependency on the
prototype.
 Users may get confused in the prototypes and actual systems.
 Practically, this methodology may increase the complexity of the system as scope of the
system may expand beyond original plans.
 The effort invested in building prototypes may be too much if it is not monitored
properly.
FUNDAMENTAL DESIGN CONCEPTS AND PRINCIPLES
IEEE defines software design as “a process of defining, the architecture, components, interfaces,
and other characteristics of a system or component and the result of that process.” Once the
requirements document for the software to be developed is available, the software design phase
begins. While the requirement specification activity deals entirely with the problem domain,
design is the first phase of transforming the problem into a solution. In the design phase, the
customer and business requirements and technical considerations all come together to formulate
a product or a system.
The design process comprises a set of principles, concepts and practices, which allow a software
engineer to model the system or product that is to be built. This model, known as design model,
is assessed for quality and reviewed before a code is generated and tests are conducted. The
design model provides details about software data structures, architecture, interfaces and
components which are required to implement the system. The next few lines would describe the
design elements that are required to develop a software design model. It would also discuss the
design patterns and various software design notations used to represent a software design.
Developing design is a cumbersome process as most expansive errors are often introduced in
this phase. Moreover, if these errors get unnoticed till later phases, it becomes more
difficult to correct them. Therefore, a number of principles are followed while designing the
software. These principles act as a framework for the designers to follow a good design practice.
Principles of Software design

1. Software design should correspond to the analysis model: many times a design
element corresponds to many requirements; it becomes important to therefore know how
the intended design model would satisfy all the requirements represented by the analysis
model.

2. Choose the right programming paradigm: A programming paradigm describes the


structure of the software system. Depending on the nature and type of application,
different programming paradigms such as procedure oriented, object-oriented, and
prototyping paradigms can be used. The paradigm should be chosen keeping constraints
in mind such as time, availability of resources and nature of user's requirements.
3. Software design should be uniform and integrated: Software design is considered
uniform and integrated if the interfaces are properly defined among the design
components. For this, rules, format, and styles are established before the design team
starts designing the software.
4. Software design should be flexible: Software design should be flexible enough to adapt
changes easily. To achieve the flexibility, the basic design concepts such as abstraction,
refinement, and modularity should be applied effectively.
5. Software design should ensure minimal conceptual (semantic) errors: The design
team must ensure that major conceptual errors of design such as ambiguousness and
inconsistency are addressed in advance before dealing with the syntactical errors present
in the design model.
6. Software design should be structured to degrade gently: Software should be designed
to handle unusual changes and circumstances, and if the need arises for termination, it
must do so in a proper manner so that functionality of the software is not affected.
7. Software design should represent correspondence between the software and real-
world problem: The software design should be structured in such a way that it always
relates with the real-world problem.
 Software reuse: Software engineers believe on the phrase: 'do not reinvent the
wheel'. Therefore, software components should be designed in such a way that
they can be effectively reused to increase the productivity.
9. Designing for testability: A common practice that has been followed is to keep the
testing phase separate from the design and implementation phases. That is, first the
software is developed (designed and implemented) and then handed over to the testers
who subsequently determine whether the software is fit for distribution and subsequent
use by the customer. However, it has become apparent that the process of separating
testing is seriously flawed, as if any type of design or implementation errors are found
after implementation, then the entire or a substantial part of the software requires to be
redone. Thus, the test engineers should be involved from the initial stages. For example,
they should be involved with analysts to prepare tests for determining whether the user
requirements are being met.
10. Prototyping: Prototyping should be used when the requirements are not completely
defined in the beginning. The user interacts with the developer to expand and refine the
requirements as the development proceeds. Using prototyping, a quick 'mock-up' of the
system can be developed. This mock-up can be used as a effective means to give the
users a feel of what the system will look like and demonstrate functions that will be
included in the developed system. Prototyping also helps in reducing risks of designing
software that is not in accordance with the customer's requirements.
Note that design principles are often constrained by the existing hardware configuration,
the implementation language, the existing file and data structures, and the existing
organizational practices. Also, the evolution of each software design should be
meticulously designed for future evaluations, references and maintenance.
SOFTWARE DESIGN CONCEPTS
1. Abstraction: IEEE defines abstraction as 'a view of a problem that extracts the
essential information relevant to a particular purpose and ignores the remainder of the
information.' The concept of abstraction can be used in two ways: as a process and as an
entity. As a process, it refers to a mechanism of hiding irrelevant details and representing
only the essential features of an item so that one can focus on important things at a time.
As an entity, it refers to a model or view of an item.
2. Architecture: Software architecture refers to the structure of the system, which is
composed of various components of a program/ system, the attributes (properties) of
those components and the relationship amongst them. The software architecture enables
the software engineers to analyze the software design efficiently. In addition, it also helps
them in decision-making and handling risks. The software architecture does the following
a. Provides an insight to all the interested stakeholders that enable them to
communicate with each other
b. Highlights early design decisions, which have great impact on the software
engineering activities (like coding and testing) that follow the design phase
c. Creates intellectual models of how the system is organized into components and
how these components interact with each other.
3. Patterns: A pattern provides a description of the solution to a recurring design problem
of some specific domain in such a way that the solution can be used again and again. The
objective of each pattern is to provide an insight to a designer who can determine the
following.
a. Whether the pattern can be reused
b. Whether the pattern is applicable to the current project
c. Whether the pattern can be used to develop a similar but functionally or
structurally different design pattern.
4. Modularity: Modularity is achieved by dividing the software into uniquely named and
addressable components, which are also known as modules. A complex system (large
program) is partitioned into a set of discrete modules in such a way that each module can
be developed independent of other modules. After developing the modules, they are
integrated together to meet the software requirements. Note that larger the number of
modules a system is divided into, greater will be the effort required to integrate the
modules.
5. Information hiding: Modules should be specified and designed in such a way that the
data structures and processing details of one module are not accessible to other modules.
They pass only that much information to each other, which is required to accomplish the
software functions. The way of hiding unnecessary details is referred to as information
hiding. IEEE defines information hiding as 'the technique of encapsulating software
design decisions in modules in such a way that the module's interfaces reveal as little as
possible about the module's inner workings; thus each module is a 'black box' to the other
modules in the system.
etc.

Developing a Design Model


To develop a complete specification of design (design model), four design models are needed.
These models are listed below.
1. Data design: This specifies the data structures for implementing the software by
converting data objects and their relationships identified during the analysis phase.
Various studies suggest that design engineering should begin with data design, since this
design lays the foundation for all other design models.
2. Architectural design: This specifies the relationship between the structural elements of
the software, design patterns, architectural styles, and the factors affecting the ways in
which architecture can be implemented.
3. Component-level design: This provides the detailed description of how structural
elements of software will actually be implemented.
4. Interface design: This depicts how the software communicates with the system that
interoperates with it and with the end-users.

Structured Design:

Structured design (SD) is concerned with the development of modules and the synthesis of these
modules in a so-called "module hierarchy". In order to design optimal module structure and
interfaces two principles are crucial:

 Cohesion which is "concerned with the grouping of functionally related processes into a
particular module" and
 Coupling relates to "the flow of information or parameters passed between modules.
Optimal coupling reduces the interfaces of modules and the resulting complexity of the
software".
Structured design was developed by Larry Constantine in the late 1960s, then refined and
published with collaborators in the 1970s. Page-Jones (1980) has proposed his own approach
which consists of three main objects:

 structure charts
 module specifications
 data dictionary.
The structure chart aims to show "the module hierarchy or calling sequence relationship of
modules. There is a module specification for each module shown on the structure chart. The
module specifications can be composed of pseudo-code or a program design language. The data
dictionary is like that of structured analysis. At this stage in the software development lifecycle,
after analysis and design have been performed, it is possible to automatically generate data type
declarations", and procedure or subroutine templates.
TESTING AND DEBUGGING STRATEGIES:
As similarly used as these two terms are, it is important to note that they are completely
different. In
any application development both testing and debugging takes important role and make the
application complete and error free.
As computer scientists, it is important to remember that programming leads you through a series
of tasks and roles:

Task Role
Design Architect
Coding Engineer
Testing Vandal
Debugging Detective
We of course would be focusing on testing and debugging.
Testing: Some existing objectives of testing include

 To exhibit that bugs are not there


 To illustrate that proposed methods are there
 To achieve assurance in the capability of application to perform what the need to do

One difficulty with these objectives is that it is almost impractical to eliminate all of the bugs in
an important software application. Therefore, the objectives are idealistic to establish with. An
additional trouble is that though an application might execute all of its planned methods, it might
still include bugs in that it also executes inadvertent methods.

We could say a good objective of testing is to find out what bugs exist in an application. This
objective presumes that are bugs in the application, a guess which is right for virtually all
software applications and one which demonstrates a much more helpful approach to testing. As
this objective is more favorable to discover bugs, it is also further probable to boost the
consistency of the application.
One technique of identifying the existing approach to testing is to distinguish how the terms
"successful" and "unsuccessful" are used in illustrating test case outcome. If a test case which
discovers no bugs is measured to be victorious, this is a symbol that an infertile or not-so-good
approach presents. A victorious test case ought to be one that discovers bugs. In general, the
more the bugs discovered, the more improved the test case.

Debugging:

Debugging is that action which is done following carrying out a victorious test case. It is
basically solving the bug. One of the reasons why debugging is possibly the mainly tricky action
in software programming is because It is generally done under a marvelous quantity of stress to
solve the alleged bug as early as probable. Among the two features of debugging (identifying and
solving the bug), identifying the bugs depicts about 95% of the action. Therefore, we would be
mainly focusing on the method of discovering the place of a bug, specified that a bug prevails,
on basis of the consequences of a victorious test case.

Preconditions for effective debugging

In order to avoid excessive time spent on debugging, the programmer should be mentally
prepared for the effort. The following steps are useful to prepare for debugging.

 Understand the design and algorithm - If you are working on a module and you do not
understand its design or its algorithms, then debugging will be very difficult. If you don't
understand the design, then you can't test the module because you do not know what it is
supposed to do. If you don't understand the algorithms, then you will find it very difficult
to locate the errors that are revealed by testing. A second reason for the importance of
understanding algorithms is that you may need that understanding in order to construct
good test cases. This is especially true for algorithms for complex data structures.
 Check correctness - There are several methods for checking correctness of an
implementation prior to execution.
 Correctness proofs - One useful code check is to examine code using the logical
methods of correctness proofs. For example, if you know preconditions, invariants,
terminating conditions, and post conditions for a loop then there are some easy checks
that you can make. Does the precondition, together with any loop entry code imply that
the invariant is initially true? Does the loop body preserve the invariant? Does execution
of the loop body make progress towards loop termination? Does the invariant, together
with the loop terminating condition and loop exit code, imply the post-condition? Even if
these checks don't find all errors, you will often gain a better understanding of the
algorithm by making the checks.
 Code tracing - Often, errors can be detected by tracing through the execution of various
calls to module services, starting with a variety of initial conditions for the module. For
poorly understood psychological reasons, tracing works best if you are describing your
tracing to someone else. In order to be effective, tracing of a procedure or function should
be done assuming that calls to other procedures and functions work correctly, even if they
are recursive calls. If you trace into a called procedure or function, then you will find
yourself dealing with too many levels of abstraction. This usually leads to confusion. If
there is any doubt about the called procedures and functions, then they can be traced
separately to verify that they perform according to specifications. Again, tracing may not
catch all errors, but it can enhance your understanding of algorithms.
 Peer reviews - A peer review involves having a peer examine your code for errors. To be
effective, the peer should either already be familiar with the algorithm, or should be given
the algorithm and code in advance. When the reviewer meets with the code writer, the
code writer should present the code with explanations of how it correctly implements the
algorithm. If the reviewer doesn't understand or disagrees with part of the
implementation, they discuss that part until both are in agreement about whether or not it
is an error. The reviewer's role is only as an aid to detecting errors. It is left to the
programmer to correct them. Much of the benefit of a peer review derives from the
psychology of presenting how something works. Often the code writer discovers his or
her own errors during the review. In any case, it is useful to have an outsider review your
work in order to get a different perspective and to discover blind spots that seem to be
inherent in evaluating your own work. Like code tracing, peer reviews can be time
consuming. For class work, a peer review of an entire module is not likely to pay for
itself in terms of instructional value. So reviews should be restricted to short segments of
code. For commercial programming, however, quality of the code is much more
important. Thus peer reviews are a significant part of a software quality assurance
program.
 Anticipate errors - Unfortunately, humans make errors with correctness arguments and
sometimes miss cases in code tracing, and peers don't always catch errors either. So a
programmer should be prepared for some errors remaining in the code after the steps
listed above. Hopefully, there won't be too many.

Debugging strategies

As debugging is a difficult and time-consuming task, it is essential to develop a proper


debugging strategy. This strategy helps in performing the process of debugging easily and
efficiently. The commonly-used debugging strategies are debugging by brute force, induction
strategy, deduction strategy, backtracking strategy, and debugging by testing.
Brute force method of debugging is the most commonly used but least efficient method. It is
generally used when all other available methods fail. Here, debugging is done by
taking memory (or storage) dumps. Actually, the program is loaded with the output statements
that produce a large amount of information including the intermediate values. Analyzing this
information may help to identify the errors cause. However, using a memory dump for finding
errors requires analyzing huge amount of information or irrelevant data leading to waste of time
and effort. This strategy is a 'disciplined thought process' where errors can be debugged by
moving outwards from the particulars to the whole. This strategy assumes that once the
symptoms of the errors are identified, and the relationships between them are established, the
errors can be easily detected by just looking at the symptoms and the relationships. To perform
induction strategy, a number of steps are followed, which are listed below.
1. Locating relevant data: All the information about a program is collected to identify the
functions, which are executed correctly and incorrectly.
2. Organizing data: The collected data is organized according to importance. The data can
consist of possible symptoms of errors, their location in the program, the time at which the
symptoms occur during the execution of the program and the effect of these symptoms on the
program.
3. Devising hypothesis: The relationships among the symptoms are studied and a hypothesis is
devised that provides the hints about the possible causes of errors.
4. Proving hypothesis: In the final step, the hypothesis needs to be proved. It is done by
comparing the data in the hypothesis with the original data to ensure that the hypothesis explains
the existence of hints completely. In case, the hypothesis is unable to explain the existence of
hints, it is either incomplete or contains multiple errors in it.
Deduction Strategy
In this strategy, first step is to identify all the possible causes and then using the data each cause
is analyzed and eliminated if it is found invalid. Note that as in induction strategy, deduction
strategy is also based on some assumptions. To use this strategy following steps are followed.
1. Identifying the possible causes or hypotheses: A list of all the possible causes of errors is
formed. Using this list, the available data can be easily structured and analyzed.
2. Eliminating possible causes using the data: The list is examined to recognize the most
probable cause of errors and the rest of the causes are deleted.
3. Refining the hypothesis: By analyzing the possible causes one by one and looking for
contradiction leads to elimination of invalid causes. This results in a refined hypothesis
containing few specific possible causes.
4. Proving the hypothesis: This step is similar to the fourth step in induction method.
Backtracking Strategy
This method is effectively used for locating errors in small programs. According to this strategy,
when an error has occurred, one needs to start tracing the program backward one step at a time
evaluating the values of all variables until the cause of error is found. This strategy is useful but
in a large program with many thousands lines of code, the number of backward paths increases
and becomes unmanageably large.
Debugging by Testing

The work of further test cases is one more very influential debugging process which is frequently
used in combination with the introduction function to acquire details required to make an
assumption and/or to verify an assumption and with the conclusion process to remove assumed
resources, purify the outstanding assumption, and/or confirm the assumption.

The test cases for debugging vary from those used for incorporation and testing in that which are
more particular and are planned to discover an exacting contribution area or interior situation of
the application. Test cases for combination and testing lean to wrap a lot of situation in one test,
while test cases for debugging lean to wrap only one or the extremely only some circumstances.
The previous are intended to distinguish the bug in the nearly all competent method while the
last are planned to separate the bug most proficiently.

Variation between Testing and Debugging:

Testing Debugging

1 Performed by the test engineers in testing stage. Performed by the programmers in


the development stage.

2 In these stage test engineers would discovers the In these stage programmers solve
bugs, called testing to upgrade the excellence of the the errors which called debugging
software.

3 Discovered errors. Solving the discovered errors.

4 It is done by test engineers with the target of It is the work of solving the bugs
discovery bugs in a system. After getting a bug the that is provided by either the
test engineer will be delivering it to programmers testing group or by the users.
group.

5 It is not anything else but discovering the bugs. It is not anything else but solving
the errors.

TEST-CASE DESIGN
A Test Case provides the description of inputs and their expected outputs to observe whether the
software or a part of the software is working correctly. A Test Case is a set of actions executed to
verify a particular feature or functionality of your software application. IEEE defines test case as
'a set of input values, execution preconditions, expected results and execution post conditions,
developed for a particular objective or test condition such as to exercise a particular program
path or to verify compliance with a specific requirement.' Generally, a test case is associated with
details like identifier, name, purpose, required, inputs, test conditions, and expected outputs.
Incomplete and incorrect test cases lead to incorrect and erroneous test outputs. To avoid this, the
test cases must be prepared in such a way that they check the software with all possible inputs.
This process is known as exhaustive testing and the test case, which is able to perform
exhaustive testing, is known as ideal test case. Generally, a test case is unable to perform
exhaustive testing; therefore, a test case that gives satisfactory results is selected.
Now, consider the Test Scenario Check Login Functionality there many possible cases like
Test Case 1: Check results on entering valid User Id & Password
Test Case 2: Check results on entering Invalid User ID & Password
Test Case 3: Check response when User ID is Empty & Login Button is pressed etc.

Test Test Test Steps Test Expected Actual Pass/Fail


Case ID Scenario Data Results Results
TU01 Check 1. Go to Userid = User As Pass
Customer site http://demo.guru99. guru99 should Expected
Login com Password Login into
with 2. Enter UserId = pass99 application
valid 3. Enter Password
Data 4. Click Submit

TU02 Check 1. Go to Userid = User As Pass


Customer site http://demo.guru99. guru99 should not Expected
Login com Password Login into
with 2. Enter UserId = glass99 application
invalid 3. Enter Password
Data 4. Click Submit

This is nothing but Test Case. Test scenarios are rather vague and cover a wide range of
possibilities. Testing is all about being very specific. Hence, we need Test Cases.

Standard Test Case example

While drafting a test case do include the following information

 The description of what requirement is being tested


 The explanation of how the system will be tested
 The test setup like: version of application under test, software, data files, operating
system, hardware, security access, physical or logical date, time of day, prerequisites such as
other tests and any other setup information pertinent to the requirements being tested
 Inputs and outputs or actions and expected results
 Any proofs or attachments
 Use active case language
 Test Case should not be more than 15 steps
 Automated test script is commented with inputs, purpose and expected results
 Setup offers alternative to pre-requisite tests
 With other tests, it should be incorrect business scenario order
GOOD PRACTICES.
1. Test Cases need to be simple and transparent: Create test cases that are as simple as
possible. They must be clear and concise as the author of test case may not execute them. Use
assertive language like go to home page, enter data, click on this and so on. This makes the
understanding the test steps easy and test execution faster.
2. Create Test Case with End User in Mind
Ultimate goal of any software project is to create test cases that meets customer requirements
and is easy to use and operate. A tester must create test cases keeping in mind the end user
perspective
3. Avoid test case repetition: Do not repeat test cases. If a test case is needed for executing
some other test case, call the test case by its test case id in the pre-condition column
4. Do not assume: Do not assume functionality and features of your software application
while preparing test case. Stick to the Specification Documents.
5. Ensure 100% Coverage: Make sure you write test cases to check all software requirements
mentioned in the specification document. Use Traceability Matrix to ensure no
functions/conditions is left untested.
6. Test Cases must be identifiable: Name the test case id such that they are identified easily
while tracking defects or identifying a software requirement at a later stage.
7. Implement Testing Techniques: It's not possible to check every possible condition in your
software application. Testing techniques help you select a few test cases with the maximum
possibility of finding a defect.
Boundary Value Analysis (BVA): As the name suggests it's the technique that defines the
testing of boundaries for specified range of values.
Equivalence Partition (EP): This technique partitions the range into equal parts/groups that
tend to have the same behavior.
State Transition Technique: This method is used when software behavior changes from one
state to another following particular action.
Error Guessing Technique: This is guessing/anticipating the error that may arise while testing.
This is not a formal method and takes advantages of a tester's experience with the application
8. Self-cleaning: The test case you create must return the test environment to the pre-test state
and should not render the test environment unusable. This is especially true for configuration
testing.
9. Repeatable and self-standing: The test case should generate the same results every time no
matter who tests it.
10. Peer Review: After creating test cases, get them reviewed by your colleagues. Your peers
can uncover defects in your test case design, which you may easily miss.
PROGRAMMING ENVIRONMENTS

Though Environment Setup is not an element of any Programming Language, it is the first step
to be followed before setting on to write a program.

When we say Environment Setup, it simply implies a base on top of which we can do our
programming. Thus, we need to have the required software setup, i.e., installation on our PC
which will be used to write computer programs, compile, and execute them. For example, if you
need to browse Internet, then you need the following setup on your machine −

 A working Internet connection to connect to the Internet


 A Web browser such as Internet Explorer, Chrome, Safari, etc.
Similarly, you will need the following setup to start with programming using any programming
language.

 A text editor to create computer programs.


 A compiler to compile the programs into binary format.
 An interpreter to execute the programs directly.
In case you don’t have sufficient exposure to computers, you will not be able to set up either of
these software. So, it is suggested that you take the help from any technical person around you
to set up the programming environment on your machine from where you can start. But for you,
it is important to understand what these items are.

Text Editor

A text editor is a software that is used to write computer programs. Your Windows machine
must have a Notepad, which can be used to type programs. You can launch it by following these
steps −

Start Icon → All Programs → Accessories → Notepad → Mouse Click on Notepad

It will launch Notepad with the following window −

You can use this software to type your computer program and save it in a file at any location.
You can download and install other good editors like Notepad++, which is freely available.

If you are a Mac user, then you will have TextEdit or you can install some other commercial
editor like BBEdit to start with.

Compiler

You write your computer program using your favorite programming language and save it in a
text file called the program file.

The computer cannot understand your program directly given in the text format, so we need to
convert this program in a binary format, which can be understood by the computer.

The conversion from text program to binary file is done by a software called Compiler and this
process of conversion from text formatted program to binary format file is called program
compilation. Finally, you can execute binary file to perform the programmed task.

The following flow diagram gives an illustration of the process −


So, if you are going to write your program in any such language, which needs compilation like
C, C++, Java and Pascal, etc., then you will need to install their compilers before you start
programming.

Interpreter

Compilers are required in case you are going to write your program in a programming language
that needs to be compiled into binary format before its execution.

There are other programming languages such as Python, PHP, and Perl, which do not need any
compilation into binary format, rather an interpreter can be used to read such programs line by
line and execute them directly without any further conversion.

So, if you are going to write your programs in PHP, Python, Perl, Ruby, etc., then you will need
to install their interpreters before you start programming.

Integrated Development Environment (IDE)

Integrated development environments are designed to maximize programmer productivity by


providing tight-knit components with similar user interfaces. IDEs present a single program in
which all development is done. This program typically provides many features for authoring,
modifying, compiling, deploying and debugging software. This contrasts with software
development using unrelated tools, such as vi, GCC or make.
One aim of the IDE is to reduce the configuration necessary to piece together multiple
development utilities, instead providing the same set of capabilities as a cohesive unit. Reducing
that setup time can increase developer productivity, in cases where learning to use the IDE is
faster than manually integrating all of the individual tools. Tighter integration of all development
tasks has the potential to improve overall productivity beyond just helping with setup tasks. For
example, code can be continuously parsed while it is being edited, providing instant feedback
when syntax errors are introduced. That can speed learning a new programming language and its
associated libraries.
Some IDEs are dedicated to a specific programming language, allowing a feature set that most
closely matches the programming paradigms of the language. However, there are many multiple-
language IDEs.
While most modern IDEs are graphical, text-based IDEs such as Turbo Pascal were in popular
use before the widespread availability of windowing systems like Microsoft Windows and the X
Window System (X11). They commonly use function keys or hotkeys to execute frequently used
commands or macros. Popular IDEs are Netbeans, Android Studio e.t.c.
TESTING AND DEBUGGING TOOLS
A debugger or debugging tool is a computer program that is used to test and debug other
programs (the "target" program).
The following are examples of debuggers
 DBG : PHP debugger and profiler
 Intel Debugger (IDB)
 Turbo Debugger
 Ups — C, Fortran source level debugger
 VB Watch Debugger — debugger for Visual Basic 6.0
 Microsoft Visual Studio Debugger
 WinDbg
 Xdebug — PHP debugger and profiler
 DDTLite — Allinea DDTLite for Visual Studio 2008
 DEBUG — the built-in debugger of DOS and Microsoft Windows

Introduction to Problem Solving Methods and Algorithm Development

A computer cannot solve a problem on its own. One has to provide step by step solutions of the
problem to the computer. In fact, the task of problem solving is not that of the computer. It is the
programmer who has to write down the solution to the problem in terms of simple operations
which the computer can understand and execute. In order to solve a problem by the computer,
one has to pass though certain stages or steps. They are:

1. Understanding the problem.


2. Analyzing the problem.
3. Developing the solution.
4. Coding and implementation.
1. Understanding the problem: Here we try to understand the problem to be solved in totally.
Before with the next stage or step, we should be absolutely sure about the objectives of the given
problem.

2. Analyzing the problem: After understanding thoroughly the problem to be solved, we look
different ways of solving the problem and evaluate each of these methods. The idea here is to
search an appropriate solution to the problem under consideration. The end result of this stage is
a broad overview of the sequence of operations that are to be carries out to solve the given
problem.

3. Developing the solution: Here the overview of the sequence of operations that was the result
of analysis stage is expanded to form a detailed step by step solution to the problem under
consideration.

4. Coding and implementation: The last stage of the problem solving is the conversion of the
detailed sequence of operations in to a language that the computer can understand. Here each
step is converted to its equivalent instruction or instructions in the computer language that has
been chosen for the implantation

PASCAL PROGRAMMING
Pascal is a high-level language developed in the early 1970s by Niklaus Wirth, a computer
scientist at the Institute of Informatics, Technical University, Zurich, Switzerland. The language
was named in honour of Blaise Pascal (1623 -1662), the brilliant French scientist and
mathematician. Pascal is now widely used as programming language for a variety of different
applications.

Pascal Program Structure


Every pascal program generally have a heading statement, a declaration and an execution part
strictly in that order. Every Pascal program has the same essential format, which is illustrated
below,
program TITLE ( input, output );
begin
program statements;
program statement
end.
program is the first word of all Pascal programs. It is a keyword (Keywords are reserved, i.e.,
you cannot use keywords to describe variables).
TITLE is the name the programmer gives to the Pascal program being written.
It is an identifier. Identifiers begin with a letter, then followed by any digit, letter or the
underscore character ( _ ).

Comments
Comments are things that are used to explain what parts of a program do. Comments are ignored
by the compiler and are only there for the people who use the source code. Comments must be
put between curly brackets { }. You should always have a comment at the top of your program to
say what it does as well as comments for any code that is difficult to understand. Here is an
example of how to comment the program we just made:
{This program will clear the screen, print "Hello world" and wait for the user to press enter.}
Variables and Constants
What are variables?
Variables are names given to blocks of the computer's memory. The names are used to store
values in these blocks of memory. Variables can hold values which are either numbers, strings or
Boolean. We already know what numbers are. Strings are made up of letters. Boolean variables
can have one of two values, either True or False.
Using variables
You must always declare a variable before you use it. We use the var statement to do this. You
must also choose what type of variable it is. Here is a table of the different variable types:
Byte 0 to 255
Word 0 to 65535
ShortInt -128 to 127
Integer -32768 to 32767
LongInt -4228250000 to
4228249000
Real floating point
values
Char 1 character
String up to 255
characters
Boolean true or false

A variable definition is put in a block beginning with a var keyword, followed by definitions of
the variables as follows:
var
A_Variable, B_Variable ... : Variable_Type;
Pascal variables are declared outside the code-body of the function which means they are not
declared within the begin and end pairs, but they are declared after the definition of the
procedure/function and before the begin keyword. For global variables, they are defined after the
program header.
Here is an example of how to declare an integer variable named i:
program Variables;
var i: Integer;
begin
end.
To assign a value to a variable we use :=.
program Variables;
var
i: Integer;
begin
i := 5;
end.
You can create 2 or more variables of the same type if you seperate their names with commas.
You can also create variables of a different type without the need for another var statemtent.
program Variables;
var
i, j: Integer;
s: String;
begin
end.
When you assign a value to a string variable, you must put it between single quotes. Boolean
variables can only be assigned the values True and False.
program Variables;
var i: Integer;
s: String;
b: Boolean;
begin i := -3;
s := 'Hello';
b := True;
end.

Calculations with variables


Variables can be used in calculations. For example you could assign the value to a variable and
then add the number 1 to it. Here is a table of the operators that can be used:
+ Add
- Subtract
* Multiply
/ Floating Point
Divide
div Integer Divide
mod Remainder of
Integer Division

The following example shows a few calculations that can be done:


program Variables;
var
Num1, Num2, Ans: Integer;
begin
Num1 := 5;
Ans := Num1 + 3;
Num2 := 2;
Ans := Num1 - Num2;
Ans := Ans * Num1;
end.
ARITHMETIC STATEMENTS
The following symbols represent the arithmetic operators, ie, use them when you wish to
perform
calculations.
+ Addition
- Subtraction
* Multiplication
/ Division
Addition Example
program Add (output);
var number1, number2, result : integer;
begin
number1 := 10;
number2 := 20;
result := number1 + number2;
writeln(number1, " plus ", number2, " is ", result )
end.
Subtraction Example
program Subtract (output);
var number1, number2, result : integer;
begin
number1 := 15;
number2 := 2;
result := number1 - number2;
writeln(number1, " minus ", number2, " is ", result )
end.
Multiplication Example
program Multiply (output);
var number1, number2, result : integer;
begin
number1 := 10;
number2 := 20;
result := number1 * number2;
writeln(number1, " multiplied by ", number2, " is ", result )
end.
Division Example
program Divide (output);
var number1, number2, result : integer;
begin
number1 := 20;
number2 := 10;
result := number1 / number2;
writeln(number1, " divided by ", number2, " is ", result )
end.
GETTING INFORMATION/DATA FROM THE KEYBOARD INTO A PROGRAM
It is convenient to accept data whilst a program is running. The read and readln statements allow
you to read values and characters from the keyboard, placing them directly into specified
variables.
The program which follows reads two numbers from the keyboard, assigns them to the specified
variables, then prints them to the console screen.
program READDEMO (input, output);
var numb1, numb2 : integer;
begin
writeln('Please enter two numbers separated by a space');
read( numb1 );
read( numb2 );
writeln;
writeln('Numb1 is ', numb1 , ' Numb2 is ', numb2 );
end.
When run, the program will display the message
Please enter two numbers separated by a space
then wait for you to enter in the two numbers. If you typed the two numbers, then pressed the
return key, eg,
237 64
then the program will accept the two numbers, assign the value 237 to numb1 and the value 64 to
numb2,
then continue and finally print
Numb1 is 237 Numb2 is 64
Differences between READ and READLN
The readln statement discards all other values on the same line, but read does not. In the
previous program, replacing the read statements with readln and using the same input, the
program would assign 237 to numb1, discard the value 64, and wait for the user to enter in
another value which it would then assign to numb2.
Constants
Constants are like variables except that their values can't change. You assign a value to a
constant when you create it. const is used instead of var when declaring a constant. Constants are
used for values that do not change such as the value of pi.
program Variables;
const
pi: Real = 3.14;
var
c, d: Real;
begin
d := 5;
c := pi * d;
end.
MAKING DECISIONS
Most programs need to make decisions. There are several statements available in the Pascal
language for this. The IF statement is one of the them. The RELATIONAL OPERATORS,
listed below, allow the programmer to test various variables against other variables or values.
= Equal to
> Greater than
< Less than
<> Not equal to
<= Less than or equal to
>= Greater than or equal to
The format for the IF THEN Pascal statement is,
if condition_is_true then
execute_this_program_statement;
The condition (ie, A < 5 ) is evaluated to see if it's true. When the condition is true, the program
statement will be executed. If the condition is not true, then the program statement following the
keyword then will be ignored.
program IF_DEMO (input, output); {Program demonstrating IF THEN statement}
var
number, guess : integer;
begin
number := 2;
writeln('Guess a number between 1 and 10');
readln( guess );
if number = guess then
writeln('You guessed correctly. Good on you!');
if number <> guess then
writeln('Sorry, you guessed wrong.')
end.
Executing more than one statement as part of an IF
To execute more than one program statement when an if statement is true, the program
statements are grouped using the begin and end keywords. Whether a semi-colon follows the end
keyword depends upon what comes after it. When followed by another end or end. then it no
semi-colon, eg,
program IF_GROUP1 (input, output);
var
number, guess : integer;
begin
number := 2;
writeln('Guess a number between 1 and 10');
readln( guess );
if number = guess then
begin
writeln('Lucky you. It was the correct answer.');
writeln('You are just too smart.')
end;
if number <> guess then writeln('Sorry, you guessed wrong.')
end.
program IF_GROUP2 (input, output);
var number, guess : integer;
begin
number := 2;
writeln('Guess a number between 1 and 10');
readln( guess );
if number = guess then
begin
writeln('Lucky you. It was the correct answer.');
writeln('You are just too smart.')
end
end.
IF THEN ELSE
The IF statement can also include an ELSE statement, which specifies the statement (or block or
group of statements) to be executed when the condition associated with the IF statement is false.
Rewriting the previous program using an IF THEN ELSE statement, { Program example
demonstrating IF THEN ELSE statement }
program IF_ELSE_DEMO (input, output);
var number, guess : integer;
begin
number := 2;
writeln('Guess a number between 1 and 10');
readln( guess );
if number = guess then
writeln('You guessed correctly. Good on you!')
else
writeln('Sorry, you guessed wrong.')
end.
There are times when you want to execute more than one statement when a condition is true (or
false for that matter). Pascal makes provision for this by allowing you to group blocks of code
together by the use of the begin and end keywords. Consider the following portion of code,
if number = guess then
begin
writeln('You guessed correctly. Good on you!');
writeln('It may have been a lucky guess though')
end {no semi-colon if followed by an else }
else
begin
writeln('Sorry, you guessed wrong.');
writeln('Better luck next time')
end; {semi-colon depends on next keyword }

Case
The case command is like an if statement but you can have many conditions with actions for
each one.
program Decisions;

uses crt;

var Choice: Char;

begin

Writeln('Which on of these do you like?');

Writeln('a - Apple:');

Writeln('b - Banana:');
Writeln('c - Carrot:');

Choice := ReadKey;

case Choice of

'a': Writeln('You like apples');

'b': Writeln('You like bananas');

'c': Writeln('You like carrots');

else;

Writeln('You made an invalid choice');

end;

end.

Loops
Loops are used when you want to repeat code a lot of times. For example, if you wanted to print
"Hello" on the screen 10 times you would need 10 Writeln commands. You could do the same
thing by putting 1 Writeln command inside a loop which repeats itself 10 times.
There are 3 types of loops which are the for loop, while loop and repeat until loop.
For loop
The for loop uses a loop counter variable, which it adds 1 to each time, to loop from a first
number to a last number.
program Loops;
var
i: Integer;
begin
for i := 1 to 10 do
Writeln('Hello');
end.
If you want to have more than 1 command inside a loop then you must put them between a begin
and an end.
program Loops;
var
i: Integer;
begin
for i := 1 to 10 do begin
Writeln('Hello');
Writeln('This is loop ',i);
end;
end.
While loop
The while loop repeats while a condition is true. The condition is tested at the top of the loop and
not at any time while the loop is running as the name suggests. A while loop does not need a
loop variable but if you want to use one then you must initialize its value before entering the
loop.
program Loops;
var
i: Integer;
begin i := 0;
while i <= 10 begin
i := i + 1;
Writeln('Hello');
end;
end.
Repeat until loop
The repeat until loop is like the while loop except that it tests the condition at the bottom of the
loop. It also doesn't have to have a begin and an end if it has more than one command inside it.
program Loops;
var
i: Integer;
begin i := 0;
repeat i := i + 1;
Writeln('Hello');
until i = 10;
end.
If you want to use more than one condition for either the while or repeat loops then you have to
put the conditions between brackets.
program Loops;

var

i: Integer;

s: String;

begin
i := 0;

repeat i := i + 1;

Write('Enter a number: ');

Readln(s);

until (i = 10) or (s = 0);

end.

NESTED LOOPS
A for loop can occur within another, so that the inner loop (which contains a block of statements)
is repeated by the outer loop.
RULES RELATED TO NESTED FOR LOOPS
1. Each loop must use a seperate variable
2. The inner loop must begin and end entirely within the outer loop.

Procedures and Functions


Procedures
Procedures are sub-programs that can be called from the main part of the program. Procedures
are declared outside of the main program body using the procedure keyword. Procedures must
also be given a unique name. Procedures have their own begin and end. They do not return
values. The sytanx for declaring a procedure is as shown below.
Procedure Proc_Name(params...);
Here is an example of how to make a procedure called Hello that prints "Hello" on the screen.
program Procedures;
procedure Hello;
begin
Writeln('Hello');
end;
begin
end.
Any variables used by the procedure are declared before the keyword begin.
Program procedure;
PROCEDURE DISPLAY_MENU;
begin
writeln('<14>Menu choices are');
writeln(' 1: Edit text file');
writeln(' 2: Load text file');
writeln(' 3: Save text file');
writeln(' 4: Copy text file');
writeln(' 5: Print text file')
end;
The above procedure called DISPLAY_MENU, simply executes each of the statements in turn.
To use this in a program, we write the name of the procedure, eg,
program PROC1;
PROCEDURE DISPLAY_MENU;
begin
writeln('<14>Menu choices are');
writeln(' 1: Edit text file');
writeln(' 2: Load text file');
writeln(' 3: Save text file');
writeln(' 4: Copy text file');
writeln(' 5: Print text file')
end;
begin
writeln('About to call the procedure');
DISPLAY_MENU;
writeln('Now back from the procedure')
end.
In the main portion of the program, it executes the statement
writeln('About to call the procedure'); then calls the procedure DISPLAY_MENU. All the
statements in this procedure are executed, at which point we go back to the statement which
follows the call to the procedure in the main section, which is, writeln('Now back from the
procedure')
To use a procedure we must call it by using its name in the main body.
program Procedures;
procedure Hello;
begin
Writeln('Hello');
end;
begin
Hello;
end.
Procedures must always be above where they are called from. Here is an example of a procedure
that calls another procedure.
program Procedures;
procedure Hello;
begin
Writeln('Hello');
end;
procedure HelloCall;
begin
Hello;
end;
begin
HelloCall;
end.
Procedures can have parameters just like the other commands we have been using. Each
parameter is given a name and type and is then used just like any other variable. If you want to
use more than one parameter then they must be separated with semi-colons, here is an example
illustrated below.
program Procedures;
procedure Print(s: String; i: Integer);
begin Writeln(s);
Writeln(i);
end;
begin
Print('Hello',3);
end.
Global and Local variables
The variables we have been using so far have been global because they can be used at any time
during the program. Local variables can only be used inside procedures but the memory they use
is released when the procedure is not being used. Local variables are declared just underneath the
procedure name declaration.
program Procedures;
procedure Print(s: String);
var i: Integer;
begin
for i := 1 to 3 do
Writeln(s);
end;
begin
Print('Hello');
end.
Functions
Functions are like procedures except they return a value. The function keyword is used instead of
procedure when declaring a function. One can also say that another type of sub-program is called
a function. The only difference from the procedure is that the function returns a value at the end.
Note that a procedure cannot return a value. A function start and end in a similar way to that of a
procedure. If more than one value is required to be returned by a module, you should make use
of the variable parameter. A function can have parameters too. If you change the sub-program
from procedure to a function, of the previous program, there will be no difference in the output
of the program. Just make sure which one is best when you can to implement a module. For
example, if you don't need to return any values, a procedure is better. However if a value should
be returned after the module is executed, function should be used instead. The actual heading of
a function differs slightly than that of a procedure. Its format is,
function Function_name (variable declarations) : return_data_type;
After the parenthesis which declare those variables accepted by the function, the return data type
(preceeded by a colon) is declared.
Example of a program using a function is seen below:
program Functions;

function Add(i, j:Integer): Integer;

begin

end;

begin

end.

Assigning the value of a function to a variable make the variable equal to the return value. If you
use a function in something like Writeln it will print the return value. To set the return value just
make the name of the function equal to the value you want to return.
program Functions;
var
Answer: Integer;
function Add(i, j:Integer): Integer;
begin
Add := i + j;
end;
begin
Answer := Add(1,2);
Writeln(Add(1,2));
end.
You can exit a procedure or function at any time by using the Exit command.
program Procedures;

procedure GetName;

var

Name: String;

begin

Writeln('What is your name?');


Readln(Name);

if Name = '' then Exit;

Writeln('Your name is ',Name);

end;

begin

GetName;

end.

Arrays
Arrays are variables that are made up of many variables of the same data type but have only one
name. Here is a visual representation of an array with 5 elements:

1 value 1
2 value 2
3 value 3
4 value 4
5 value 5
Arrays are declared in almost the same way as normal variables are declared except that you
have to say how many elements you want in the array. An array is defined as follows,
type array_name = ARRAY [lower..upper] of data_type;

Lower and Upper define the boundaries for the array. Data_type is the type of variable which the
array will store, eg, type int, char etc. A typical declaration follows,
type intarray = ARRAY [1..20] of integer;
This creates a definition for an array of integers called intarray, which has 20 separate locations
numbered from 1 to 20. Each of these positions (called an element), holds a single integer. The
next step is to create a working variable to be of the same type, eg,
var numbers : intarray;
Each element of the numbers array is individually accessed and updated as desired.
To assign a value to an element of an array, is as shown below,
program Arrays;
var a: array[1..5] of Integer;
begin
a[1] := 12;
a[2] := 23;
a[3] := 34;
a[4] := 45;
a[5] := 56;
end.
This assigns the integer values to elements of the a array. The value or element number (actually
its called an index) is placed inside the square brackets.
It is a lot easier when you use a loop to access the values in an array. Here is an example of
reading in 5 values into an array:
program Arrays;
var
a: array[1..5] of Integer;
i: Integer;
begin
for i := 1 to 5 do
Readln(a[i]);
end.
Sorting arrays
You will sometimes want to sort the values in an array in a certain order. To do this you can use
a bubble sort. A bubble sort is only one of many ways to sort an array. With a bubble sort the
biggest numbers are moved to the end of the array.
You will need 2 loops. One to go through each number and another to point to the other number
that is being compared. If the number is greater then, it is swapped with the other one. You will
need to use a temporary variable to store values while you are swapping them.
program Arrays;
var a: array[1..5] of Integer;
i, j, tmp: Integer;
begin
a[1] := 23;
a[2] := 45;
a[3] := 12;
a[4] := 56;
a[5] := 34;
for i := 1 to 4 do
for j := i + 1 to 5 do
if a[i] > a[j] then
begin
tmp := a[i];
a[i] := a[j];
a[j] := tmp;
end;
for i := 1 to 5 do
writeln(i,': ',a[i]);
end.
2D arrays
Arrays can have 2 dimensions instead of just one. In other words they can have rows and
columns instead of just rows. Here is how to declare a 2D array:
program Arrays;
var a: array [1..3,1..3] of Integer;
begin
end.
To access the values of a 2d array you must use 2 numbers in the square brackets. 2D arrays also
require 2 loops instead of just one.
program Arrays;
var r, c: Integer;
a: array [1..3,1..3] of Integer;
begin
for r := 1 to 3 do
for c := 1 to 3 do
Readln(a[r,c]);
end.
You can get multi-dimensional arrays that have more than 2 dimensions but these are not used
very often so you don't need to worry about them.

You might also like