1PROBLEMSSOLVING USING COMPUTERS High Level Language (HLL)
Definition: A HLL is a programming language which enables a
finition: Solving any sort of problem is the basic aim of the
the
normal human being like us to write programs that helps
mputer. The person who writes a solution to the problem is
instructed task.
computer to perform any of the required/
grammer These types of Programming Language are easy to
grammers understand how a human can solves a problem, understand, read and write.
en translates this "algorithm" into a bit of computer can do, and But this type of Programming Language is never ever
ally"write" the detailed syntax (requisite by a computer) to understood by the computer.
mplete the task. To make our computer understand that language we require
that machine tries to in converting it to Machine Language.
metimes, it is the case implement
.Before converting it to any machine level the high level
ferent way than any human can do.
language gets converted to Assembly level Language.
In
mputer Programmers are basically problem solvers.
Medium Level Language
quence to solve a problem on a computer you must:
(data) describing the Definition: Medium-level language (MLL) is a computer
Know how to represent the information
programming language that interacts with the abstraction layer
problem.
Determine the steps to transform the information from one of a computer system.
representation into another. Middle level language is also known as Assembly level
INTRODUCTION TO COMPUTER language/ intermediate programming language.
PROGRAMMING It is basically the output of programming code which is
is set of specific instructions which
efinition: Programming a written in high level language.
for
computer for execution of certain process
or
e given to
Before executing the actual code written in HLL, it needs to
ertain problem solving.
translated so that the processor understands it.
instructions can be precise in one r more
These
programming languages like C, C++, Java and so on. C intermediate language and Java byte code are some examples
A computer follows a set of steps whose intention behind is of medium-level language.
to achieve something. Low Level Language:
These steps are instructed to the computer by computer
Definition: It is a programming language that deals with a
programs.
is the process by which computer's hardware components and constraints.
Basically, computer programming
these programs are designed and implemented. I t is the only language which is only and only understood by
be done with the help of
Computer Programming can the computer and no human can actually read or understand
various programming language. it.
gamming languape So these languages are always considered to be closer to
computers.
eya langua ldmlevel langua Machine level language Low level languages are also known as Machine Level
Languages.
Fig. 1.1:Distribution ofProgramming Language
(1.1)
PROCESS PROGRAMMIN
3. Linking
ww
ortran C Pascal The firstquestion that comes to most peoples minds is
gh-level language linking necessary? The main reason is that Whu
languages come with library routines which can be addedcompile
many
ssembly langt
Machine language program. Theses routines written by the
are you to yo
ww ww88N
manufacturer of th
Hardware compiler to perform a variety of tasks, from
input/output
complicated mathematical functions. In the case of C thet
Fig. 1.2:Levels of Programming Language standard input and output functions are contained in a libran
(stdio.h) the most basic program will require a
so even
libran
function. After linking the file extension is .exe which
are-
executable files.
4. Executable files
Thus the text editor produces.c source files, which go to the
compiler, which
produces .obj object files, which go to the linker,
Hgh level langu which produces exe executable file. You can then run .exe files as
you can other applications, simply by typing their names at the
Easy fo
DOS prompt or run using windows menu.
Ogram
1.4 COMPILING AND EXECUTINGCPROGRAM
ww
Cis compiled language.
english Once the program is written, you must run it through C
Words nd
compiler that can create an executable file to be run by the
Fig. 1.3: High Level Programming Lang. to Machine Code computerWhile the C Program is human-readable on other
side executable file is machine readable.
1.3 EDITING THE PROGRAM The compiler translates source code into an object code.The
Developing a program in a compiled language such as C requires
object code contains machine instructions for the CPU.
at least four steps:
However object file is not executable file.Therefore in next
1 Editing (or writing) the program step,the object file is processed with another special program
2. Compiling it called as Linker.The output of the linker is an executable or
3. Linking it
runnable file.The process isshown in Fig. 14
4. Executing it
We will now each step Compler Executable
cover
separately. e
1Editing
You write a computer program with words and symbols that are orar
les
understandable to human beings. This is the editing part of the
development cycle. You type the program directly into a window Fig.1.4:Overview of Compilation and Execution Process
on the screen and save the resulting text as a separate file. This is
LS ERROR CHECKINGG
often referred to as the source file (you can read it with the TYPE ution
command in DOS or the cat command in unix). The custom is that
Error handling refers to the anticipation, detection, and reso errors
of programming, application, and communications
the text of a C program is stored in a file with the extension.c for
C programming language
Specialized programs, called error handlers, are availao errors
2. Compiling
some applications. The best
programs of this type forest withou
if possible, recover from them when they occur efully
You cannot directly
execute the source file. To run on
terminating the grace
(if all else fails)i n f o r m a t i o n
any application, or
computer system, the source file must be translated into binary
numbers understandable to the computer's Central
terminate an affected application and save the error n
Processing to a log file.
be
Unit (for example, the 80*87 microprocessor). This process that
can
In
produces an intermediate object file - with the extension .obj, the programming, a development error is O
one
ne
tha
logic. Synt3
prevented. Such an error can occur in syntax or
logi of
obj stands for Object. use
errors, which are typographical mistakes or imprope
OM
pecial characters, are handled by rigorous proofreading. Logic pfafopen (unexdst.1r" rb)
errors, also called bugs, occur when executed code does not
produce the expected or desired result. Logic errors are best f (pt NULL
andled by meticulous program debugging. This can be an
ongoing process that involves, in addition to the traditional
lebugging routine, beta testing prior to official release and errnum erpno
ustomer feedback after official release.
fprintflatderr "Valueof errno hd, errno)
run-time eror takes place during the execution of
program, a
perrorError printed by perror
and usually happens because of adverse system parameters or
nvalid input data. An example is the lack of sufficient memory to
printf(tderr "Error opening file %s\, strerror errnum
un an application or a memory conflict with another program.
s such C programming does not provide direct support for error
sandling but being a system programming language, it provides
wou access at lower level in the fom of return values. Most of the
or even Unix function calls return -1 or NULL in case of any
Tor and set an error code emo. It is set as a global variable and
fclose (pf
ndicates an error occurred during any function call. You can find
arious error codes defined in <error.h> header file.
So a C programmer can check the returned values and can take
ppropriate action depending on the return value. It is a good
practice, to set ermo to 0 at the time of initializing a program. A When the above code is compiled and executed, it produces the
walue of 0 indicates that there is no error in the program. following result -
errno, perror0, and strerror0 Value of erno: 2
The C programming language provides perror) and strerroro Error printed by perror: No such file or directory
functions which can be used to display the text message
Error opening file: No such file or directory
associated with erno.
The peroro function displays the string you pass to it, followed 1.5.1 Divide by Zero Erors
by a colon, a space, and then the textual representation of the It is a common problem that at the time of dividing any numbe
curent erno value. programmers do not check if a divisor is zero and finally it creates
a runtime error.
The streror0 function, which returns a pointer to the textual
representation of the current errno value. The code below fixes this by checking if the divisor is zero before
Let's try to simulate an error condition and try to open a file dividing
which does not exist. Here I'm using both the functions to show include stdlo.he
the usage, but you can use one or more ways of printing your
includetoli.h
errors. Second important point to note is that you should use
stderr file stream to output all the errors.
main
#includestdio.h
#include ermoh
#include string.he
Int dividend: 20
int divisor 0
int quotient
externinterrino
int main 0 if( divisor s 0X
fpelitfotdern "Divlsion by zerol Exiting..In)
FILE xit-1)
interrnum
the ti Tods CVS Window Helo
the above code is compiled and executed, it produces Ple tdk earch Wew rbject
hen
ollowing result-
i iNew Insert 2 1om
Division by zero! Exiting..
PrejectInepKtor
1.5.2 Program Exit Status Peuject CAgOR
It is a commonpractice to exit with a value of EXIT_SUCCESS in
case of program coming out after a successful operation. Here,
EXIT_SUCCESS is a macro and it is defined as 0.
If you have an error condition in
your program and you are X
ICompent
out then you should exit with a status EXIT FAILURE PropwhyI, Conporew
coming
which is defined as -1.
1.6 EXECUTING C PROGRAMS
File Debug Proiect
Edit search Run CompileEXAM.CPP
Snctudecmarlt Compler Resouces| dh Conglo Log | Oebuy| Frd Reals | To-0oLbt
int upp(int a) MeSF0g
int rith;
mainO{.
int tek;
printf
printf
Scanf ( , &tek); N Rasdv
rith upp(tek); File > New > Sourc
rith): You may start programming by clicking on
printf
return(0) File in the window. Note that while saving the file, you must sele
int upp(int a) file type as C as this 1DE supports C++ also.
2:17
wxDav.C
ile Edt Sewch ev Pofectiete Yods CVS whdow He
1.6.1 Write, Compile and Run CProgram Open Proect ov Pls. Ctrl+o Project. N w Insert Toq
new file from File > New in the Turbo C++ IDE. Write a AResourre Plo
Open a >in.
******ait***nt
small program in the 1DE. uP1 Newwaoelog
UNow wfr eme
Now go to File > Save As and save the program with the filename
A
of your choice (make sure extension of the filename is .c).
on Directories and
Click on Options and go to Directories. Click
Impt
set Output Directory as you want and Source Directory as where
file.
you have saved the C program i N Setup
on Run.
Now go to compile and click on Compile. And then Click
You will see the output of your C program.
1.6.2 Write, Compile and Run C Program using
wxDev-C++ in Windows
wxDev-C++ is easy to use lIDE which you may opt for to write C
You may download the installer from MeM
Program.
We found it working perfectly on
wxdsgn.sourceforge.net.
It also installs MinGW along with
Windows 7 and Windows XP.
OMPUTER PROGRAMMIN
excellent 1DE fo
shown below to Compile and Run Though slightly dated, we find wxDev-C++ an
use F9 or as
ou may Windows.
programming C. You may try it if you are using
brogram. 1.6.3 Install, Compile and Execute CProgram in Linux
wey Uttedt Wihdow
s Edk Search ew Proect; Execure
Ctr are installing Linux, GNU Gcc
Comgils Most of the time, when you
Ne
Run without Debupgho CrH10 run the following commanc
******
is already installed. f not,
compiler
ReOUO A Ctr#11
*
to C
Toject Syntax Check disgl sys the Roeo sge "Welcoo Progranmi tng"
(oursystem is Ubuntu Linux):
r
... us***********
PTolie anayss w@war-linux 1Desktop
************************* PIoT ARiTg
0000000009
Eile Edit ewearcheminaHp
instatl buiid-essentíal
W3rg3r-iinux:~/Desktop$ |sudo
apt-get ooononn****************
*********
|Reading package lists... Done
Building dependency tree Done
Reading state information.
the newest version.
build-essential is already not upgraded.
e to remove and 273
|8upgraded, 8 newly installed,
w3r@war- iinux:~/besktops
wwco will show you a message like
If C compiler is already installed, it
ww* above. If not, it will install all the necessary
packages.
***************** *"*** *****
********
***********
. n****** ****** .*********************************
......... * * ************* editor and write a small C program like following
******amee**************************************************************************************************
.. nae.n - *********************
Now open a text
....
********************************************************** *
************************************************************* and save it as demo.c
**********:***********************************************
a new window to show you incluo
When compilation is done, it opens
butput. main
****************************
intfWelcome to CProgramming
elh.
Proa
below to compile and execute-
Now run the command as shown
thefile:
wsr@w3r-linux/Desktop
ieEditiewearch 1emina Hep
0 demo deno.c
3r@w3rLinux:~/Desktops gcC
w3r@3r-linux:-/Desktop$ ./deso
Progranaingw3r@3r-linux:-/Desktops
elcome to C
compiler, write a C program
This how you can install GNU Gcc
and run it under Linux.
********** **** ***r***********en****"
*****************************!************
****************************r***********************************r***************
**** ********* * +onunenefg **o*
*** ** *****tera*******t**********
,.....*a* *******
****n**r*********************************************r*** *****
1.7 TESTINGAND DEBUGGING CPROGRAM
be done at
means verifying correct behavior. Testing can
Testing
requirements analysis,
below like following. all stages of module development:
shows you in the pane design, implementation, and
If you have errors, it interface design, algorithm
wdhey 1Uiled11 attention will be
modules. In the following,
integration with other is not
Implementation testing
directed at implementation testing.
can also be
An implementation
restricted to execution testing.
3 d n a proyr an a1op)ay and peer reviewWs,
1ngude <ptdio.h correctness proofs, code tracing,
Wnoude <goni0.h>
tested using
as described below.
printE ( a lcoma.Eo C Prograaning"
gereh) execution testing and
Debugging is a cyclic activity involving has a
debugging
code correction. The testing that is done during
aims
module testing. Final module testing
FAVPu ,ha ch undecredlidenrsrpo chupgtiont ppaarsn different aim than final
is
:Pmts ternine chede (end by dtol. **va**!1*****: * * * * *************
demonstrate correctness,
whereas testing during debugging
********** * : *espne to
FIDumerts ond SetigsAdra p o c e d e o r e toen
cOMPUTER PROGRAMMING IN C(BATU) (1.6)
ROCESS OF PROGR
This difference has a significant Peer Reviews: A peer review involves havin.
primarily aimed at locating errors. ing a peer
effect on the choice of testing strategies. your code for errors. To be effective, the
peer shouldea
already be familiar with the algorithm, or shoun
Preconditions for Effective Debugging e
debugging, the algorithm and code in advance. When theould be give
In order to avoid excessive time spent on
programmer should be mentaly prepared for the effort. The
with the code write the code writer reviewer
should prese
following steps are useful to prepare for debuggin9.
with explanations of how it
correctly implememte
algorithm. If the reviewer doesn't
Understand the Design and Algorithm:Ifyou are working
with part of the implementation, they
understand or disa
on a module and you do not understand its design or its discuss t
both are in agreement about whethe or
not it is
par
algorithms, then debugging will be very difficult. If you don't an
The reviewer's role is only as an aid to
understand the design then you can't test the module detectingd ers.
errors
left to the implementor to correct them.
because you do not know what it is supposed to do. If you Much of the .
of a peer review derives from the
don't understand the algorithms then you will find it very psychology of prece
how something works. Often the code writer
difficult to locate the errors that are revealed by testing. A discovers
second reason for the importance of her own errors during
the review. In any
understanding case, it is ue-
algorithms is that you may need that understanding in order have an outsider review your work in order to
get a dit-
to construct good test cases. This is perspective and to discover blind spots that seem -
especially true for
algorithms for complex data structures. inherent in evaluating your own work. Like code
tracing
Check Correctness: There are several methods for reviews can be time consuming. For class work, a
checking of an entire module is not likely to
per r
correctness of an implementation prior to execution. pay for itself in ter
Correctness Proofs: One useful code check is to examine instructional
value. So reviews should be restricted to
code using the logical methods of correctness segments of code. For commercial programming, ho-
proofs. For quality of the code is much more important. Thus
example, if you knowpreconditions, invariants, terminating
conditions, and postconditions for a reviews are a significant part of a software
loop then there are quality assu
some easy checks that
you can make. Does the precondition, program.
together with any loop entry code imply that the invariant is Anticipate Errors: Unfortunately,
initialy true? Does the loop
humans make error=
body preserve the invariant? correctness arguments and sometimes miss cases n
Does execution of the
loop body make progress towards tracing, and peers don't
always catch errors either
loop termination? Does the invariant,
together with the loop programmer should be prepared for some errors rem-
terminating condition and loop exit code, in the code after the steps listed above. Hopetuly
imply the
postcondition? Even if these checks don't find all errors, won't be too many.
will often gain a better you
making the checks.
understanding
of the
algorithm by 1.7.1 Requirements for Debugging
To
Code Tracing : Often, errors can be
effectively debug code you need two ies.
capabilities. FTS
detected by need to be able to videdi
through the execution of various calls to module tracing efficiently call on the services prov
module. Then you need
starting with a variety of initial conditions for the services, to be able to get informato the m
back
poorly understood psychological reasons, module. For results of the
calls, changes in the internal state o
tracing works error
if you are
describing your tracing to someone else. In best conditions, and what the module was doing when
to be effective, order occurred.
tracing of a procedure or function
done assuming that calls should be Driving the Module
other procedures and
to
work correctly, even if they are recursive calls. functions To
effectively debug have
into a called If a module, it is necessary
procedure or function then you will findyou trace method for calling upon the services provided by
the
m
dealing with too many levels of yourself There
to confusion. If abstraction. This usually are two
commonmethods for doing tu iS.
there is any doubt leads pro
procedures functions then they can be about the called Hardwired Drivers: A hardwired is a
main
to verify that
and
traced module that contains a
driver is v e r
t ot h ese
they
perform according to separately fixed sequence oT ca
tracing may not catch all specifications. Again,
errors, but it
provided by the module that is being tested. t h e driver cooe
can
understanding of algorithms. enhance your of calls can be modified
by rewriting
dules whose behav
recompiling it. For testing modules har
determined by a vary small
of
cases,
numo
Der t o consn
drivers offer the
COMPUTER PROGRAMMING IN C(BATU) (1.7) PROCESS OF PROGRAMMING
there are too many cases, though, they have the the execution state of the module. One
common method for
shortcoming that a considerable effort is involved in
determining the execution state is the addition of debugging
modifying the sequence of calls.
print statements that indicate entry and exit from
Command Interpreters: A command interpreter drives the segments
of code.
module under test by reading input and
commands
interpreting
it as
to execute calls to module services. Command
1.7.2Principles of Debugging
interpreters can be designed so that the commands can Report Error Conditions
Immediately Much debugging
time is spent zeroing in on the cause of errors. The earlier an
either be entered interactively or read from a file. Interactive error is detected, the easier it is to find the cause. If
command interpretation is often of great value in an
early incorrect module state is detected as soon as it arises then
stages of debugging, whereas batch mode usually is better
the cause can often be determined with minimal effort. If it is
for later stages of debugging and final
testing. The primary not detected until the in the client
disadvantage of command interpreters is the complexity of symptoms appear
interface then may be difficult to narrow down the list of
writing one, including the possibility that a lot of time can be
possible causes.
spent debugging the interpreter code. This is mitigated by
Maximize Useful Information and Ease of
the fact that most of the difficult code is reusable, and can Interpretation:
It is obvious thatmaximizing useful information is desirable,
be easily adapted for testing different kinds of modules. For
and that it should be easy to interpret. Ease of interpretation
almost all data structure modules, the
flexibility offered by is important in data structures. Some module errors cannot
command interpreters makes them a preferred choice.
easily be detected by adding code checks because they
Obtaining Information about the Module
depend on the entire structure. Thus it is important to be
Being able to control the sequence of calls to module services has
able to display the structure in a form that can be easily
little value unless you can also obtain information about the
Scanned for correctness.
effects of those calls. If the services generate output then some
Minimize Useless and Distracting Information: Too much
information is available without any further effort. However, for
information can be as much of a handicap as too little. If you
many modules, including data structure modules, the primary have to work with a printout that shows entry and exit from
effect of calls to services is a change in the internal state of the
every procedure in a module then you will find it very
module. This leads to needs for three kinds of information for
difficult to find the first place where something went wrong.
debugging. ldeally, module execution state reports should be issued only
Module State: Data structure modules generally have when an error has occurred. As a
general rule, debugging
services for inserting and deleting data. These services information that says "the problem is here" should be
almost never generate output on their own, and often do not preferred in favor of reports that say "the problem is not
return any information through parameters. Therefore, in here"
order to test or debug the module, the programmer must
Avoid Complex One : Use testing code One reason why it
add code that provides information about changes in the
is counterproductive to add module correctness checks for
internal module state. Usually, the programmer adds
errors that involve the entire structure is that the code to do
procedures that can display the data contents of the module.
so can be quite
These procedures are made available to the driver module,
complex. It is very discouraging to spend
several hours debugging a problem, only to find that the
but are usually removed or made private when testing is
error was in the debugging code, not the module under test.
complete. For debugging, it is useful to have procedures that
Complex testing code is only practical if the dificult parts of
show internal structure as well as content.
the code are reusable.
Module Errors: When a module has a complex internal
state, with incorrect code it is usually possible for invalid 1.7.3 Debugging Aids
states to arise. Also, it is possible that private subroutines are Aids Built into Programming Language
called incorrectly. Both of these situations are module errors.
When practical, code can be added to the module to detect Assert Statements: Some Pascal compilers and all C
compilers that meet the ANSI standard have assert
these errors.
procedures. The assert procedure has a single paramete,
Execution State : In order to locate the cause of module which is a Boolean expression. When a call to assert is
errors, it is necessary to know what services and private executed the expression is evaluated. If it evaluates to true
subroutines have been called when the error occurs. This is then nothing happens. If it evaluates to false then the
PROCI AMA
(1.8) tu
chances of having to deal with
PROGRAMMINGIN C(BATU) Is that it greatly
reduces the
often will geritre
COMPUTER The assert
time. Multiple
errors
errors at the
message. same
error
terminates with an
error
more
program
detecting and reporting c o n f u s i n g e r r o r Indicatlons.
procedure can
be used for
Sanlty Checks
conditions.
code that structure is often written wit s
compilers generate in complex data
Tracebacks: Many Pascal
A Low level code code correctly implernerts 1
the higher level
occurs.
runtime error
results in
tracebacks
whenever a
assumption that low level code may be w
of subroutines that are
For example, the
is a report of the sequence desired algorithm. variable or parameter a s
traceback
traceback will also
indicate line that a certain
currently active.
Sometimes a
with the assumption
a traceback is justified by the algorith
subroutines. If available, that assumption
numbers in the active be NULL. Even if test to see if the conditios
runtime error occurred,
but it is up to the idea to put ina
may still be good
reveals where the a
code may be implemerr
to determine where
the cause lies.
satisfied because
the higher level
programmer check. If anas
computer systems
or
check is called a sanity
General Purpose Debuggers: Many incorrectly. This kind of checks
ample,
programs. For example, available then it can be used for the
compilers come with debugging procedure is detectiora
have general purpose
sanity checks is that they give early
most UNDX operating systems advantage of
and dbx. Debugging programs
debuggers such as sdb errors.
through a program line-by- Turning Debugging
Code on
provide capabilities for stepping 2. Boolean Constants For
set by the user.
line and program with breakpoints
running a Off
is about to be executed the often profita
When a line with a breakpoint added to a module then it is
that the user can examine or If debugging code is
a Boole
interrupted statement that is controlled by
so
program is
canprovide to enclose it in an if
programs also
modify program data. Debugging often constant added to the
module. this, the debugg
By doing
Debuggers are
tracebacks in case of run-time errors. be readily available if nee
are the only tool code can easily be turned off, yet
difficult to learn to use effectively. If they be used for different stages
later. Different constants should
that they will not save
used for debugging then it is likely
data structure module testing so that useless information is minimized.
much time. For example, debugging a Behavior A
with a
a good test driver, will likely
debugger, but without 3. Error Variables For Controling Program
result in spending a getting piecemeal
lot of time Errors
there is t
information about errors. When debugging print statements are added to code,
information.
174 Debugging Techniques possibility a tremendous explosion of useless
of
1 Incremental Testing problem is that a print itself will be execus
statement by
does r
In a good design for a complex module, the code is broken up whether or not there is an error. Thus, if the error
ma
subroutines, than 10 to
most of which are no more appear untila number of subroutine calls have been
large
into numerous
then most of the messages are just telling you everything i5 0
15 lines long. For a module designed in this way, incremental
incremental testing, the so far. This problem is greatly magnified if the added cod
testing offers significant advantages. For
subroutines are classified in levels, with the lowest level displaying the internal structure of a data structure. Assum
subroutines being those that do not call other subroutines. If that the module has sanity checks for error detection, an e
subroutine A calls subroutine B then A is a higher level subroutine Boolean variable be added to the module. It
can
shouo
than B. The incremental testing strategy is to test the subroutines initlalized to false, indicating that there is no error. For mostur
individually, working from the lowest level to higher levels. To do
testing at the lower levels, the test driver must either be capable
structures, there is a Create operation for initialization. The
variable can be initialized at the same time. Instead of exiting
ble
of calling the low level subroutines directly, or else the sanity checks are modified so that they set the error varn3
programmer must be able to provide several test input cases, true. Then debug code can be enclosed in if statements 5o
each of which only involves a small number of low level information is only printed when errors have been detected.
eba
subroutines. Devising these test cases requires a thorough possible application of this method is obtaining trace
understanding of the module algorithms, along with a good information when it is not otherwise available.
imagination. The strength of incremental testing is that at any 4. Traceback Techniques
time in the process, there are only a small number of places
where errors can arise. This To obtain a traceback, use an error Boolean set by sanity c
automatically makes debugging
information more meaningful and leads
to quicker determination At various places in the module add debug code
controlle
of the cause of an error. A second reason for incremental testing the error position. Usualy
variable that prints the current
cOMPUTERPROORAMMINGIN C
(BATU)_
MinGW".
MinGW GCC: Read "How to Install
the code with a terminating sanity
economical to first run Make sure tha
more
code at Cygwin GCC: Read "How to Install Cygwin".
need to add the controlled debug
check. Then you only and "make" packages under the
that contains the sanity check is you select "gcc", "g++", "gdb",
places where the subroutine these packages are not part o
"Devel" (Development) category
called.
the default installation.
5. Correcting Code Errors C/C++ Development Tool (CDT)
the is one very Step 2: Install Eclipse
For the correctlon
of errors detected by testing, on whether you have
Two ways to install CDT, depending
to keep in mind: fix the cause, not the
important princlple previously installed an Eclipse:
installed "Eclipse for Java Developerso
symptom.
Ifyou have already could install the CDT plug-in as
code and get a segmentation fault. other Eclipse packages, you
Suppose that you run some
you determine that a NULL pointer was
follows:
After some checking "Wor
Launch Eclipse Help Install New Software I n
passed intoa procedure that did
not check for NULL, buttried to menu and select
NULL with" field, pull down the drop-down
anyway. Should you add
a
reference through the pointer "Kepler http://download.eclipse.org/releases/kepler (o
to the procedure, enclosing the entire body of the In "Name" box
pointer check juno for Eclipse 4.2; or
helios for Eclipse 3.7).
if statement? This question cannot be answered Check "CIC++
procedure in
expand "Programming Language" node
an
It be
without an understanding of the design and algorithm. may Development Tools" "Next" . "Finish".
that if the algorithm corectly implemented then the pointer
is If you have not install any Eclipse package, you
could
from
cannot be NULL, so the procedure does not make the check. If download "Eclipse IDE for CIC++ Developers"
statement does not fix the http://www.eclipse.org/downloads, and unzip the
that is the case then adding the if
by downloaded file into a directory of your choice.
of the problem. Instead, it makes
matters worse
cause
will surely appear Step 3: Configuration
covering up the symptoms. The problem
as the Cygwin
somewhere else, but now the symptoms will be
further removed You do NOT need to do any configuration, as long
MinGW binaries included in the PATH environment
are
from the cause. the pointer NULL check should be
Code such as
or
variable. CDT searches the PATH to discover the C/C++
added only if you are sure that it should be part of the algorithm.
compilers.
If you add a NULL pointer check that is not required by the
2. Writing your First C/C++ Program in Eclipse 2.1 C++
it should report an error condition. In other words,
algorithm then Program
it should be a sanity check. [an error occurred while processing
Step 1: Launch Eclipse
this directivel Start Eclipse by running "eclipse.exe" in the Eclipse installed
1.8 1DE COMMANDS AND ECLIPSE directory.
PROGRAMDEVELOPMENT Choose an appropriate directory for your workspace (i.e.,
for Java where you would like to save your works).
Eclipse is an integrated development environment (1DE) If the "welcome" screen shows up, close it by clicking the
and Ruby
and other programming languages like C, C++, PHP,
"close" button.
etc. Development provided by Eclipse includes the
environment
Step 2: Create a new C++ Project
CDT for
Eclipse Java development tools (DT) for Java, Eclipse For each C++ application, you need to create a project to keep all
CC+, and Eclipse PDT for PHP, among others.
the source codes, object files, executable files, and relevant
t
1How to Install Eclipse C/C++ Development Tool (CDT) resources.
8.1.2 for Eclipse 4.2.2 (Juno) To create a new C++ project:
k C++
Step 1: Install MinGW GCC or Cygwin GCC Choose "File" menu "New" Project... C/C++
To use Eclipse for C/C++ programming, you need a CIC++ project.
compler. On Windows, you could install either MinGW GCC or The "C++ Project" dialog pops up.
Cygwin GCc. Choose MinGW if you are not sure, because MinGW >In "Project name" field, enter "HelloWorld"
y is lighter and easier to instal, but having less features. In "Project Types" box, select "Executable" "Empty
is Project".
PROCESSOFPROGRAMIMe
(1.10)
COMPUTER PROGRAMMING IN CBATU)
For MinGW GCC:
eg, "Cygwin C
In "Toolchains" box, choose your compiler, following
directories to "GNU
1 "Add the
Next
GCC" or "MinGW GCC" installed directory
is your MinGW
The "Select Configurations" dialog appears.
Select both SMINGW HOME
SMINGWHOMEVibigccmingw3214.6.rinclude
Finish.
"Debug" and "Release"
Hello-world C++ Program SMINGW_HOMEinclude
Step 3: Write a
In the "Project Explorer (leftmost panel) Right-click on
Source File.
.SMINGW_HOMEVib\lgccimingw3214.6.rinclude-fixed
"HelloWorld" (or use the "File" menu) New
directories to "GNU C++", Whers
2. "Add" the following
The "New Source File" dialog pops up. installed directory:
>In "Source file" field, enter "Hello.cpp". SMINGWHOME is your Cygwin
SMINGWHOMEVib\gccvmingw3214.6.xincludelc+
Click "Finish".
The source file "Hello.cpp" opens on the editor panel SMINGW_HOMEViblgccymingw32\46.xincludelc++mingw~2
(double-click on "test.cpp" to open if necessary). Enter the SMINGWHOMEVibigccumingw3214.6.xincludelc+ibackward
following codes:
SMINGw_HOMEVib\gccmingw3214.6.xinclude
ncdude siostreom SMINGw_HOMEVinclude
sing nanespace std
SMINGW HOMEVibigccmingw3214.6.xinclude-fixed
NOTE: To find the header paths, you can do a search on header
elo such as "stdio.h" (for and "iostream (for C++) underte
Cygwin or MinGW installed directory.
Note: f you encounter "error while loading shared libranes
If "Unresolved Inclusion Error during link Install "libmpfr4" in cygwin.
If eror "unresoved inclusion" appears next to #include Step 4: Compile/Build
statement, the "include paths for headers" are not set properly.
Right-click on the "HelloWold" (or use the "Project" menu)
Select "Project" menu Properties C/C++ General Paths
choose "Build Project" to compile and link the program.
and Symbols I n "Includes" tab:
Step 5: Run
For Cygwin GCC:
To run the program,
1 "Add the following directories to "GNU C', where right-click on the "Helloworld" (or anywhes
on the source
SCYGWIN_HOME is your Cygwin installed directory: "testcpp, or select the "Run" menu) Run As
Local C/C++ Application f ask, choose Cygwin's g
SCYGWIN HOMEViblgccli686-pe-cygwin4.5.xjinclude debugger) The
output "Hello, world!" appears on
$CYGWIN_HOMEVib\gce\li686-pc-cygwin 4.5.x\include-fixed Console" panel.
SCYGWIN_HOME\usrVinclude
SCYGWIN HOME\usrinclude\w32api
2. "Add" the following directories to "GNU C++*, where
SCYGWINHOME is your Cygwin installed directory
SCYGWIN_HOMEViblgcci686-pc-cygwinl4.5.xjinclude\c+
SCYGWIN_HOME \ib\gcci686-pc
cygwin4.5.xincludelc++j686-pc-cygwin
SCYGWIN_HOMEliblgcli686-pc-
cygwin4.5.xinclude\c+\backward
sCYGWINHOME libigceli686-pc-cygwint4.5.xinclude
SCYGWINHOMEliblgceli686-pe-cygwin4.5.x\include-fixed
sCYGWIN HOME\usrinclude
SCYGWIN_HOME\usrincludelw32api
PROCESS OF ROGRAMMIN
L.9 INTRODUCTION TO ALGORITHMS AND obtains the result for the current
input by applying the
FLOWCHARTS operations for the smaller (or simpler) input.
sar
There are three ways to represent the logical steps for Approaches for Designing an Algorithm:
findingthe solution to a given problem, i.e., Algorithm, Top-down Approach: A top-down design approach starts b-
Flowchart and Pseudocode. identifying the major components the system or prograr
of
. I n an algorithm, description of steps for a decomposing them into their lower level components an
given problem is iterating until the desired level of module complexity i
provided. A flowchart represents solution to a given problem
achieved. In this we start with the topmost module anc
graphically. Another way to express the solution to a given
problem is by means of pseudo code. incrementaly add modules that it calls, (For example: 'C
1.9.1Algorithms language).
Bottom-up Approach: A bottom-up design approach start=
An algorithm is a finite set of
precise instructions for with designing the most basic
performing a computation for solving a problem.
or primitive components anc
proceeds to higher level components. Starting from the ver
A step-by-step procedure for
solving a particular problem is bottom, the operations that provide a layer of abstraction ares
called as an algorithm.
implemented.
Fig. 1.5 shows a simple illustration of how algorithms Definition
used for solving computational
are
problems. An algorithm can be defined as "a step-by-step procedure
An algorithm solves only a single problem at a time. that provides solution to a given
However, the
problem"
same problem can be solved using multiple OR
algorithms. "A set of steps that generates a finite
sequence of
The advantage of using multiple algorithms to solve the elementary computational operations leading to the solution
same problem is purely situational. of a given problem is called an algorithm".
The choice of a particular algorithm solely depends on the Characteristics:
type of input values ie., single or multiple.
Every algorithm must satisfy the following characteristics:
Finiteness: An algorithm must always terminate after a finite
number of steps.
Definiteness: Each and every step of the algorithm should
be rigorously and unambiguously defined.
oble gorfng
Input: The algorithm should take zero or more inputs.
Computer Output: The algorithm should produce one or more outputs,
Effectiveness: A human should be able to calculate the
values involved in the procedure of the algorithm using
utp pencil and paper
Fig. 1.5: Use of Algorithms for Solving Computational Problems Advantages:
be written two methods as An algorithm gives a language independent layout of the
Algorithmic strategies can using
shown in Fig. 1.6. program or problem.
It allows the programmers to use the most efficient solution
of the problem.
It eases the process of actual development of program code.
t breaks down the solution of a problem into a series of
simplifed sequential steps
Fig. 1.6: Strategies of algorithm Its simplified way of representing program instructions
1. Iterative Algorithm: In iterative algorithms, the process is enables other programmers to easily understand and modify
carried out repetitively on the inputs in order to achieve the it.
desired output. Disadvantages:
2. Recursive Algorithm: This algorithm is an algorithm which algorithms, it becomes difficult to understand the
For large
calls itself with smaller (or simple) input values, and which flow of program cotrol.
OMPUTR PROGRAMMING INC (ATU)
Following Table 1.1 shows different flowcharting symh
There are no standard conventions to be followed while mbols
developing algorithms.
Table 1.1: Flowcharting Symbols
amount of time to write the Symbol
t may take considerable
algorithm for a gven problem.
is
t lacks the visual representation of programming logic as
1 Process An operaton or action
step,
prevalent in flowcharts.
Terminator A start or stop point in a
2.
L9.2 Flowcharts processor program.
of
A flowchart is a visual representation of the sequence
3. Decision Aquestion or branch in the
steps for soving a problem.
A flowchart can be referred as a pictorial representatlon of an process or function.
Aformally defined sub
algorithm. The objective of using flowcharts to describe the Predefined
problem solution isto ease the understanding of process process.
programming logic. 6. Data (1/0) Indicates data inputs and
A flowchart is a diagrammatic representation of the outputs (1/O) to and from
algorithm or of the plan of solution of a problem. process
Flowchart indicates the process of solution, the relevant A document or report
6. Document
operations and computations, thee point of decision and
Same as document but wel
other information which is a part of the solution. Mult
Principles of Flowcharts: document mutiple document.
Pictorial representation of flowchart makes it a convenient
8. Preparation A preparation or set-up
method of communication. process step
It promotes logical accuracy and is a key to correct
A machine display.
9. Display
programming.
It takes care that no path is left incomplete without any 10. Connector A jump from one point to
action being taken. another.
to develop logic and serves as 11. Continuation onto another
It helps program Of-page
documentation. Connector page
It is an important tool for planning and designing a new
12. Merge Merge multi-process
into o
system. (Storage)
Types of Flowcharts:
13. Extract Extract a measurement.
1 System Flowchart: Used by system analyst. This flowchart
14. Stored data Data storage symbol in
shows various processes, subsystems, outputs and
operations on data in a system. fowchart.
15.
2. Program Flowchart: Used by computer programmers. This Magnetic disk A database.
flowchart shows program structure, logic flow and operations
(database)
performed. 16. Direct access Storage on a
hard disk
Definition storage
direction dl op
We can define flowchart as "a symbolic representation of a 17. Flow Line Indicates the
solution ofa particular problem".
flows.
OR
Advantages and Disadvantages
A flowchart is "a pictorial/graphical/symbolic representation
The
Follows:
Benefits (Advantages) of Flowcharts are as
o
of an algorithm". pra
Proper Documentation: Flowcharts serve as g
a go
ood
Flowchart Symbols 2ses
Flowcharts are constructed or designed by using special
documentation, which is needed for various purpe blue
Efficient guidedevelo
Coding: The flowcharts act as ogram
a
geometrical symbols. Each symbol represents an activity. The during the systems analysis and program
activity could be input/output of data, computation
phase.
/processing of data, taking a decision, terminating the
Efficient
n e maintenanc
solution, etc. The symbols are joined by arrows toobtain a Program Maintenance: The ma Ao
gperating nrngram ho tho heln offlow
(.13)
PROGRAMMING IN c (BATU)
OSIMP
ONALGO
THMSA
cOMPUTER efficiently on
efforts more
to put FLOWCHARTS
Number to the
the programmer
a
It helps Flowchart to Input
and Screen.
that part. Algorithm Number on the
in debugging Same
The flowchart helps Computer and
Display the
Debugging:
Proper
process.
Algorithm:
Flowcharts are better way of communicating Start
Communication:
concerned.
Step 1 Enter number A
a system to
all
the logic of can be Step 2
problem
Effective Analysis:
With the help of flowchart, Display A
effective way.
Step 3
analysed in Stop
more
of Flowchart a r e
as Follows: Step 4
(Limitations)
The Disadvantages
Flowchart
what is done can
Technical Details:
The essentials of
Loss of
of how it is done.
technical details
in the
easily be lost
Sometimes, the program logic is quite
Complex Logic: complex and
flowchart becomes
that case,
complicated. In
clumsy.
If alterations are required, the
Modifications:
Alterations and
completely. in
flowchart may require redrawing Temperature
typed, Flowchart to Convert
cannot be
the flowchart symbols 2. Algorithm and
Reproduction: As Celsius to Fahrenheit.
flowchart becomes
a problem the main two
reproduction of Celsius C) a r e
constructing a
flowchart is Fahrenheit ('F) and Degree convert a
Developing and Degree is possible to
It
Time Consuming: temperature.
Flowchart requires more time to construct units to measure
to Fahrenheit using following
time consuming. and temperature
from Celsius degrees
between Algorithm
(Difference)
1.9.3 Comparison formula:
Flowchart of =oCx 32
Table1.2
Algorithm:
Step 1 Start
Read oC
finite set of A fowchart is a Step 2
An algorithm is a Calculate oF =
(oCx 9/5)+ 32
for solving
graphicalpictorlal Step 3
precise instructions representation of an Display oF
Step 4
a problem.
algorithm. Step 5 Stop
flow of Flowchart
for solving It is a tool which shows
2. t refers to the logic
problem solving.
problem.
of the
rule A flowchart is a diagram
3. An algorithm is a precise in
sequence of operation
(or set of rudes) specitying
problem solving.
how to solve some problem.
Algorithm is stepwise analysls
of the work to be done.
Flowchart gves loglcal flow of and
4 Algorithm gives language Flowchart to Input One Number
problem. 3. Algorlthm and
indepen-dent layout of the in Increasing Order.
problem.
Display Next 10 Numbers
Dificult to update. Algorithm:
5. Easy to update. Step1 Start
Less time required for wrtte an
Time consuming to write and
6 Input A
draw a flowchart. Step 2
algorithm. B A + 10
Step 3 :
COMPUTER PROGRAMMIN IN C(BATO) PROG
GRAMM
Step 4 Output A 5. Algorithm and Flowchart to Display 1 throuah
Step5 A A+1 Numbers.
Step 6 I f A < B, Go to Step 4
Algorithm:
Step 7 Stop Step1 Start
Flowchar Step 2 Let A 1
Step 3 Display A
Step 4 A A+1
Step 5 IfA< 100 GotoStep 3
Step 6 Stop
Flowehart:
Dsplay A
Yes
top
Yes
Algorithm and Flowchart for Given Year is a Leap Year or
Not No
A Year is Called Leap Year if it is Divisible by 400. For Stop
Example: 1600, 2000 etc leap year while 1500, 1700 are not leap 6. Algorithm and Flowchart to Calculate the Area of Cirde
Area of circle measures the
year. area enclosed by a cide
If year isnot divisible by 400 as well as 100 but it is divisible formula is A =n *rr.
by 4 then that year are also leap year. For example: 2004, 2008, Algorithm:
1012 are leap year. Step1 Start
Algorithm: Step 2 Input and Read r
Step 1: Start Step 3 Area 3.14*r*r
Step 2: Accept an year value from the user (year) Step 4 Print Area
Step 3: If remainder of year value divided by 4 (year%4) Step 5 Stop
is 0 then go to Step 4 else go to Step 5
Flowchart:
Step 4: Display "Leap Year and go to Step 6
Step 5: Display "Not Leap Year
Step 6: Stop
Flowchart: w.ww ww w
wwN
7. Algorithm and Flowchart to Print All Divisors or*Inte
No N.
Algorithm:
Yes Step 1 :Start
Step 2 Read N
Step 3 Let Ctr =1
wwww%
Step 4 IfN Mod Ctr = 0
then N is divisible by Ctr, Print Ctr
Stan S
cOMPUTERPROGRAMMINGIN C(BATU) (1.15) PROCESS OFPROGRAMMINO
Step 6' If Ctr is less than or equal to N then Goto Step 4 Flowchart:
Step 7 Stop
Flowchart:
RoadN
rnt Lcn
10. Algorithm and a Flowchart that will Read the Two Side=
of a Rectangle and Calculate its Area.
No To find the area of a rectangle, multiply the length by th
width. The formula is
A L* W, where A is the area, L is the length, W is th
Yes
width, andmeans multiply.
No Algorithm:
Step1 Start
8. Algorithm and Flowchart for Pass or Falil. Step2 Input W, L
A LxW
Algorithm: Step 3
Print A
Step 1 Start Step4
Step 2 Input Q1, Q2, Q3, Q4 Step 5 Stop
Grade (Q1+Q2 +Q3+Q4)/4 Flowchart
Step3
Step 4 if (Grade<50) then nput W
Print "Fail"
else
Print "Pass" nt
Step5 Stop itop
Flowchart: 11. Algorithm and Flowchart to Print What do When Drivin
Sar to a Traffic Signal.
Algorithm:
Step1 Start
Read traffic signal
Step 2
If signal is GREEN then set action as GO
No Yes Step3
Else
Set Action as STOP
Step 4 Print Action
Step5 Stop
Flowchart to Convert
the Length in Feet to Flowchart:
9. Algorithm and
Centimeter.
Sial
1 Feet is equal to 30.48 Centimeter.
Algorithm:
Step 1 Start
Step 2 Input Lft
Step 3 Lcm =Lftx 30.48
Step 4 Print Lcm
Step 5 Stop
cOMPUTERPROGRAMMINGIN C(BATU) (1.16)
12. Algorthm and Flowchart to Find the Square of a Number. 14.
PROCESS PROGRAMM
The number we get after multiplying an integer (not a fraction) by
Algorithm and Flowchart to Find the
for the Given Three Area of a TA
Sides.
itself.
Algorithm:
Tianey
Example: 4 x 4 = 16, so 16 is a square number.
Step 1: Start
Algorithm:
Step 2: Declare the floating variables
Step1 Start a, b, c, s, area
Step 2 Input the Number A
Step 3: Print the message "enter three
sides"
Step 3 Let Square = A*A
Step 4: Read the values of sides from
Step 5: Write the logic for s i.e. S (a + b+
keyboard
Step 4 Display =
c)/2
Step 6: Write the logic for area=root of
Step5 Stop
Step 7: Print the area.
(s(s a)(s -
-b (s
Flowchart:E Step 8: Stop
Flowchart:
13. Algorithm and
Pint and
Flowchart for Finding the Volume and
Surface Area of a Stop
Cylinder.
Lateral Surface Area of a
Cylinder is directly EXERCISE
radius and the
height of the
proportional
to the 1. Explain the following processes with
Cylinder. The formula is A 2* pi * r respect
h. There is special formula for finding the volume programming
The volume is how of a cylinder.
much space takes up the inside of a
)Editing (ii) Comp
The formula for calculating volume () is m*r*r*h. cylinder. ii) Error Checking (iv) Executing the program
Akgorithm: 2. What do
you mean by testing and
Step 1 Start programs? debugin
Step 2 Read radius and 3. What is flowchart?
Step 3 height as r and h 4. Enlist
Step 4
Calculate VT*r*r*h 5. Define
characteristics of algorithm.
Calculate A=2*n*r*h algorithm and flowchart.
Step 5 Print Volume and 6. Enlist
Step 6 Area advantages and disadvantages of Flowchart
Stop 7. Enlist advantages and
Flowchart: 8.
disadvantages of an algorth
Differentiate between algorithm and
9. Write an flowchart
algorithm tofind odd and even number-
draw flowchart.
10. Write an
algorithm for making tea. Also sketch To
11. Enlist principles of
flowchart.
12. Draw symbols for flowchart.
13. What are the
types of flowcharts?
14. Draw flowchart
for addition of two numbers.
15. List
approaches of algorithms in short
16. Write
algorithm for display the given number is P
not.