CMP 211 - Computer Programming
CMP 211 - Computer Programming
PROGRAMMING METHODOLOGY
Problem Solving Phase (Make an ordered sequence of steps that solves a problem –
Algorithm).
Implementation Phase (Implement using a programming language).
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.
Steps in Programming
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.
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.
Example 2:
Write an algorithm and draw a flowchart to convert the length in feet to centimeter.
Pseudocode:
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:
All computer programs can be coded using three logic structures (or programs) or combinations
of these structures:
1. Simple sequence
2. Selection
3. Repetition
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]
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:
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 5: Compare the bigger number with C and Choose the biggest
Step 9: STOP
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:
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. 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.
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.
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
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.
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
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.
Testing Debugging
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.
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.
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.
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 −
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 −
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.
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.
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:
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.
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.
Case
The case command is like an if statement but you can have many conditions with actions for
each one.
program Decisions;
uses crt;
begin
Writeln('a - Apple:');
Writeln('b - Banana:');
Writeln('c - Carrot:');
Choice := ReadKey;
case Choice of
else;
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;
Readln(s);
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.
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
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.