MS Univ - Internet and Its Applications
MS Univ - Internet and Its Applications
MS Univ - Internet and Its Applications
SYLLABUS
UNIT I
\7hat is Internet - History of Internet - How the l$7eb works? - \(/eb Servers and Clients - Looking at
connection as ISP - ISDN - Dial up or Leased Connection - Domain Naming System - Registering our
own Domain Name - Intranet - Overview of \7eb Browsers - hypertext - Hyper Text Markup
Language-Basic Components - Formatting the text HTML-URL-Protocol - Server name - Port - Relative
URLs Absolute URLs - Linking to other HTML Documents - Linking Inside the same Documenrs -
Linking to other internet servies - File Transfer Protocol (FTP)-Gopher.
TINIT II
List in HTML - Displaing Text in lists - Ordered List - Using Ordered Lists - Using Netscape Extensions
- IJnordered Lists - Using < UL > Tag - Directory Lists - Defintion Lists - Combining Lists Types -
Graphics and'Web Pages - Image Format and Drowsers - HTML Tables Aligning Table Elemenrs -
Row and Colum Spanning - Netscaps Table - Enhancements Frames in HTML - Frameser Container
- HTML Forms - The (Input> T.g - Dynamic Documents - Background Graphhics and colour -
Microsoft Internet Extensions - Font Tag Enhancements - Scrolling Marquees.
UNIT III
Data - Steps in Programming Process - Programming Specification - Problem Definition - Requirement
Analysis - Desing a Program Model - Determine or correctness of an Algorithm - Code Program - Test
and Debug - Debugging - Documentation - Structured Programming Techniques Program Tools -
Flow Chart - l$flhy Structured Programs? - Structures - Sequence Program Flow - Decision Srructure
- Iteration Structure - Tools for Structured Programming - Structure Charts - Pseudo Codes - Strucutred
Programming issues - Maintenance - Portability - Readability - Program verification - Modularity -
Problem solving - Apporaches - Top - Down Approach - Brute - Force Approach - Testing Methods
- Black-Box Approach - Glass Box Approach.
UNIT IV
Client - Side and Server-side Programming Languages n-Declaring variables Commenting - Adding
Data and Time Functions to Scripts - Using Mathematical Operators and Functions - Using Conditional
Statements.
LINIT V
String Functions - Creating Subroutines - Creating Functions - Using Logical Connectives and Operators
- Using Loops to Repeat Code - A Simple Page - VB Script and Forms - Hiding Errors.
UNITI
LESSON
1,
INTERNET
CONTENTS
1.0 Aims and Objectives
1.1 Introduction
L.2 Internet
t.z.t History of Internet
1.2.2 Internet Usages
t.3 \Torking of Veb
t.4 Veb Client & Veb Server
t.4.L Veb Server
1.4.2 l$flebClient/Browser
1.1 INTRODUCTION
This lesson will provide an introduction to the various terms like web pages, web servers and
clients,
d?-T1i" naming system, intranet etc, you might have come across while surTing the Internet. Firsrly
we
will discuss about internet and history of internet.
1.2 INTERNET
'The Internet" is probably one of the most overused technical terms in common man's lingo today.
Though everyone seems to have some ideas and opinions about the Internet yet nor many.rrid.firr.i,
precisely. There is no single, generally agreed .rpor, ,rrr*.r ro the question "\fh", is
- the Inrernet?,' -
because the Internet is a different thing to diffeient people. Consider the following
few expressions in
this context.
Internet, the mega network connecting millions of people, is a tremendous phenomenon. The
' web, an offshoot of this global resource has revolutionizei the way information is passed
on.
It is the name given for a vast, worldwide system consisting of people, information, and
'' computers.
. It is a network of networks.
. It is an unlimited commercial opportunity.
It is a set of computers talking over fibre-optics, phone lines, satellite links, and
' other media.
. It is cyber space where data surfing can be done.
. It is an ocean of information.
o It is a gold mine of professionals from all fields sharing information about their work.
Today the information can be in the form of Text, Images, Animation, Sound, Video erc.,
romorrow
it would probablybe in the form of smell, touch, t.rr. o1 some energ ized, f.orm.If information can be
M.S. University - D.D.C.E. Internet 9
Put on computers, it can be digitized and can be made available on the Internet. The only carch is -
How fast? Even the future may nor be able ro tell.
To be technically correct, we can say that the Internet is "an ever growing wide area network of
millions of computers and computer networks across the globe, which can exchange information
through standard rules (protocols)". The same is illustrated in the following figure.
Ethernet Uluster
The lnternet
Campus Cable
Network
Etn
LocalArea Nework
Each computer panicipating in the Internet has a unique address. Information is divided into packets,
which may travel through different paths to the destination address where it is recombined inro its
original form.
A few computers can be interconnected to share resources and exchange information using a number
of network technologies. Further, such networks can be interconnected to form even larger nerworks.
The Internet is a similar network that connects millions of networks worldwide.
Note that we use "The Internet", with definite anicle "The" and not just "Internet". This is because
though there are many networks existing today the one we call "Inrerner" is a single network
consisting of all the participating nerworks.
government information during a "nuclear event". Thus, the predecessor of Internet, as often called
ARPANET, came into being.
Till late 1970s, ARPANET operated to provide connection facility ro around a d,ozenof research sites.
Later in 1982, ARPA established the Transmission Control Protocol (ICP) and Internet Protocol (Ip),
as the protocol suite, commonly known as TCP/IP, which is a connection protocol b.t*."r, ,it.r,
which is still in use today and is the primary method of connecting ro rhe Interner.
This technique of information access, which started as a merhod of sharing files amongsr researchers
was slowly adopted by a wider clientele and after 7982 the network ,t..t.J expanding faster like the
big bang.
The credit remains with the National Science Foundation (NSF), USA, whose nerwork of strategically
located suPercomputers (I',lSFnet) allowed people to share information from home or their
institutions. The other networks which developed in parallel, like BITNET of IBM, X.25 based in
Europe and UUCP based in Bell Labs got slowly absorbed or gor conneced ro Inrerner, in order to
provide a unified information sharing medium. The network although started in US, slowly srarted
reaching other countries by connecring the networks of other countriei.
Internet in India started on an auspicious day, 15'h of Augusr, 1995. This in a way marks the beginning
of free information flow from every nook and corner of the world and thus could well be callled ai
"Independence day" for Information Age in the counrry. Videsh Sanchar Nigam Limited (VSNL)
started a service called GIAS (Gateway Internet Access Service) to allow the Indian users a bite of the
Internet.
l.2.2lnternet Usages
The Internet is an important tool for practically everybody. The applications are endless limited only
by our imagination. Vhatever information is required, it is either ilready available on rhe Inrernet or
it is soon going to be available. Here are some interesting application areas:
. Electronic mail, which was until recently considered only an internal mechanism of an enterprise,
is quickly becoming the most widely used application on the Internet. The most commol of th.
communication methods used by people on the Internet is the private letter, written by one
individual to another (on any subject and in any language), and sent betweenany rwo connecred
Internet sites or through an Internet E-Mail garcway ro or from a service which provides an
Interner gateway.
. The ability to exchange visual information in readable and reusable formats
figures, tables, images, databases, software code
- such as charrs,
opens up possibilities for collaboration at the
-
global as well as local levels. 'With the trend specialization, the abiliry not only ro communicare
but also to actually work with colleagues in the same field scattered ali orer the world makes long
distance collaboration feasible.
o The resources for online research are multiplying at an asrounding rate. Searchable databases
library holdings, alerting services, pre-prints, and other information ryrr.*, are all changing the
way research is done And it is not only the research community that is responsible i"r1tir.
Library shelves are overflowing with journals and proceeding, and with acquisitions budgets
receiving deep cuts, a likely scenario for the future is one in which libraries archive electronica-lly,
share holdings, and become information clearing houses instead of closers.
M.S. University - D.D.C.E. Internet 11
. Another very imporrant application of Internet is multimedia. Live music concerts' radio
broadcasts, live or recorded television shows, interactive audio and webphone, and video
conferencing are no more a dream on Internet, even for a desktop PC user.
Internet provides a variety of information to everybody ranging from entertainment to serious
business application to areas of daily life such as:
13'!$T/ORKING OF \T/EB
The \florld Vide \(eb or just the web is a collection of millions of files stored on the thousands of
compurers (\Ufleb servers) all over the world. \[eb is only a few years old, but it is growing afl
^tand
astounding rate. Its popularity has increased dramatically because it is so easy to use, colorful,
right in content. Basically, the \ileb is a series of interconnected documents stored on comPuter sites or
lffeb sites. On a trip through this \feb, you can visit colleges, companies, museums, government
departments, and other individuals like yourself. As you move through the'Web you can read data on
almost every imaginable topic. You can visit stores to buy things or transfer movies, pictures, games,
\Wide Veb is in its infancy, but it
and other software to your computer, much of it free. The Vorld
may soon become a pipeline for telephone, communication, entertainment, and news - challenging
existing technologies.
The \rorld Vide \7eb called'$f\f\7, or'W3, or simply the \7eb) is a tool that helps you to find
(also
and retrieve information, using links to the other W-W"Sfl pages. Veb links are stored within the page
itself and when you wish to "jump'l to the page that is linked, you select the "hotspot" or "anchor".
This technique is some times called hypermedia or hypertext. If you have used a \Tindows or
Macintosh based help system in which you click on an underlined phrase to jump to that topic, you
'$7eb,
are already familiar with hypermedia. On the a link can point anywhere else on the Internet.
Thus, it is possible to follow one link after another, jumping from one comPuter to another, all
around the Net.
12 Internet and its Applications
M.S. University - D.D.C.E.
Since the\reb is not hierarchical and can handle graphics, it offers a greatdeal of flexibility in
the way
information resources can be organized,p..r"rrr.J, and described.
Note carefully that web server is actually a software. People often use the term loosely for the machine
itself running the web server.
'We
Server Software stores and manages web pages. '$7hen required, the'Web Server accepts requests
for these \i7eb Pages, retrieves these web pages from its HDD, and sends the page back to the client
who requested for it.
Computers that offer the facility to read information stored in web pages are called \7eb Clients.
'$7eb
Clients run special software called Browser that allows them to:
. Connect to an appropriate Server.
. Qrr"ry the Server for the information to be read.
. Provides an interface to read the informarion returned by the Server.
Some of the most popular Browser software that clients nrn to allow them to query 'Web Servers for
information is Netscape Communicator, Internet Explorer, etc.
A typical hardware connection for accessing the Internet is shown below. Intercontinental networks
include communication backbone. Backbones are typically fiber optic trunk lines. The trunk line has
multiple fiber optic cables combined together to increase the capacity.
NSFNET was the first high-speed backbone created by National Science Foundation (NSF) in the year
1987.lt connected 170 smaller networks together and operated ar 1.544 Mbps (million bits per second).
IBM, MCI and Merit worked with NSF to create the backbone and developed 45 Mbps backbone rhe
following year.Today there are many companies that operate their own high-capacity backbones. The
entire Internet is a gigantic, sprawling agreement between companies ro intercommunicare freely.
The Internet interconnects multitude of electronic resources. These resources can be hardware,
software information or a combination of them. The end-users of the Internet are largely either an
individual like you and me or an organization.
From an end-user point of view, following are the required hardware and software infrastructure to
hook onto the Internet.
14 Internet and its Applications M.S. University - D.D.C.E.
The first requirement is an Inrerner-access device, which could be a personal computer - desktop,
laptop etc., or a mobile device like PDA (Personal Dara Assistant).
Q*#-
* Ii.1""-".::ii..*gsxffi *
A Desktop PC A PDA A mobile phone
Next a communication line isneeded to allow communication between the participating devices.
Commonly available communication lines for public use are:
. Telephone lines
. Optical fiber lines
. Microwave links
. Radio links
Then one needs an NIC (Irletwork Interface Card), which connects the above devices ro the
communication line. The other devices required for Internet access are:
1.5.1 Modem
Modem, an acronym for Modulation - Demodulation, is a device that takes a digital signal from the
comPuter, converts it into an analog signal that the phone line and recognize and transmits the signal
through the phone line to another modem that is connecred ro anotler compurer. The receiiing
modem then converts t_he analog signal back to its original digital format th.r, ,"rrd, it to the .orrrprl,"i
for processing. Depending on the speed of the modem, the iransmission could be fast o. ,lo*. ^l\4ort
modems today transmit at speeds of up to 56Kbps.
M.S. University - D.D.C.E. Internet L5
Modems can be internal to rhe hardware or external attached as external device to the computer.
1.s.2 ISP
Inrerner Service Provider is any company which provides Internet facility, either through dial-up or
through leased lines. In India, some leading ISPs are Satyam, BSNL, VSNL, Airtel, etc.
1.5.3 ISDN
ISDN stands for Integrated Services Digital Network. There are two versions of ISDN available. The
simplest one is Basic Rate Interface (BRD, which takes advantage of the copper twisted pair wiring that
is in homes and offices. Instead of a single analog signal, an ISDN line carries three digital channels:
two B @earer) channels that can carry any kind of data at 64,000 bps, and a D (or Delta) channel,
operaring at 16,000 bps, that can carry control signals and serve as a third data channel.
Cable Modem
1.5.5 DSL
DSL stands for Digital Subscriber Line, is a very high*peed connection that uses the same wires as a
regular telephone line. DSL offers a number of advantages over other lines. You don't have to shut
down your Internet connection to talk on the phone. The speed taps off at 1.5 Mbps vs. 56 K.bps for a
regular modem. DSL doesn't require new wiring it can use the phone line you already have. However,
16 Internet and its Applications
M.S. University _ D.D.C.E.
there are some disadvantages as well. your connection is better when you
are closer to the provider's
central office. The connection is faster for receiving data than it is for sendingdata.
You can'r get the
service every'where.
ADSL
ADSL is asymmetric DSL. ADSL divides up the available frequencies in a line based
on rhe fact users
do more downloading than uploading. The iwo pieces of equiiment includes:
for the cusromer, a DSL
transceiver, for the service provider, a DSL Access tvt,rltipl.r., (DSLAM)
ro receive cusromer
connections.
Connecting to the Inrernet is a simple process ourlined below.
1. Connect your device to the modem
2. Connect the modem ro rhe communication line
3. Run a modem driver program on your sysrem
4. subscribe the Internet service from an Interner Service provider.
5' Run the Internet Access software on your system to connect to the Internet server at the
Provider's end.
6' once connected - after proper authentication - run rhe Internet applications ro use the Internet
services.
You may be now thinking of how DNS is able to provide the quick translation of text of the IP
addresses within fraction of seconds from a directory of billions of such addresses. This could be made
possible by using Domain concepts, which uses hierarchical arrangemenrs of text addresses translation.
You can see from the Figure 1.1 that at the top level is the root server, which has null label. Below this
is another level domain or domain as com, edu, int and so on which are grouped rogether. Below this
different sub domains or groups have been created.
In general, while typing Internet addresses it is better to use all lower case letters. There are basically
two types of topJevel domains:
. Non-geographical domains or those which indicate the type of organization, e.g., in
Iu)IDTD.yahoo.com,the.com indicates that it is a commercial organization.
. Geographical domains indicate the code for individual countries, e.g., www.vsnl.net.in. Here the
.in indicates that the network connection is in a country called India.
There are several computers in a network which can be grouped under a domain and can be given
friendly names for convenience. Thus if machines/resources are shifted, their names need not change.
Domain names are easy to remember.
The latest we have heard is that soon we will have .travel to indicate sites related to travel, .movies to
indicate sites related to movies and so on, i.e., extensions will be according to the functions the sites
perform.
af Afghanistan
bb Barbados
by Belarus
co Colombia (Republic of)
su Guam
kr Korea (Republic of)
kw Kuwait (State of)
ng Nigeria pederal Republic of)
Contd....
M.S. University - D.D.C.E. Internet 19
ua Ukraine
ye Yemen (Republic of)
zw Zimbabwe (Republic of)
Each domain corresponds to a unique numeric IP address. The user might be connecring ro an address
like www.sun.com but as far as the Internet is concerned it is connecting to the web server with the IP
address associated with that domain name. The Domain Name System (DNS) implemented as Domain
Name Server, automatically converts domain name addresses inro IP addresses. DNS is portable. Even
if IP addresses change, the domain name may remain the same.
Sub-domains can also be created within domains. They are represenred by period(.). The rightmost
part is the top level domain which can be a geographic/organisation rype domain till you reach the left
which could be the name of the individual host comptt€r, €.g.: asnl.net.in means in India there is a
networking organisation called vsnl.doc.cis.myunioersity.eda shows that this host/server is in the
documentation department called doc in the (CIS) Computer Information Services division ar My
University which is an educational organisation.
Rcgistering your own Doruain Narue (net)
Your Internet service provider may setup your domain name free of charge, excepr for the domain
name registration fees, or for a low fee, so contact them first. If you already have a web site and an
Internet service provider to add your domain name to their DNS servers (so that your name can be
translated into an IP address), the cheapest and the most straight forward way ro get a domain name
maybe by contacting the InterNIC yourself.
Although registering your domain name yourself through InterNIC could cut your co$ by
eliminating the middle rRafl, you can save some time by asking a third party to do the registering for
you. This type of service could come in handy, specially if you don't already have a web server
running to keep the new domain name acrive.
1.7 IN"TRANET
Intranet is a network based on TCP/IP protocols (an internet) belonging to an organization, usually a
corPoration, accessible only by the organization's members, employees, or others with authorization.
An intranet's \7eb sites look and act just like any other rWeb sites, but the firewall surrounding an
intranet fends off unauthorized access.
computers, it can be digitized and can be made available on the Internet. The Internet is an important
tool for practically everybody. The applications are endless limited only by our imagination. 'Whatever
information is required, it is either already available on the Internet or it is soon going to be available.
The \florld Vide Web (also called \fW"\tr7, or'W'3, or simply the Veb) is a tool that helps you to find
and retrieve information, using links to the other \f\ruf pages. \fleb links are stored within the page
itself and when you wish to "jr*p" to the page that is linked, you select the "hotspor" or "anchor".
This technique is some times called hypermedia or hypertext. The ttrf\ruf provides a network of
interactive documents and the software to access them. To navigate the \7\[W, you surf from one
page to another by pointing and clicking on the hyperlinks in text or graphics.
Computers which stores web pages in the form of directories and files and provide these files to be
read, are called 'servers'. They act like service providers that service the need for information.
Computers that offer the facility to read information stored in web pages are called \feb Clients.
Internet Service Provider is any company which provides Internet facility, either through dial-up or
through leased lines. In India, some leading ISPs are Satyam, BSNL, VSNL, Airtel, etc. ISDN stands
for Integrated Services Digital Network. There are two versions of ISDN available. The simplest one
is Basic Rate Interface @RI), which takes advantage of the copper twisted pair wiring that is in homes
and offices. DSL stands for Digital Subscriber Line, is a very high-speed connection that uses the same
wires as a regular telephone line. ADSL is asymmetric DSL. ADSL divides up the available frequencies
in a line based on the fact users do more downloading than uploading. Domain is a large group of
computers on the Internet. Under this scheme each computer has an IP address and a domain name.
Domains have been made on the base of. organization type or geographic locations, e.g., rhe domain
name - ibm.com - where .com indicates that ibm is a commercial organization. Non-geographical
domains or those which indicate the type of. organrzation, e.g., in www.yahoo.com, the .com indicates
that it is a commercial organization. Geographical domains indicate the code for individual counrries,
e.g., www.vsnl.net.in. Here the .in indicates that the network connection is in a counrry called India.
1.9 KEY\T/ORDS
Intentet: Internet, the mega network connecting millions of people, is a tremendous phenomenon.
'World
Web:The \(ide \7eb (also called \f'W1U7, or'W3, or simply the \7eb) is a tool that helps you ro
find and retrieve information.
Web Senter: Computers which stores web pages in the form of directories and files and provide these
files to be read, are called'servers'.
Web Client: Computers that offer the facility to read information stored in web pages are called \(eb
Clients.
IJP.'Internet Service Provider is any company v'hich provides Internet facility, either through dial-up
or through leased lines.
ISDN.'ISDN stands for Integrated Services Digital Network.
Domain: Domain is a large group of computers on the Internet.
M.S. University - D.D.C.E. Internet 21
7. Discuss the process of a typical hardware connection for accessing the Internet.
Martin $/. Murhammer and Eamon Murphy, TCP/D Tutorial €" Tecbnical Ooervieu, Prentice Hall.
Erik T R:ay, LearningXML,Secord Edition O'Reilly Media.
Michael Morrison, HTML and XML for Beginners, Microsoft Press.
\TEB BRO\T/SERS
CONTENTS
2.0 Aims and Objectives
2.1 Introduction
2.2 \7eb Browsers
2.2.t Information Files Creation
2.2.2 Basic Features of Browsers
Contd....
'u7eb
M.S. University - D.D.C.E. Browsers 23
2.1 INTRODUCTION
This lesson will provide an introduction to the various terms like web pages, web server, html,
browser etc., you might have come across while surfing the Internet. It will provide an easy but
comprehensive explanation of what web pages are and how they are created. It will give you an idea
of how communication takes place between web clients and a web server and how web pages are
transferred from the web server to the web clients. Further it will f.amrliarize you with hypertext
markup language, which is used to create web pages along with various tools, HTML editors and
HTML tags. This lesson will familiarize you with the structure of an HTML program which consist of
a head and body part, how to put title and footer and text formatting in a web page. For emphasizing
material in a web page heading styles and horizontal rules are given which will equip you with the
basic skills to write a simply HTML document.
This lesson will familiarize yoru with how HTML allows linking of one HTML document to other
HTML documents. It will provide you with details of how one can link to documents, which are
either present in the current working directory, or to a different location in the same document.
Images can also act as links and you will be introduced to the concept of images maps, which provides
a technique to link multiple documents to the same image.
display and interact with text, images, videos, music and other information typically located on a web
Page at a website on the www or a LAN. Text and images on a web prg" r,orrrr.ly iesigned to provide
hyperlinks to other web pages at the same or differeni website. Tlius web browser e|ables poirr, ,o
point click to reach directly to rhe targetted web pages.
S_ome.of the popular web browsers are Internet Explorer, Mozilla Firefox, Safari, AOL Explorer, erc.
\reb browsers belong to. HTTP user agent category. Browsers also provide in accessing inforr.nation
provided by web seryers in privare networks or conrent in file sysrems.
'Web
browsers talk with web servers using HTTP (hypertexr rransfer protocol) ro retrieve web pages.
HTTP enables web browsers to provide information to web servers ro rerrieve web pages frorl ihJrrr.
Different web pages have a URL address starting with http:// for HTTP access. Th;r; may different
other-URL types and their corresponding proto.ol, arrd most of the browsers supports th.*. FTp (file
transfer protocol) is one_of the examples of such types. Other examples ,r. *rp, for RTSp (real-time
streaming protocol) and https: for HTTPS (an SSL encrypted version of HTTP).
The file format for a \Web page is normally HTML (hyper-texr markup language) and is identified in
the HTTP protocol with a MIME content type. Most oi the bro*rers srpplr, iin rent formars such
as the JPEG, PNG and GIF image formats including HTML. The combinrtior,
of HTTP conrenr rype
and URL protocol specification enables designers to embed images, animations, video, ,orrd ,rrd
streaming media into a web page or ro make them accessible through the web page.
To access information stored in the form of web pages, users musr connect to a \Web Server. Once
connected, an inrerface that displays rhe conrents of thl web page is required.
Computers that offer the facility to read information srored in web pages are called \reb Clients.
\7eb clients run special software called Browser that allows rhem to:
a Connect to an appropriate Server.
. Qrr.ry the Server for rhe information to be read
. Provides an interface to read the informarion returned by the Server.
Some of the most popular Browser software that clients nrn ro allow them to query \reb
Servers for
information is Netscape Communicator, Internet Explorer, etc.
Files that travel across, the largest network in the world, the Internet, and carry information
from a
'Server' to a 'Client' that requested them are called '\Web Pages'. The individual who
develops these
web pages is called'\7eb Developer'.
1. The \7eb browser should be able to look at the \7eb pages throughout the Internet or ro connecr
to various sites to access information, explore resources, and have fun.
M.S. University \Web Browsers 25
- D.D.C.E.
2. The Veb browser must enable you to follow the hyperlinks on a ITeb page and also to type in a
URL for it to follow.
3. Another feature of browser is to have a number of other commands readily available through
menus, icons, and buttons.
4. Your browser ought to include an easy way to get on-line help as well as built-in links to other
'Web
resources on the that can give you help or answers to your questions.
5. You will definitely want a way to save links to the sites you have visited on the \trf\f\f so that
you can get back to them during other sessions. \7eb browsers take care of those in two ways,
through a history list, which keeps a record of some of the \7eb pages you've come across in the
current session, and a bookmark list, which you use to keep a list of \f\f!f pages you want to
access any time you use your browser. The name of the site and its URL are kept in these lists.
The bookmark list is particularly imponant and the browser will contain tools to manage and
arrange it.
6. One of the main features of a browser is to search the information on the current page as well
as search the \[\XAV itself.
7. Browsers give you the facility to save a \fleb page in a file on your computer, print a IUfleb
page on your computer, and send the contents of a \Web page by e-mail to others on the
Internet.
8. Few Web browsers (like Netscape Communicator) are complete Internet package, means
they come with components like e-mail client, newsgroup client, an HTML composer, telnet
client, ftp client, etc.
9. \fleb browser should be able to handle text, images of the \florld \Iflide Web, as well as the
hyperlinks to digital video, or other types of information.
10. To take advantage of some of the most exciting things on the \7orld \7ide '$7eb, your browser
'$7eb
needs to properly display and handle pages that contain animated or interactive items.
Netscape Navigator can incorporate these features through its ability to interpret programs
written in Java and Java Script.
1,t. \ileb browsers interact not just with the 'Web, but also with your computer's operating system
and with other programs, called plug-ins that gives the browser enhanced features.
1,2. Another important feature to insist on in your browser is caching. A browser that caches
keeps copies of the pages you visit so that it does not have to download them again if you
want to return to them. Reloading a page from the cache is much quicker than downloading
it again from the original source.
13. The most important feature of any browser is ease of use. \7hi1e all \ileb browsers are
fundamentally simple to use, the one you settle on should be very easy to work with; it
should function as a transparent window onto the \7eb.
25 Internet and its Applications M.S. University - D.D.C.E.
\7hen a Browser communicates with a'$7eb Server, it results into a four-step HTTP rransaction.
Figure 2.1
As seen in the Figure 2.1, a clrends Browser retrieves a web page from rhe server and displays the web
page in the Browser. The communication steps between the client and rhe server can be summarized as
follows:
Establish Connection
Before a client and server can exchange information, they mu$ firsr establish a connection. TCP/IP is
used to let computers establish a link between a'Web Server and a \feb Browser over rhe Internet.
To communicate with the \Web Server, the client machine must be given the IP address of the server
along with the sub protocol that must be used, i.e., HTTP, FTP, etc. The client browser will amempt
to locate the server based on the IP address supplied and establish a connection.
'Web
M.S. University - D.D.C.E Browsers 27
\7hen a browser connects to a \Web Server using an appropriate protocol name, IP address and port
'Web 'Web
number, and the Server treats this connection to be a request for the 'Default Document'.
The Veb Server then dispatches the'Default'Web Document' to the client who connected.
If the client requires viewing any other web page then the client can specify the web page name (if
known) along with rhe connection information. Thus the complete connection and web page
information will now be specified as:
Protocol:/ /servername:port numb er/web Page name
A web from text and HTML tags can also include references to external obiects, like GIF's
page, apart
JPEG's, Audio files, Video files, etc.
It is the Server's responsibility to terminate the TCPAP connection with the Browser after it responds
to the Browser's request. However, both the Browser and the'Web Server must manage an unexpected
closing of a connection as well. In other words, if the user clicks on the Browser's STOP button, the
Browser must close the connection.
Also a computer crash by either a Browser or a Web Server must be recognized by the surviving
computer, which, in turn, will close the connection.
2.3 HYPERTEXT
'$Tithin
Hypertext is mosr basically a way of constructing documents that reference other documents.
a hypertext document, a block of text can be tagged as a lrypertext link pointing to another document.
\(hen viewed with a hypenext browser, the link can be activated to view the other document. Of
course, if you're reading this document, you're already familiar with the concePt.
Hypertext's original idea was to take advantage of electronic data processing to organize large
quanriries of information that would otherwise overwhelm a reader. Two hundred years ago, the
printing press made possible a similar innovation - the encyclopedia. Hypertext's older cousin
iombined topical articles with an indexing system to afford the researcher one or perhaps two orders
of magnitude increase in the volume of accessible information. Early experience with hypertext
28 Internet and its Applications
M.S. University - D.D.C.E.
sugge:ls- that it may ultimately yield an additional order of magnitude increase, by making
directly
accessible information that would otherwise be relegated to a bibliog raphy, Hypen.*t's limitLg
f^ui,
aPPears not to be the physical size of some books, bur rarher tt.
atility ofth.
reader to n"avigate
increasingly complex search structures. Now, additional increases in human information pro..riirrg
ability seem tied to developing more sophisticated auromared search tools, rhough th. pr.r.rri
technology presenrs possibilities that remain far from fully explored.
Supplementing basic hypertext
.with graphics, more complex user input fields and dynamically
generated documents_ adds_ considerable power and
flexibility to this .orr..pt. Hypertext, thorrgh stiil
useful for its original goal o-f organizing large quantities of information, t..o*., a simple,
i..r.rrl
PurPose user interface that fits neatly into the increasingly popular client-server model. It dJ., ,rot
seem difficult to image a day when restaurant orders, for example, will be taken using a hand-held
hypenext terminal, relayed directly to the kitchen for preparation, arrd simultaneousl| logged to a
database for later analysis by management.
Characteristics of Good H1pertext
The flexibility of hypertext gives free range to the author's creativity, but good hypertext appears ro
have some common characteristics:
. Lots of doeuments: M":! of the hypertext's power comes from its ability to make large quantities
of information accessible. If all the text in your sysrem can be printed on ten p.g.r,1, would be
just as simple to read through it from beginning to end and forget all this hyp"ne*t
silliness. on
the other hand, if there are ten million pages of texr in yo.r. ,yrri*, rhen ,o*.orr" could follows a
link on atomic energy and ultimately hope to find a description of the TJ-238 decay process.
. Lots of links.'If each document has just one
link, then it is little more rhan normal, sequential text.
A hypertext document should present the reader with several links, offering a choice aborrt wher.
to go next. Ideally, a document should present as many relevanr links ai the reader can easily
comprehend and select among.
Range of futail: The great advantage of hypertext is that it permits readers to explore to a breadth
' and depth that is simply not feasible in print. To make this accessible, available hypertext
documents should range from the broadest possible overview of a subjecr, down to iis'gritty
details. Imagine the Encyclopedia Britannica, all thirty-odd volumes of ii, searchable onlinJ and
with each article possessing links to a half dozen reference documents with even more detailed
subject coverage. This is the potential of hypertext.
o Correct links: This may seem trivial, but it's amazing how many \Web links point nowhere. In
general, be careful linking to any hypertext document nor under your direct control. Can you
count on it to be there later?
of these marked elements up to the browser. For example one browser may indent the beginning of a
paragraph, while another m y only leave a blank line.
HTML instructions divide the text of a document into blocks called elements. These can be divided
into two broad categories - those that define how the BODY of the document is to be displayed by
the browser, and those that define information 'about' the document, such as the title or relationships
to other documents. The vocabulary of these elements and a description of the overall design of
HTML documents are given in the rest of Section 2. The Last part of the section also describes
standard naming schemes for HTML documents and related files.
The detailed rules for HTML (the names of the tags/elements, how they can be used) are defined using
another language known as the standard generalized markup language, or SGML. SGML is wickedly
difficult, and was designed for massive document collections, such as repair manuals for F-16 fighters,
or maintenance plans for nuclear submarines. Fortunately, HTML is much simpler!
However, SGML has useful features that HTML lacks. For this reason, markup language and software
experts have developed a new language, called XML (the eXtensible markup language) which has most
of the most useful features of HTML and SGML.
How do you get a'$7eb page into a \7eb browser? All you have to do is to enter a HTML code into a
file, and then open that file in your \feb browser. To create that file, you can use common editors like
\findows \TordPad or Notepad if you save the page in text format. You can even use a word
'Word, but note that you cannot
processor like Microsoft save normal Veb pages in .doc format
(which includes many speciai formatting characters that \7eb browsers won't understand) - they must
be saved in text format from the Save As dialog box.
The name you give the \(eb page does not matter as long as you give it the extension .html to indicate
that it is an HTML document.
In fact, there are many tools called HTML editors to help you with the process * many of which will
even write the HTML for you.
Singular Tags
The second type of tag is the singular or stand-alone tag. They don't have a companion tag. For
example, < BR > tag will insert a line break. This tag does not require any companion tag.
'S7'elcome
to the home page of the Environmental Change Project.
This project is different from other projects with similar names. In our .rr" *. actually wisb rc change
the climate. For example, we would like hot beaches in Northern Quebec, and deserts near Chicago.
<p>So how will we do this. Well we do the following
<u1>
<1i><A HREF="burn.htmI ">Burn</A>more forests.
<1i>Destroy the
<A HREF="http : / /who. zoo.do/ ozone.html ">
Ozone< / A> layer.
<li>Birth more r
Document Head
Information placed in this section is essential to the inner workings of the document and has nothing
to do with the content of the document. Vith the exception of information contained within the
<TITLE> </TITLE) tags,allinformationplacedwithinthe (\IEAD> </HEAD> tagsisnot
displayed in the browser. The HTML tags used to indicate the start and end of the head section are:
<HEAD>
<TITLE> </TITLE>
< /HEAD>
Docurnent Bodjt
The tags used to indicate the start and end of the main body of textual information are:
<BODY>
< /BODY>
Page defaults like background color, text color, font size, font weight and so on can be specified as
attributes of the < BODY ) tag. The attributes that the ( BODY ) tag takes are:
BGCOLOR Changes the default background color to whatever color is specified with
this tag. The user can specify a color by name or its equivalent hexadecimal
number.
BACKGROUND Specifies the name of the Gif file that will be used as the background of the
document. This Gif tiles up across the page to give a background.
TEXT Changes the body text color from its default value to the color specified
with this attribute.
32 Internet and its Applications
M.S. University - D.D.C.E.
Footer
Just as a title can be placed in the title bar of the browser window, cerrain information is commonly
placed at the foot of the web page. Copyright informarion, conract details of the crearor
of the wet
Page, etc' are the type of information traditionally placed at the foot of the web page. The HTML rags
arei
Section Headings
HTML allows for six levels of headings, marked by the element names Hl, H2... H6. There is no
forced hierarchy in these headings, but for consistency you should use the iop lerrel (H1) for main
headings, and lower levels for progressively less imponant ones. In general ^hyperrext documenrs
M.S. University - D.D,C.E. ![eb Browsers 33
should be broken up so that each page does not occupy much more than a single screen. In these cases
you can use the Hl heading to mark the main document heading, and the others to mark subheadings.
Heading Alignrnent: The ALIGN Attribute
HTML 3 proposed an ALIGN attribute to the heading element, which allows an author to "hint" at
the desired alignment of the heading on the display. The possible values are ALIGN:"left" (the
default) to left-align the heading, ALIGN="center" to center the heading, and ALIGN:"right" to
right-align the heading. Several browsers understand left and center alignment, while very few
understand right-alignment.
Some examples are shown below.
Examples ofHeadings
The following examples show the HTML coding for the six heading types, along with the results (note
that the results will vary from viewer to viewer)
(H1 align="left" ) Heading type Hl </HL>
Heading type Hl
<H2 align:"center" ) Heading typeH2 </H2>
Heading typeH2
( H3 align= "right" ) Heading type H3 < /H3>
Heading type H3
<H4> Headingtype H4 </H4>
Heading type H4
<H5 > Heading type H5 < /H5>
Heading type FI5
<H6> Heading type H6 </H6>
Heading type H5
\(/IDTH Sets the width of the de. It can be set to affixed number of pixels, or to the percentage of the
available screen width.
,
Example:
'Welcome (BR>
to HTML Programming
<SPACER TYPE : "HORIZONTAL" SIZE : 90) Hope you enjoy it
Output:
lVelcome to HTML Programming
Hope you enjoy it
M.S. University - D.D.C.E. Veb Browsers 35
COLOR Sets the color of the text. COLOR can be ser to an English language color name or ro
a hexadecimal triplet.
Example:
<HTML>
<HEAD>
<;r>
TRYING AT INDENTING TEXT <BR>
36 Internet and its Applications M.S. University - D.D.C.E.
2.6 URL
Uniform (or Universal) Resource Locator: Though TCP/P serves its role very well, it won'r be easy
remembering the TCP/iP address of every website. To simplify this, we have an English equivalent of
each web site's address. This English address is also unique and yet, it is easy to remember. This is
known as the URL. h includes the protocol, the web server's address and the domain name, such as -
hup: / / www.raj bhavanmp.ind.in
It is the role of the browser to connect with the server where the requisite requests from client or user
'$7hen
is stored or available. the web server receives the request from browser it replies back ro the
browser, which is client in this case. The information basically conrains the HTTP protocol version,
name of the server, the media type of the document and date etc. The media type of the document is
quite important information because the browser is required to know what kind of document rhis is
before it can process it. HTML is the most common media type transferred over the \7eb. Other
media types are GIF image and JPEG image. Several times when a response like "HTTP 404 Not
Found" is displayed which means that the request document is not available ar rhe link. There are
different responses defined in HTTP. Briefly, in order to access a web page, HTTP involves browser
that issues a request followed by a few headers. In response, the server replies back with a few headers
and a document.
The web server basically maps the URLs to files on its hard disks. The web server interprets the path
tn arry URL to map it with a filename on its hard disk. In order to make it work ro map with the
requisite file, the web server is configured to contain a "document root" directory relative to which all
URLs are resolved as filenames. Let us take an example, suppose the URL is hup://myspace.
tutorial.in, and the document root is D:\W\7\flFiles\. \ilhen a user rypes the URL http://myspace.
tutortal.in/ lessonl/networking.htm into browser, the browser requests the server for the document
lVeb Browsers 37
M.S. University - D.D.C.E.
Links available with HTML are hyperlinks that enables user to link to another document on the \7eb.
To facilitate hyperlinks there are the anchor tag (a) and 1/a) and the Href attribute, which are
used by HTML. An anchor can be used to point to any resource on the'Web such as an HTML page,
an image, a sound file, a movie, etc. The syntax for creating an anchor is: ( a href : "url" > Text to be
displayed 1/a). For example - ( a href : "http: / /www.hotmail.com" ) 1/a)
The href attribute is used to address the document to link to and the words between the open and
close of the anchor tag will be displayed as a hyperlink. Target attribute is used to define where the
'When using
linked document will be opened. The name attribute is used to create a named anchor.
named anchors, links can be created that can jump directly into a specific section on a page, instead of
letting the user scroll around to find the needed document. Below is the syntax of a named anchor: ( a
name: "label" ) Text to be displayed< /a> .
Defining colorsfor the HTML links - \7ith the use of a few settings, colors for all links could be defined
on rhe \flebPages. The general color of text links which is blue before the click is given in the
<body> tag as: <body link:"#C0COCO" vlink:"#800080" alink-"#FF0000'). vlink, indicates
that the link has been visited by the user and standard color is purple. alink specifies active link which
means the color of the link when the mouse is on it. Its standard color is red.
In order to define more links to have different colors than the rest of the page, we can either place the
font tags between the (a href > and the 1/a) tag: (a href:"httpt//www.hotmail.com"> (font
color="FFOOCC')here</font)1/a) or using a style setting in the (a) tag: (a
href : "httpt/ /www.hotmail.com" sryle: "color: rgb(o,zss,O)" ) here 1/a) .
Defining link targets - It is evident that a link is usually open in the current window or frame by
default. However, in some cases it is required to be opened in another window or frame. It is
accomplished by adding a rarget:"" to the <a href>. For example: (a href:"http://www.
hotmail.com" rarget: "_blank" > . The *blank loads the page into a new browser window.
38 Internet and its Applications M.S. University - D.D.C.E.
Other targets are jarent; and that load the web page inro the currenr window, the frame
that is suPerior to-self; -top
the frame the hyperlink is in and cancels all frames, and loads in full browser
window respectively
Defining link within a page - It is required to create a link pointing to the anchor. As it has already
been mentioned that an anchor is created using the <, > trg. For example, if an anchor is created for
TOYS in an online shopping mall, this word Toys is simply added *h.ie it is anchored. The HTML
cod is: (a name-'TOYS') 1/a) and then a link pointing ro the anchor using rhe normal <a
href > tag,like this: (a href:'#TOYS')here 1/a).
Yh-." is required to create a link to anchors on exrernal \TebPages, rhe syntax is: <a
: _it
href "htrp;/ /www.hotmail.com#HotmailAnchor" > blabla 1/a)
D"rt"kg linksfor aframeset - A link in a frameset may provide link to a web page rhar is loaded in the
other frame window. Take an example website having tutorials in a frames., LU.a Contents where
different links such as Lesson 1, Lesson 2, and Lesson 3 erc are created.'The HTML code to go at
Lesson3willbelike: (ahref:"Lesson2.htm"target-"Lesson2")Lesson 21/a) of thetutoriai.
Defining image link - A technique called image mapping is used to link one image ro several pages by
simply specifying which of the areas of the image should link ro where. In other iords it .*plririr thrt
an user can go to different websites by simply clicking at different porrions of an image. For example,
<img src="rainbow.g'if ,, usemap = #example border=0>
<map name=exampfe>
<area shape=circle coords=0, 0,29,29 Href="http : / /www.hotmail.com">
<area shape=circle coords=30,30,59,59 Href=,,http;//www.goog1e.co.in,,>
</maP>
In the example above, if mouse is clicked at the upper left corner it links to hotmail website and if it is
clicked at the lower righr corner, it links to Google *ebsite.
For other shapes we can use:
<area shape=rect coords= x1 ,y1 ,x2,y2 Href="ht.tp://www.domain.com"> for Rect,angles
<area shape=circle coords= xl ,y1 ,x2,y2 Href="ht.tp: //www.domain.com,'> for Circl_es
<area shape=polygon coords= xi_,y1,x2,y2, ,xn,yn Href="http: / /www.
domain.com"> for polygons
Defining link to the neu windop - in order to open a page in a new window use the rarget : "_blank" in
<a href ) tag.It simply opens a new browser window that will load the linked page. Fol example
Ih:
linking to the hotmail, the link will be like this: (a href:"hup://www.hotmail.com,,)Go ro
Hotmail l/a).
Defining links to send an ernail - In order to send email, links are created almost in a similar manner as
it is done to link other pages: (a href) tag. The HTML code for the email link is: 4a
href : "mailto:emailaddress" ) Email Me 1/a) .
If a special subject is needed to be added in the email, it can be done using subjecr: serring: <a
href : "mailto:email@lessonnnn.org?subjecr:HTML Tags" ) Send Email 1/a) .
M.S. University - D.D.C.E. Veb Browsers 39
An email link for specific text in the body of the message can be accomplished by simply adding
6cbody:: (a href:"mailto:email@lessonnnn.org?body:Please send me a list of HTML Text
Tags!" )Send Email I/a)
All the above options can be combined in a single emaii. It will look like: 4a
href:"mailto:email@lessonnnn.org?subject:HTML Tags8cbody:Please send me a list of HTML
Text Tags!" )Email Mel/a)
The browser distinguished Hyperlinks from normal text. Every Hyperlink,
o Appears blue in color
.l The default color setting in a browser for Hyperlink text or image
* The color can be set dynamically via an HTML program, if required.
. The hyperlink textlimage is underlined
. When the mouse cursor is placed over it, the standard arrow shaped mouse cursor changes to the
shape of a hand.
The blue color, which appears by default, can be over-ridden. To change these link colors, there are
three attributes that can be specified with the < BODY > tag. These are:
LINK Changes the defauit color of a hyperlink to whatever coior is specified with this tag.
The cursor can specify the coior name or an equivalent hexadecimal number'
ALINK Changes the default color of a hyperlink that is activated to whatever color is
specified with this tag. The user can specify the color name or an equivalent
hexadecimal number.
VLINK Changes the default color of a hyperlink that is already visited to whatever color is
specified with this tag. The user can specify the color name or an equivalent
hexadecimal number.
Links are created in a web page by using the < A > < / A> tags. Anything written between the
<A> </A> tags becomes a hyperlink/hotspot. By clicking on the hyperlink navigation to a
different web page or image takes place.
The document to be navigated to needs to be specified. By using the HREH attribute of the (A) tag
the next navigable web page or image can be specified.
Syntax
<A HREF = "filename.htm">
Hyperlinks can be of two types:
. Links to an external document
. Links (umps)to a specific place within the same document
Here Visit rny Home Page becomes a hyperlink, and links to anorher document, detaik.htm, which is
Present in the current working directory. If the file is not present in the current directory, a relative or
absolute path can be specified.
Syntax
<A NAME = "locarion_name")
<AHREF - "#location_name") </A>
Internal links behave identical to external links with one exceprion - you can use relative URLs for
internal links. A relative URL simply drops the common parr from the URL and lets the browsers
automatically figure out the part that is missing. For example, instead of specifying < A HREF
=
'-http:/ /www.myserver.com/history.hrm" > MyPage < / A> just specify it.
from the currenr page's URL:
irrr that's different
The link element indicates relationships between your documents and other documents or URLS.
Attributes:
. HREF = "IJRL"
The address of the current link destination, accessible through normal web linkage mechanisms.
. MEDIA = SCREEN IPRINT IPROJECTION IBRAILLE ISPEECH IALL
Identifies the ideal environment for the web page to be conveyed in. The default is ALL.
o REL = "text"
It indicates a normal relationship to the document specified in the URL.
Unlike Telnet, FTP does not require any familiarity with rhe remore operaring sysrem. The user is
still required, however, to be familiar with the FTP command set built inlo the protocol itself so rhar
he or she can productively manage the session.
Modern FTP servers known as ftpd support two differenr TCP connections, namely conrrol and data
connections. First control connection is invoked for the enrire duration of transier of file or FTp
session. It facilitates the exchange of commands issued by the client, and replies originating from
server' Data connection is established as and when it is required. Its main function ii to facilitate
transfer of files and directory listings to and from the clienr at the client's requesr.
'Whenever
you wish to do FTP, you need to invoke a few commands. These commands basically are
related to transfer a file from remote computer to your computer or from your computer to the
remote comPuter. There are anonymous as well as authorized privileges with regard to iransfer of a
file from a server. In case of anonymous FTP servers, you cardo fip withouiauthorization you
need to login with a username, which is anonymous, and a password that is your e-mail address. Apart
from this, there are authorized servers for which yor, ,r""J to register befoie yot are permitted to do
FTP. After registration, you will get a password.
Tiuial Fih Transfer Protocol (TFTP)
TFTP, like FTP, is also an Internet service intended for the rransfer of files between from one
comPuter to another over a network. It does not provide password protection or user directory
capability' Unlike FTP, however, TFTP does not rely on TCP for trrriport services. Instead, TFTi,
uses UDP to shuttle the requested file to the TFTP client. Furthermore, diskless devices that keep
software in ROM to use it to boot themselves can use it. It is simpler than the File Transfer Protocol
Ffp) but less capable. FTFTP facilitates to quickly send files ".ros rhe nerwork with fewer security
features than FTP.
Gopher Presents information in a hierarchical structure. Relying on which client software is used and
what choices are obtainable on the Gopher server) the user .rn opt how to vision information-for
instance, as a text file, as a Microsoft 'Word for \Windows documenr, or in a particular language.
A Gop_her client presents the individual user with directory lists. If the user chooses a subdirectory
from the displayed list, the listing for that subdirectory is displayed. If the user selecrs a file, it is
downloaded. Each directory and file can be on a different Gopher server.
M.S. Universitv - D.D.C.E \tr7eb Browsers 43
You can also organize a Gopher server to search local lUfide Area Information Server (WAIS)
databases.
Gopher uses TCP as its transport protocol for all communication and data exchanges between the
client and the server. Internet Information Server communicates with \Tindows Sockets, then
'Windows
Sockets interacts with TCP.
TCP is a connection-oriented protocol (that is, the communications session is established between the
client and the server before data is transmitted). However, unlike FTP, Gopher does not maintain the
connection between requests; this is also called as a stateless connection.
Administrators use Internet Service Manager to configure the following Internet Information Server
Gopher Service components:
. Gopher tlser Access
Manages user access to Gopher Service
. Gopher IP Access
Manages computer access to Gopher Service
. Gopher Connection Parameters
Manages connections to the Gopher Service
. Gopher Resource Location
Manages location and view of Gopher Service resources
. Gopher Logging
Manages Gopher Service logs
Gopher Service user access mentions which \ilindows NT Server logon account the Internet
Information Server uses. Most Internet sites use anonymous Gopher logons.
Gopher Service IP access controls which computers can use the Gopher Service. It uses rhe customer
computers IP address to control access.
Gopher Service connection parameters control connection time-out periods, maximum number of
Gopher Seivice connections, and anonymous logons to rhe Gopher Service.
A Gopher Service URL resource location is an a.k.a. for an absolute path name on a \Tindows NT
Server.
Gopher Service information is logged to a database, file, or not at all. A new log file is produced at
specified intervals.
The assigned protocol port number for Internet Information Server Gopher service is 70.
44 Internet and its Applications M.S. University - D.D.C.E.
heck Your
1. Define URL.
2. \flhat are html tags?
2.10 KEY\T/ORDS
Wcb Pages: Files, which carry information across the Internet.
HTMI; Hyper Text Markup Language, which are designed to specify the logical organization of a
document along with imponant hypertext exrensions.
HTMLEditors: Tools, which help to write HTML.
HTMLTags:They are instructions embedded directly into the text of a documenr.
Struciure: Parts of the HTML document.
Illtperlinks: Image that provides linkages of one HTML documenr ro anorher.
M.S. University 'Web
- D.D.C.E. Browsers 45
Danny Goodman, Dynamic I{TML: Tlte Definitiae Reference (2nd Edition), O'Reilly Media; 2nd edition.
Ed Tittel, Stephen J. James, HTMLfor Dummies @aperback), For Dummies; 3rd edition.
UNITII
LESSON
3
HTML LISTS
CONTENTS
3.0 Aims and Obiectives
3.1 Introduction
3.2 Lists
3.3 Regular Lists
3.3.1 Netscape Extensions to List Elements
3.1 INTRODUCTION
HTML provided several elements for making lists. This lesson will provide an introduction to the
types of lists namely the regular list under which comes the ordered and unordered list and the
definition list or the glossary list. In this lesson we will show displaying text in lists through various
iist tvpes.
50 Internet and its Applications M.S. University - D.D.C.E.
3.2 LISTS
HTML suPPorts several elements for making lists. They can be divided inro rwo types: glossary lists,
and regular lists. Glossary Lists are denoted by the element < DL > , while regular iirrr ,r". denoied by
the elements (UL>, <OL>, <MENU) and <DIR). Lists can be nestld. Thus you.rr, hrrr.
regular list within a regular list, a regular list within a glossary list, and so on. "
' DrR'A list of short elements, typically less than 20 characters in length. These may be arranged in
columns across the page, as opposed to one above the other. This is bro*r., dependent. iVoa OtR
was dropped from the language as of HTML 4.0 - you should use uL instead.
Here_are four examples, showing the rendering for the four differenr types. The text we will format is
as follows:
Hi. The following is an example list.
<UL>
< LI > list element. The quick brown fox jumped over the
lazy dog. The quick brown fox jumped over rhe lazy dog.
The quick brown fox jumped over the lazy dog.
The quick brown fox jumped over the lazy dog.
The quick brown fox jumped over the lazy dog.
< LI> another list element ...
< /UL>
M.S. Uoiversity - D.D.C.E HTML Lists 51
(i) Firstitem
(ii) Second item
(iii) Third itemi value=2
(iv) Second item; tJrye="A"
Example of DL Lists
Here is an example from the Paragraphs section of this manual (with a small addition ro show a nested
regular list:)
<d1>
<dt> Things to Avoid: </dt>
<dd> You shoul-d NOT use elements Ehat define paragraph
formatting within the PRE element. This means you should
not use <code> <P>, &1t;ADDRESS>, <Hn>
M.S. University - D.D.C.E. HTML Lists 53
</code>and so
on. You should avoid the use of t.ab characters - use single
blank characters to space text apart. </dd>
<dt> Things That are OK: <,/dt>
<dd>You <em> can </em> use Anchor. A tlped
carriage return will cause a new line in the presenEed text.
People you should never let format lists include:
<u1>
<1i> Bozo Ehe Clown </li>
<1i> Uncle Fester </Li>
<1i> Knights who say nii </li>
< /uI>
e.g.: <DfR>
<LI>. It.em 1
<LI> Item 2
<LI> Item 3
<,/Df R>
A. Description
B. Examples
1. Reference One
2. Reference Two
lII. Part 2
IV..Summary
Can you visualize what the HTML code would appear like for the preceding outline? The finest solution
would be to use a sequence of nested ordered lists as shown in the follo-inglllusrrarion and
code.
<o1 type="1,>
<1 i>Introduction< / 1i>
M.S. University - D.D.C.E. HTML Lists 55
<1i>Part, I
<oI tlpe="A">
< l- i>Description< / 1 i>
<1i>Examples
<o1 type= " 1- " >
<1i>Ref erence One< / 1i>
<Ii->Reference Two< / l-i>
</ oL>
</li>
</ol>
</Li>
<Ii>Part 2</l-i>
<1 i>Summary< / Li>
</ol>
As we discussed before, you can also shell one type of list within anorher type. For insrance, you
could comprise a bulleted list inside a definition list to provide additional clarification to a definition
description. Look at the following illustration and code to observe what I mean.
<dl->
<dt><b>Morning< /b>< /dt>
<dd>Corinna wakes up around 7:00.</dd>
<dd>Change her diaper and dress her.</dd>
<dd>Feed her breakfast. Some of her favorites are:
<u1>
< I i >Waf f 1es<,/ 1i >
<l-i>Oatmeal< / 1i>
<1i>Cereal< / 1i>
<1i>Fruit < / Li>
</uf>
</dd>
</dL>
heck Your P
1. Define regular list.
2. r$(hat is glossary listl
3.9 KEY\UTIORDS
Unordcred Lrsr..Regular list provided for making list of items.
Ordcred Le'sr.'Regular list provided for making list of 8 items and provides control of the numbering
scheme to be used.
Definition Lrr; List used to present a list of items along with descriptive paragraphs.
Directory List:It marks unbulleted list of short elemenrs, such as filenames.
Menu List:It encloses a menu list in which each element is typically a word or short phrase that fits on
a single line.
Natanya Pitts-Moultis, Dynamic HTML Black Book: The Vkb Profesional's Guide to Using and Interacting uitb
Dynamic HTML, Coriolis Group Books; Bk&CD-Rom edition.
Lisa Lopuck ,lYeb Design for Dummies: For Dummie-s; Bk&CD-Rom edition'
LESSON
4.1 INTRODUCTION
This lesson will introduce to how you can add graphics
ro HTML documenrs. one can add static as
y:l:]'uil::::1fl.::l:':-I._y witLlearn the usJof Border ,ii.;;;."
attrib,,,., *ii.r, to specify the
learn"*.^r_dl1.ll.:
::::: ,"y.are placing on rhe html docum.r,,r. Alorg with
other attributes like the r$7idth and. Height attribute, Al[n attribute
a;rJ*'";;i;;#;;,;
the
with which ;.; ;";
manipulate your pictures according to the rh.p. -you wanr as "as
w"ll using the Aii- att.ibute enables
you to place some rexr in case a particular browser is unable to display
yo,ri i-rg*
M.S. University - D.D.C.E. Graphics and Sfleb Pages 59
Some browsers cannot display images, while users connecting via phone lines often turn off image
loading. The ALT attribute lets you specify a text alternative to the image, for use in these
circumstances. You should aluays include an ALT alternative, particularly if the image is a button
linked to some other resource. If the image is unimportant, you can always put ALT': ".
ALIGN: "bottom", "middle", "top"
ALIGN tells the browser how to align the image with the neighbouring text. "Bottom" aligns the
bottom of the image with the baseline of the text, and is the default. "Middle" aligns the middle of
the image with the baseline of teyt, and "top" aligns the top of the image w-ith the top of the tallest
item in the line. This attribute is optional. "left", "right" (HTML 3.2) HTML 3.2 supports left and
right-aligned images. In this case, the image "floats" to the left or right margin, with the text
following the image element flowing around the image. This attribute value is supported by all
current browsers. "absmiddle", "absbottom", "texttop", "baseline" (HTML 3.2) Netscape introduced
these extra attributes, which work like "top", "middle" and "bottom" but which give additional
vertical control of image placement, when the image flows with the text. These are illustrated in the
example document.
HEIGHT="n", WIDTH-"n" (HTML 3.2)
HEIGHT and WDTH specify the display height and width (in pixels) for the image - if the picture
does not fit, the browser should rescale the image to fit in the specified box. An example is
HEIGHT:'30''!ilIDTH:"50" This is supported by most current browsers. Some also support
percent values (a percentage of page size, or sometimes a percentage of available size inside a table cell)
- but you had better test percentage values, to make sure things work as expected.
4.2.1 Using the Border Attribute
Example 1:
<HTML>
<HEAD>
</HEAD>
<BODY NACKGROUND = ..images/texturel .gif ,,>
<B> Controlling fmage Borders ! </B>
<CENTER>
Example
<fMG wfDTH = 441 HETGHT = 57 BORDER - 0 HSPACE - 0 sRC
=*rMAGE1.crF"
ALIGN=CENTER>
The attributes taken by the < IMG... ) are explained in the following examples:
4.4.1Image Maps
\7hen a hyperlink is created on an image, clicking on any parr of the image will lead ro opening of the
docurrlent specified in the < A HREF ... > tag. If the image is a large i-rge and there is a needlo [nk
multiple documents to_ the same image, there has to be a techniqr" th.t divides the image into multiple
sections and allows linking of each secrion to a differenr document.
The technique that is implemented to achieve this is an Image Map.Image maps can be created and
applied to an image so specific portions of the image can be [nled to a different filelimage.
Linked regions of an image map are called hot region and each hot region is associated with a
filename.btm document that will be loaded into the browser (navigated to) when the hot region is
clicked.
M.S. University - D.D.C.E. Graphics and \X/eb Pages 63
Create an image map, i.e., divide the image into various areas. This is done using the <MAP)
< /MAP > tags. The < MAP > tag takes an attribute, NAME, via which the map ...r1. referenced in
an HTML file.
Syntax
Step Two
Deals with applying the image map to a particular image. For this purpose, the < IMG > rag takes an
attribute called USEMAP that takes the name of the image map as a value, and applies the map
specification to the respective image. The value is always preceded with the # sign.
Syntax
Specifies a low-resolution image file. A netscape browser will first load the smaller, low-resolution file
specified by Lo\7SRC and will then load the larger SRC-specified image file.
54 Internet and its Applications M.S. University - D.D.C.E.
USEMAP:'url'(I{TML 4)
heck Your
1. Define SRC attribute.
2. Define image maps.
4.6 KEY\T/ORDS
Graphics: Static or animated images.
4. Name some tools, other than the one given in the book, with which images can be created for
adding to web pages.
5
HTML TABLES AND FRAMES
CONTENTS
5.0 Aims and Ob.iectives
5.1 Introduction
5.2 Tables
-
M-S. Universitv - D.D.C.E. HTML Tables and Frames 67
5.1 INTRODUCTION
A table is a two dimensional maffix, consisting of rows and columns. Tables are intended for displaying
data in columns on a web page. All table related tags are included between the < TABLE > < /TABLE >
tags. Each row of a table is described between the (TR) </TR> tags. Each column of a table is
described between the <TD > </TD > tags. HTML tables are discussed in this lesson in detail.
The HTML tags that divide a browser screen into two or more HTML recognizable unique regions is
the ( FRAMESET > < /FRAMESET > tags. Each unique region is called a frame. Each frame can be
loaded with a different document and hence, allow multiple HTML documents to be seen concurrently.
The HTML frame is a powerful feature that enables a web page to be broken into different unique
sections that, although related, operated independently of each other. \Ve will discuss frames in this
lesson in detail.
5.2 TABLES
Table rows can be of two types:
. Header rows (A row) thdt spans across columns of a table)
A table header row is defined using ( TH > < /T}{) tags. The content of a table header row is
automatically centered and appears in boldface.
. Data rows (Indioidual data celk placed in tbe borizontal plane creates a data row)
There could be a single centered data cell (i.e., a single column table) or multiple data cells (i.e., a multi
column table).
Data cells hold data that must be displayed in the table. A data row is defined using ( TR > < /TR >
tags. Text matter displayed in a data row is left justified by default. Any special formatting like
boldface or italics is done by including appropriate formatting tags inside the ( TR > < /TR ) tags.
An image can also be displayed in a data cell.
The attributes that can be included in the < TABLE ) tag are
ALIGN Horizontal alignment is controlled by the ALIGN attribute. It can be set to LEFT, CENTER, or
zuGHT.
VALIGN Controls the vertical alignment of cell contents. It accepts the values TOP, MIDDLE, or BOTTOM.
'$rIDTH Sets the IfiDTH to a specific number of pixels or to a percentage of the available screen width. If
width is not specified, the data cell is adjusted based on the cell data value.
BORDER Controls the border to be placed around the table. The border thickness is specified in pixels.
CELLPADDING This attributes controls the distance between the data in a cell and the boundaries of the cell.
CELLSPACING Controls the spacing between adjacent cells.
COLSPAN The COLSPAN attribute inside a < TH > or < TD > tag instructs the browser to make the cell
defined by the tag to take up more than one column. The COLSPAN attribute can be set equal to
the number of columns the cell is to occupy. This attribute is useful when one row of the table needs
to be a cenain number of columns wide.
RO\7SPAN The RO\(SPAN attribute works in the same way as the COLSPAN attribute except that it allows a
cell to take up more than one row. The attribute can be set by giving a numeric value. For example,
RO\flSPAN - 3
68 Internet and its Applications M.S. University - D.D.C.E.
Quotation marks were used for each value. Line breaks when you are writing HTML code in the text
editor are acceptable and white spaces between your lines or par^graphs are also acceptable and will
'Web
not show up in the complete \7eb page. (\flhite space in the HTML code of the document does
not get into the \7eb page.)
ALIGN values o{ left I center I rigbt have been defined by the HTML 3.2 specification. The default
value is "left". If you do not code the align attribute the browser will assume that the table is aligned to
theleft. If youcode (DIVALIGN:"center") beforeatableand </DiV> afteratableanddonot
code an align attribute, the table will still be centered.
Note:
The <CENTER> element has been deprecated by HTML 4.0 to be supplanted by coding <DiV
ALIGN: "center" ) and < /DIV >.
<TABLE ALIGN= "center " >
Text wrapping did not occur. You do not see text on either side of the table aligned in the center.
Advanced techniques of style can force the issue but advanced techniques are not covered in this
tutorial. The important thing to remember is that when a table is aligned in the center using only
HTML coding that the text will not appear on either side of the table.
ALIGN was not mentioned when this table was coded.
Align was not specified for this table. ALIGN:"left" is the default value so the browser aligned this
table to the far left, even avoiding any margin settings. The text did not wrap to the right of the table
because the attribute ALIGN was not coded. Do not assume that if you need a left aligned table and
left is the default, then you will not have to code the ALIGN: "left" to get text wrap. (See next table).
< TABLE ALIGN = "left" STYLE= "margin-right:15px;" >
\ilhen ALIGN: "left" is coded text will wrap to the right of the table.
<HEAD>
<TR>
<TH>NAME</TH>
<TH>AGE</TH>
</TR>
<TR ALfGN=CENTER>
<TD Tapas</TD>
<TD>21</rD>
</TR>
<TR ALIGN=CENTER>
<TD>pradeep< /TD>
<TD>25</TD>
</TR>
< /TABLE>
< /CENTER>
< /BODY>
< /HTML>
< /TR>
<TR ALIGN=CENTER>
<TD>Pradeep< /TD>
<TD>2 5< /TD>
< /TR>
< /TABLE>
</CENTER>
<HR>
</TR>
<TR ALIGN=CENTER>
<TD>Pradeep<,/TD>
<TD>25</TD>
< /TR>
</TABLE>
</CENTER>
</BODY>
< /HTML>
between.
72 lnterner and its Applications M.S. University - D.D.C.E.
<HEAD>
<TH COLSPAN=3>MARKS
</TR>
<TR>
<TH>PowerBuilder
<TH>VisualBasic
<TH>Oracle
< /TR>
<TR ALIGN=CENTER>
<TD>Tapas
<TD>2 5
<TD>3 5
<TD>4 5
M.S. University - D.D.C.E. HTML Tables and Frames 73
< /TR>
<TR AI,IGN=CENTER>
<TD>Pradeep
<TD>26
<TD>3 6
<TD>46
< /TR>
NAME:"name Gives the frame a unique name so it can be targeted by other documents. The
name given must begin with an alphanumeric character
SCROLLING Controls the appearance of horizontal and venical scrollbars in a frame. This takes
the values YES / NO /AUTO.
74 lnternet and its Applications
M.S. University - D.D.C.E.
ROTUTS This attribute is used to divide the screen into multiple rows. It can be set equal to a list of values.
Depending on the required size of each row, the values can be:
A number of pixels
Expressed as a percentages of the screen resolution.
The symbol *, which indicates the remaining space.
COLS This attribute is used to divide the screen into multiple columns. It can be set equal to a list of lr.1*"
Depending on the required size of each column, the values can be:
A number of pixels
Expressed as a percentage of the screen resolution
The symbol *, which indicates the remaining apce.
The above command will divide the browser screeninto two vertical frames, the first frame called Part
that will occupy 3Oo/o of the browser area and the second frame called Main will occupy 70/o of.rhe
browser area.
Hyperlink Specification:
<A HREF = "Index.htm" TARGET = "AMIN") Visit us </A>
Here an HTML file called Index.htm is loaded into the frame named Main when the hyperlink 'Visit
us'is clicked.
5.15 KEY\T/ORDS
Table: A two dimensional matrix, used for displaying date in columns on a web page.
Frames: Unique HTML recognizable regions into which the browser screen is divided.
Named Frames: The frame in which a new document is opened while still keeping the one from which
the new documenr was linked.
Target Attribute: Attribute via which the frame name is specified.
M.S. Universitv - D-D.C.E. HTML'Iables and Frames Z7
G) Destination
(d) Arrival and Departure Time
G) Fare
Place a border for the table and use cell padding to present the cell data with clarity. Align the
table in the center of the screen. You should enter, at ieast, details of 5 flights.
2. \7hat are the types of table rows?
3. Create a simple table with 3 columns and 5 rows. Name each column heading as column 1,
column 2 and column 3 and enter some random numbers in each cell.
4. Create a simple table with 3 columns and 5 rows. The table should have a border of 6 with
cellpadding of 6 and cellspacing of 6 and width o{ 60o/o.
5. Create a specimen of a corporate web page. Divide the browser screen into two frames. The frame
on the left will be a menu consisting of hyperlinks. Clicking on any one of these links will lead to
a new page, which must open in the target frame, which is on the right hand side.
'What
6. are the advantages and disadvantages of using frames in designing web pages and the care
one should take while using frames in web pages?
'STrite
7. the HTML code for creating two vertical frames named frameone and frametwo and in
which frameone should occupy l/3rd of the browser and the rest by frametwo.
8. \7rite an HTML code for loading a file named load.htm into a frame named framename when
you click on a hyperlink named "click here".
9. Create a web page of a travel agency. You can divide the browser window into two frames, in
which one frame shows navigation buttons that allow the visitor to the site to move through a set
of related pages that are displayed in separate frame.
2. The splitting of a browser screen into frames is accompanied with the ( FRAMESET >
and </FRAMESET tags embedded into the HTML document. The <FRAMESET>
< /FRAMESET > tags require one of the following two attributes depending on whether
the screen has to be divided into rows or columns.
78 Internet and its Applications M.S. University - D.D.C.E.
6
HTML FORMS AND DYNAMIC DOCUMENTS
CONTENTS
6.0 Aims and Objectives
6.1 Introduction
6.2 Information Issues
6.1 INTRODUCTION
Forms are the only method of two-way communication between Veb pages and 'Web sites. Getting
feedback is where HTML forms come into play. HTML supports a rich variety of input capabilities to
let you solicit feedback.
Most new browsers - Netscape Navigator or Communicator 4.0 (and higher) and Microsoft Internet
Explorer (Silindows 95 version 3.0.3 and higher), plus NCSA Mosaic and its varianrs - already include
HTML 4.0level forms supporr, but other browsers do not.
The first step in developing a form is determining which information to include and how ro present ir,
that is, how to break it down into manageable pieces. You then need to ensure that visitors can easily
provide the information you want from them, which means that your form needs to be both
functional and visually appealing.
Also we will discuss the concept of dynamic documents in this lesson.
Vhen you group similar categories, the form appears less daunting, and visitors are more likely to fill
it out and submit it.
M.S. University - D.D.C.E. HTML Forms and Dynrmic Documents 81
Design Issues
A well designed form, helps and encourages visitors to give you rhe information you wanr. A good
form is visually appealing, graphically helpful, and consistent with the remainde, oi th. site. HerI are
some guidelines:
o Use headings to announce each new group of information. This helps visitor's move easily
through the form.
a Be sureto visually separate groups. This makes the forms easier to use because sections become
shoner and easier to read through.
. IJse text emphases to draw rhe audience to important information.
. Specify how visitors are to move through the form. Do not make your visitors scroll horizontally
to access information. Consider making a narrow, longer form rather than a wider, shorter form
to accommodate those who have lower monitor resolution.
. IJse arrows to direct visitors through the page. This can help visitors move through the page in a
specified order.
o Be sure that it is clear which check boxes and fields go with the associated descriptive information.
Use line breaks and spacing to clearly differentiate.
o Specify which fields are optional.
. Use a background image. Be sure, that the image does not outweigh the content and that the text
adequately conrrasrs with the image.
. Make all the text entry fields the same width and put them on the left if you have a verrical column
of name and address information; this way all the text will align vertically and look much better.
. \7hen adding forms suppoft to a \7eb page, you must include special tags to solicit input from users.
You also include tags to gather input and ship it to your'$0eb server. Here is how this works:
. On a particular \7eb page, you include tags to set up a form and solicit input from users. This
essentially amounts to filling out the form that you supply.
. After users fill out your form, they can then direct their input to the program running on the \7eb
server that delivered the form.
. The in{ormation collected from a form can be:
\Written to
0 a file.
(ir) Submitted to a database, such as Informix or Oracle.
(iii) E-mailed to someone in particular.
. Submit and Reset buffions send the form information to the server for processing and return the
form to its original settings.
. Text fields are areas for brief text input. Use these for several word responses, such as names,
search terms, or addresses.
o Select lists are lists from which visitors can choose one or more items. Use them to present a long
but finite list of choices.
. Checkboxes allow visitors to select none, one, or several items from a list. Use them to elicit
multiple answers.
o Radio buttons give visitors an opportunity to choose only one item.
. Textareas are areas for lengthy text input, as in open-ended comments.
M.S. University - D.D.C.E. HTML Forms and Dynamic Documents 83
In general, radio buttons, checkboxes, and select lists are all better choices for accepting input than
textareas.
TaglAttribute IJse
Name -'POINT' SRC - "...' attribute turns off the image border.
SRC-BORDER=O>
<INPUT TYPE - 'RESET' Provides a reset button for a form. The Vaiue -
attribute VALUE - "..." )produces text on the button.
If you want to use an image for your submit bufton, substitute the following code for the submit
button.
<INPUT TYPE = 'IMAGE' NAME = *POINT' SRC = "Submitbutton.gif"
BORDER = 0>
The TYPE :
"IMAGE" attribute specifies that an image will be used to click on and submit the form.
The NAME :
"POINT" attribute specifies that the x, y coordinates where the mouse is located will
't
e returned to the server when rhe image is clicked. Finally, the SRC : and BORDER : attributes
u'ork just as they do with regular images - they specify the URL of the image and turn off the border.
84 Internet and its Applications M.S. University - D.D.C.E
TaelAttribute Use
because it does not accept any other input. You can also
Traditionally, the Submit and Reset buttons go at the bottom of the form immediately above the
closing </FORM> tag.The following example creates a Submit and Reset button by using the
<INPUT> tag, the TYPE : attribute: and the VALUE : attribute.
<HR W]DTH = 80% SIZE = 8 NOSHADE>
<FORM>
If you want to use an image for your submit bufion, substitute the following code for the submit
button.
<INPUT TYPE : "IMAGE'NAME - "POINT" SRC : "Submitbutton.gif"
BORDER : O>
The TYPE : "IMAGE" attribute specifies that an image will be used to click on and submit the form.
The NAME : "POINT" attribute specifies that the x, y coordinates where the mouse is located will
be returned to the server when the image is clicked. Finally, the SRC : and BORDER : atrributes
work just as they do with regular images - they specify the URL of the image and rurn off the border.
M.S. University - D.D.C.E. HTML Forms and Dynamic Documents 85
TaglAttribute Use
because it does not accepr any other input. You can also
SIZE: Sets the visible size for a field. Use this attribute with text
input fieids.
<P>
Please choose the most appropriate statement.
86 Internet and its Applications M.S. Universitv - D.D.C.E.
5.5.4 Checkboxes
Each checkbox works independently from others; visitors can select or deselect any combination of
checkboxes. Using checkboxes is appropriate for open questions or questions that have more than one
" right" answer. In most browsers, checkboxes appear as little squares that contain a checkmark when
selected. For example:
( P ) I'm interested in (choose all that apply):
<BR> <INPUT TYPE = "CHECKBOX'NAME : "reading"
VALUE : "reading" ) Reading
<INPUT TYPE : "password" NAME : "newpass" SIZE - "10" MAXLENGTH : "10" >
\7hen viewed in the browser, each typed character appears as an asterisk ('l).
mouse. The Netscape developers found that limitation intolerable and built in some special features to
their browser that let you change HTML document content vigorously. Actually they provide two
different mechanisms for dynamic documents.. Internet Explorer supports some of these mechanisms,
which we'll discuss as well.
Certainly you could implant animated GIFs or applets that animatedly update the display, but the
primary HTML document itself doesn't change.
\7e should declare that many of the features of dynamic documents have been showed by plug-in
browser accessories and, in specific, applets. However, Netscape and Internet Explorer carry on to
support dynamic documents, and we suppose the technology has virtues you should be aware of, if not
take advantage of, in your HTML documents.
As an alternative of using wallpaper, you can state a solid background colour for your \7eb page. Use
the BGCOLOR attribute in the < BODY > tag. For the colour, you can enter either a hexadecimal
value that represents the colour, or one of 16 standard colour names. The colour names are the
following: aqua, black, blue, fuchsia, gray, green, lime, maroon, na\ry, oliye, purple, red, silver, teal,
white, and yellow. To specify a standard colour, use this tag:
< BODY BGCOLOR:''BLIJE'' )
Using a hexadecimal value is safer, if you want your colours to be read by a broad variety of browsers.
The hexadecimal value is six characters that signify the amount of red, green, and blue in the colour.
The first two characters specify the amount of red, the next two characters the amount of green, and
the final two characters the amount of blue. For example, this code specifies light aqua:
< BODY BGCOLOR:''#99FFFF" )
In the intervening time, if you're designing pages for guests that are principally using Internet Explorer
3, you can make use of the HTML extensions mentioned h.re to enrich yo* p"g., ,rri yorr
spectator's experience.
BORDERCOLOR is functional when depicting a table on a light background. Frequently, there is not a
sharp contra$ between the background and the table border when the background is white or a light
shade of gray.By darkening the border, you produce greater contrast and make the table easier to read.
If you would like to use the shaded rule to achieve a three-dimensional effect, then you can manage the two
colors used to generate the shading with BORDERCOLORDARK and BORDERCOLORLIGHT. Each
can be set to an RGB hexadecimal triplet or to an English language color name.
You can also use the BGCOLOR attribute in a <TABLE>, <TD>, <TH), or <TR> tag to
modify the background color of a table, table cell, or table row, correspondingly. BGCOLOR is also
set identical to a hexadecimal RGB triplet or an English language color name.
Microsoft makes good use of colored table cells on its site. By turning off the borders in the table, the
cell looks like a colored, rectangular block floating on the page, and content in the floating block
stands out nicely.
Your browser will effort to use the font Arial, and then go back to Helvetica and Times Roman until
it locate a font match on the user's computer system. If none of the fonts are found, a default font is
used.
90 Internet and its Applications M.S. University - D.D.C.E.
SLIDE I ALTERNATE Specifies how the text should move in the marquee window
DIRECTION-LEFT IRIGHT Controls the direction in which the marquee text moves
SCROLLAMOIINT:Z Sets the number of pixels of space between successive presentations of marquee text
SCROLLDELAY:Z Sets the number of milliseconds to wait before repeating the marquee text
HEIGHT:plxels I percent Specifies the height of the marquee window in either pixels or a percentage of the
browser window height
riTIDTH:prxels width of the marquee window in either pixels or a percentage of the
I percent Specifies the
browser window width
HSPACE:Z specifies how many pixels to make the left and righr margins of the marquee window
VSPACE=z Specifies how many pixels to make the top and bottom margins of the marquee
window
LOOP=z IINFINITE Controls how many times the marquee text should scroll
ALIGN=TOP IMIDDLE Specifies how text outside the marquee window should be aligned with the window
IBOTTOM
Notice in Table 6.1 that many of the attributes are the same as for the <rMG> tag and that those
attributes work in a comparable way. HETGHT and wrorH define the dimensions of the marquee,
HSPACE and vspacE administer the space around the marquee, and ALrcN controls where ,.rbr.q.,ent
text appears comparative to the marquee window.
of the enduring attributes, BEHAVToR requires some explanation. Setting BEHAVToR ro scRoLL makes
the marquee text scroll on, and then off, the -"rqrr"" window in the direction mentioned by the
DTRECTTON attribute. If erHavroR is set to sLrDE, the text will slide into the window and stay ih".".
If epHavroR is set to ALTERNATE, the text will rebound back and forth in the window.
Marquee text is a nice \fleb page effect that you can complete on other browsers only by using something
more advanced, like Java or Shockwave. Figure 6.1 shows some marquee text sliding onro a page.
M.S. University - D.D.C.E. HTML Forms and Dynamic Documents 91
General Appearance -- The ideal Boxer is a medium-sized, square built dcg of good substance with short back, sfong
limbs; and short, tghffitbng coat. IIis well developed muscles are cleaq hard and appear smooth uoder taut skin I[s
movements denote energr. The gart is firm, yet elashr, the stide frea and ground-covenng, the carriage proud. Developed to
seflrE as guard, wofking and companion dog, he combures rtrength and agilrf wrth elegance and style. IIis expressionrs alert
and trrnperament steadfast and bactable.
The chiseled head imparts to ihe Boxer a uaique rndrvidual stamp. It must be m corract proporiion to dre body. The broad,
blunt muzzle is the distinctive feahye" and great value is placed upon its being of proper fonn and balance with the skull.
Inludging the Boxer, first consideration is gven to general appearance to which atkactive cqlor and arresting style contnbute.
Next is overall balance wrth special attention devoted to the head, after wbich the rndrvidual body components are exanined
for their correct consfuction, and efficiency ofgait rs evaluated
Size, hoportion, Substance Height-Adult males 22 712 to 25 inches, females 21 lo 23 1/2 inches at the vrithers.
-
Preferably, males should not be under ttre minimum nor females over the maximum: however, proper balance and quality in the
Figure 5.1
Marquees functions as electronic billboards. The text is vigorous and it scrolls across the marquee,
where it simply carches the eye. You can manage the speed, style, and direction of the text.
l. Texr marquees can be used for visual effect in your HTML document, but the only browser that
supporrs marquees is Internet Explorer. Most other browsers will display the text, but it will not
scroll, so be careful with the length of your scrolling image.
You can surround the <MARQUEE> tag pair with the (CENTER> tag Pair to center the
marquee on the screen.
92 lnternet and its Applications
M.S. University - D.D.C.E.
2. To place a scrolling text marquee in your HTML documenr, type < MAReUEE > followed by
,
the text and a closing < /MARQUEE > tag. This will cause tlre text inside ih" ,rg to scroll ,.ro5
the screen. For example, to scroll the words Sale! 50% Offl, type (MAnqfief)Sale! 50o/o
off</MARQUEE>.
3. There are several attributes that you can add ro the < MARQUEE ) tag that will allow you to
control its appearance. First, you can control the style of the marquee usiig the BEHAVIC;R tag.
You can make the text scroll, slide, or alternate (bounce back andfonh) inside the marquee. Th"e
default style is scrolling text. To change this to sliding text, r)rpe BEHAVIOR=SLIDE inside
the
< MARQUEE ) tag.
<rrAFquEE EEHAUT0R=SLroEF
4. By default, text in a <MARQUEE> tag moves from the right side of the marquee to the left.
You can reverse the direction by typing DIRECTION:RIGHT inside the ( MAReUEE > rag.
5. You can specify the height and width of the marquee by placing HEIGHT and \trIDTH
.attributes inside the <MARQUEE) tag. The height and width can be expressed as either
specific pixel values or a percentage of the screen. For example, to set the marquee to be exactly
40 pixels high wirh a width of 50 percent of the visible screen, you would type HEIGHT=40
\$ilDTH=SOolo inside the (MAReUEE
> rag.
<HEEQUEE BEHRUIOB=SLIDE DIEECTIOH=EIGHT
HEIGHT=48 trlDTH=s0?+
M.S. University - D.D.C.E. HTML Forms and Dynamic Documents 93
6. You can specify how many times the marquee text will loop by using the LOOP attribute inside
the < MARQUEE > tag. For example, to set the marquee text to loop five times, type
LOOP=5. If you do not use the LOOP attribute, the marquee text will cycle infinitely.
7. The SCROLLAMOUNT attribute allows you to specify how many pixels the marquee moves
each time it is redrawn. This directly affects the smoothness of the scroiling text as well as the
speed with which it moves across the screen. For example, to get the text to scroll slowly and
smoothly across the screen one pixel at a time, type SCROLLAMOUNT:I inside the
< MARQUEE ) tag.
8. You can also control the speed of the marquee text display using the SCROLLDELAY attribute.
This attribute specifies the number of milliseconds that will elapse between each redraw of the
marquee text. For example, to set the delay to 100 milliseconds, type SCROLLDELAY=100
inside the (MARQUEE> tag.
9. If you want to change the background color of the marquee, use the BGCOLOR attribute inside
the <MARQUEE> tag.The color must be specified using an RGB hexadecimal code and
preceded with a pound sign. For exarrrple, to set the background color of the marquee to light
green, type BGCOLOR: #008800.
'What
1,. are submit and reset buttons?
'W'hat
2. are dynamic documents?
The standard HTML/XHTML document model is static. Once displayed on the browser, a documenr
does not change until the user initiates some activiry, like selecting a hyperlink with rhe mouse.i'l The
Netscape developers found that limitation unacceptable and built in some special features to their
bro-wser that let you change HTML document conrenr dynamically. In fact, they provide rwo
different mechanisms for dynamic documents, which we describe in detail in this chapier. Inrernet
Explorer supports some of these mechanisms, which we'll discuss as well. The <uaneuEE> and
</MARQUEE> tag pair places a scrolling text marquee on your \7eb page. The text that scrolls is the
text found between the two tags.
6.10 KEY\$TORDS
Forms: Forms are the only method of two-way communication berween \7eb pages and \fleb sites.
Serclling Marquees: The <manquEE> and < /MAReuEE> tag pair places a scrolling rexr marquee on your
'Web
page. The text that scrolls is the text found between the two tags.
7
PROGRAM DEVELOPMENT
CONTENTS
7.0 Aims and Objectives
7.1 Introduction
7.2 Steps in Programming
7.3 UnderstandingProgramSpecification
7.3.1 Problem-definition
7.3.2 RequirementAnalysis
7.4 Design a Program Model
7.5 Determine Correctness of Algorithm
7.6 Code Program
7.7 Test and Debug the Program
7.8 Documentation
7.9 ProgrammingTechniques
7.9.t LinearProgramming
7.9.2 StructuredProgramming
7.9.|t Example of Structured Programming
7.9.4 Advantages of Structured Programming
7.9.5 StructuredProgrammingTechniques
7.t0 Let us Sum up
7.ll Keywords
7.12 Questions for Discussion
7.I3 SuggestedReadings
7.1 INTRODUCTION
A program is a set of instructions to be executed by the computer to accomplish a parcicular task. In
this lesson we will discuss Steps in Programming Discuss, Design a Program Model, Determine
Correctness of Algorithm, I-Inderstand Code Program, Discuss Test and Debug the Program, Discuss
Documentation.
7 .3.1 P r oblem-definition
The first prerequisite you need to fulfill before designing the program model is a clear sraremenr of the
problem that the program is supposed to solve. A problem definition defines what the problem is
without any reference to the possible solutions. It's a simple srarement, may be one ro r*o prg., and it
should sound like a problem.
The problem definition comes before the requirement analysis, which is a more detailed analysis of the
problem.
The problem definition should be in user language and the problem should be described from the
user's point of view. It usually should not be stated in technical compurer rerms.
M.S. University - D.D.C.E. Program Development 99
Correctness of an algorithm or a program can be checked by any one of the following merhods
1. Dry Run
2. Independentinspection
3. Structuredwalk-through
l. Sintax Enors: Syntax errors occur when a computer language compiler cannot understand a
command entered by the programmer. lVhen such an error is encountered, the computer rejects
the program and prints out an error message. These errors are encountered during compilation
and are very easy to correct. In many cases, these errors arise due to spelling mistakes, missing
commas, etc. and incorrect syntax. For example, in FoxPro if we type APPEND instead of
APPEND this causes a synrax error.
2. Execution Enors: These errors are encountered after error-free compilation, at the time of
execution of the program. Execution errors are also called runtime errors. Typical examples are:
(i) infinite loops
(ir) correct ourpurs only for selected data
(iii) data incorrecr or in wrong order
3. Logical Errors: Logical errors are due to mistakes made by the programmer while coding the
program. The computer does not detect logical errors.
M.S. Universitv - D.D.C.E Program Development 101
For example, for calculating the ner salary of an employee rhe formula is
Net Salary : Basic Salary + Allowances - Deductions
But through oversight, while coding, the formula is written as
Debugging is the process of identifying the root cause of an error and correcring it. It contrasts with
testing, which is the process of detecting rhe error initially.
7.8 DOCUMENTATION
Once the Program has been written and debugged, it is ready for use and hence, requires
documentation or a written procedure of how to run the program, enter data, what problems to
exPect, how to handle them, etc. Documentation of a program will consist of flowcharts/
pseudocodes, Program listings and detailed written statements of algorithms and procedures involved.
Documentation is necessary for program maintenance. \Tithout proper documenrarion, it will be
difficult to change a program ar a later date.
It is a mis-held notion that documentation is the last step in the algorithm developmenr srage. In fact,
it should be interwoven with the entire phase of the programming procerr, .rp..Lily with ihe design
and implementation, because documentation is supposed to enable individuals-ro unierstand the lojic
of programs.
prone and much easier to debug. The techniques for writing such programs are referred to as
structured programming.
7.9.3 Example of Structured Programming
Structured programming refers to the process in which we break the overall job down into separate
piece of modules. Figure 7.1 shows how a salary program is broken down into a number of small
modules. These modules, in turn, are broken down into smaller pieces which can also be further
subdivided. Modules mu$ be chosen in such a w^y that we can specify how they are to interact. In
effect, there is a contact between each pair of modules. This contact specifies two things:
Conveyance
Allowance
2. What assumptions is it making about the behaviour of the other modules? In particular, we must
specify explicitly what inputs a particular module is to receive from the various orher modules
and what outputs it is required to provide for them.
6. It saves time to use modular stnrctures rather than using self-made stnrctures. If a job can be done
well by using what is already available and known to be well tried and te$ed then trying out
something new for the sake of trying is a wasre of effort.
7. Structured programming is a standard method; so, less time is required in writing programs.
8. It is easier to name modules in such a way that they are easy to locate in the documentation, and
consistent.
2. Selection
3. Repetition (iteration)
Now let us discuss each in detail.
Sequence
Sequence structure consists of an action followed by another, and so on, till the desired result is obtained.
Statement 1
Statement 2
Statement n
Seledion
In conditional execution, there is a need to carry out a logical test and then take some particular action
which depends upon the result of that test.
The selection stnrcture consists of a text for a condition followed by two alternative paths for the
program to follow. The program selects one of the program control paths, depending upon rhe
outcome of the test condition. After performing one of the two paths, the program control returns ro
a single point. This pattern can be termed as if. . . else because of the logic.
sequence of statements
else
Itcration
In most cases, programs require that a group of consecutive instructions be executed repeatedly until
some logical condition has been satisfied. Such an iteration is called conditional looping.
Another type of repetition is unconditional looping. In such a looping the instructions are repeated for
a specified number of times.
The control structures are easy to use because of the following reasons:
1. They are easy to recognize.
2. They are simple to deal with as they have just one entry and one exir point.
3. They are free of the complications of any particular programming language.
T.IOLET US SUM UP
A program is a set of instructions to be executed by the computer to accomplish a particular task. A problem
definition defines what the problem is without any reference to the possible solutions. It's a simple $atement,
may be one to two paBes and it should sound like a problem. Requirements describe in detail, what a program
is supposed to do and they are the fint step towards a solution. The requirements activity is also known as
"funaional specification". An explicit set of requirements, is important for several reasons. Explicit
requirements help to ensure that the rxer rather than the prograrnmer drives the program's funaionaliry.
Once the problem is clearly defined, an algorithm, another term for processing logic, can be developed. This
is the most creative part of programming. Correctness of an algorithm or a program means that it gives the
correct output and it does what it is supposed to do. Syntax means the correct way or "grammar' of writing a
command or series of commands, including all the proper options and command-line statements. Semantics
means the logical meaning of a $atement, separate from the grammatical struchrre. Once coding is complete,
you will enter the program into the computer. The computer will then compile the program into machine
code. Debugging is the process of identifying the root cause of an error and correcting it. Once the program
has been written and debuggd it is ready for use and hence, requires documentation or a written procedure
of how to nrn the program, enter data, what problems to expect, how to handle them, etc. Documentation of
a program will consist of flowcharts/pseudocodes, program listings and detailed written sraremenrs of
dgorithms and procedures involved.
Structured programming refers to the process in which we break the overall job down inro separare
piece of modules. Sequence stnrcture consists of an action followed by another, and so on, till the
desired result is obtained. The selection structure consists of a text for a condition followed by. two
alternative paths for the program to follow. In most cases, programs require that a group of
consecutive instructions be executed repeatedly until some logical condition has been satisfied. Such an
iteration is called conditional looping.
M.S. University - D.D.C.E Program Development 105
7.tt l<EY\roRDS
prcgram;A program is a set of instructions to be executed by the computer to accomPlish a particular task.
Requirements Analysis: Requirements describe in detail, what a program is supposed to do and they are
the first step towards a solution
Sjtntax: It means the correct way or 'grammar" of writing a command or series of commands,
including all the proper options and command-line statements.
Semantics:It means the logical meaning of a shtement, separate from the grammatical structure.
Debugging: It is the process of identifying the root cause of an error and correcting it.
Structured.Programming: It refers to the process in which we break the overall job down into separate
piece of modules.
2. Logical errors are due to mistakes made by the programmer while coding the program.
The computer does not detect logical errors.
Byron S. Gottfried, Scbaum's outline of theory and problems of programm.ingwith Baslc, McGraw-Hill
C. Joseph Sass, 8,4SlCprogrammingand applicatioas, Allyn and Bacon
LESSON
8
PROGRAM TOOLS
CONTENTS
8.0 Aims and Objectives
8.1 Introduction
8.2 Program Flowcharts
8.2.1 The Input/Ourput Symbol
8.2.2 The Process Symbol
8.2.3 The Terminal Symbol
8.2.4 The Connector Symbol
8.2.5 The Flowline Symbol
8.3 Pseudocodes
8.3.1 Functional Procedural Layers
8.3.2 The Input Statemenr
8.3.3 The Output Statement
8.4 Decision Tables
8.4.1 DecisionTableCharacteristics
8.4.2 Building Decision Tables
8.4.3 Checking Decision Tables
8.4.4 Developing Decision Tables
8.4.5 Type of Table Entries
'Structure
8.5 Charts
8.6 I.et us Sum up
8.7 Keywords
8.8 Questions for Discussion
8.9 Suggested Readings
. Discuss Pseudocodes
. Understand decision stnrcture
o Discuss structure charts
8.1 INTRODUCTION
As programming is yery typical, and mind crushing work, some aids are required to make the task
simpler and perform it in an efficient way. Some of the aids, or tools are required to develop a
Program are:
1. Program Flowchams
2. Pseudocodes
3. Decision Tables
In the flowcharting technique, operations are represented by drawing appropriate symbols for the
actions.
These flowchart symbols are connected by arrows to illustrate the sequence of operations.
The basic symbols used in a program flowchart are represented in Figure 8.1.
Connector Terminol =
f lowline
Figure 8.1
Figure 8.2
108 Internet and its Applications
M.S. University - D.D.C.E.
Prc*e*s
0utpui
sTop
Figure 8.3
Figure 8.4
@+
o
yes
t
-T*"
?
Figure 8.5
Example 1:
A student appears for a test in 3 subjects. Each test is out of 100 marks. The percentage of each student
has to be calculated and depending on the percentage calculated, grades are given as nexr page.
Percentage Grade
: >90 E+
80-90 E
70-79 A+
60-69 A
50-59 B+
<50 FAIL
Flowchart for the same is given in Figure 8.6.
110 Internet and its Applications M.S. University - D.D.C.E.
ACCEPT M t,M2,M3
DI$PTAY GRADT
PERffi{MI +h42+M3}/?
5T0r
l*
PER >*90 GRADE*'E'
t5
FER >=80 AND G&AE[='['
Figure 8.6
M.S. University - D.D.C.E. program Tools 111
Example 2:
The flowchart to find the factorial for any given number is shown in Figure 8.7. Factorial means the
product of the positive integers l, 2, 3 up"to and including a given irtl.g.r. Factorial is derived by
applying the following equarion:
n! (factorial of n) : n* (n-1)* (n-2)* (n-3). .......*3*2*l
DTSPLAY 'Enler o
vqlue ior N'
ACCEPT N
FAC*l
FAC=FACTNN
Figure 8.7
112 Internet and its Applications M.S. University - D.D.C.E.
Examplc 1:
Fibonacci series is a series of integers in which each integer is equal to the sum of the two
preceding integers in the series. The series is formulated mathemarically by Xi = Xi-1 + Xi-z,
where X0 : 0 and X1= 1; that is 0,1,2,3,5,8....
DISPI-AY 'fnter o
numhar:' ACCEPT N
TWOBACK=0
ONEEACK= 1
Oi5PLAY TWOBACK,
ONEBACK
N:N-2
CURRENI =1
IS
N>0
Yes
CufREhlT = TWOBACK+ONEBACK
TWOBAC(=ONEBACK
ONEBACK=CU*RENT
DISPIAY CI.JR&EN?
Figure 8.8
M.S. University - D.D.C.E. ProgramTools 113
Exanple 4:
The sum of all odd numbers in the range 1 to 10 (i.e. 1+3+5+7 +9:25).
The flowchart to solve ibolre problem is shown in Figure 8.9.
SUM=SUM+N
l5 Nr" l0
Figure 8.9
114 Internet and its Applications M.S. University - D.D.C.E.
8.3 PSEUDOCODES
An alternative method.of program logic is a pseudocode Instead of using symbols to
.representing
rePresent the program logic steps, a pseudocode uses statements which are a bridge belween actual
programming and ordinary English. In a pseudocode, each step is written using a simple English
phrase which is also called a consrnrcr.
Pseudocode notation can be used both at the preliminary srage as well as the advanced stage. It can be
used at any abstraction level. In a Pseudocode, a designer deicribes system characteristics"using shon
English language phrases-with the help of keywords like while, if..the..else, End, etc. Ketsworl, ,rrd
indentation describe the flow of control while the English phrases describe the processing action that is
being_ taken. Using the top-down strategy, each English phrase is expanded into a more detailed
Pseudocode till the point it reaches the level of implemertrttrr.
a Functionalparameters
. Global variables
. Routines called by functions
. Side effects
. Input/outputassertions
Izuel 2:
a Local data structures, variables, etc
. Timing constrainrs
. Exception handling
. Any other limitations
Ituel 1:
3. The beginning and end of a pseudocode is marhed with keywords like 'start' and 'end'
respectively.
4. All statements must include cenain key words which denote an operation.
Some books follow the convention of ending each statement with a semicolon.
For example
Accept Name
Read Name
Example 1:
Accept two numbers, add them and display the result.
The steps for the above problem starement are:
START
ACCEPT Nl
ACCEPT N2
SUM:N1 +N2
DISPLAY SUM
ENI)
The above is a simple pseudocode for our problem. It may be noted here, that whether we input Nl
first or N2 first is immaterial here. However, the statement SUM : Nl + N2 cannot come before the
turo numbers have been input. rUflhat will happen if the DISPLAY SUM sraremenr was put before
SUM:N1 +N2?
115 Internet and its Applications M.S. University - D.D.C.E.
Let us now draw the flowchart for the same example as shown in Figure 8.10:
@
J
Y
@
Y
-r-(m Y
Figure 8.10
In Figure'1 "ACCEPT Nl, N2" denotes that two numbers are accepted from the user and stored in
variables N1 and N2. "SUM : N1+ N2" denotes that a process is taking place, which is adding the
numbers N1 and N2 and the resultant output stored in the variable SUM. "DISPLAY SUM" denotes
that the resultant SUM is displayed on the screen.
Example 2:
Mohan's monthly salary consists of Basic salary, travelling allowances and a l5o/o commission on sales
made. At the end of the month, we need to calculate his salary which is done in the following
pseudocode.
START
Here BAS_SAL, TVL_ALL, SALE_AMT, NET_SAL are variables which hold the value for basic
salary, travelling allowance, sales amount and net salary respectively.
M.S. University - D.D.C.E. Program Tools 117
t
Aec[PT BAS*SAI", TVL-ALL, SALE AMT
SISPLAY NET-SAL
STOP
Figure 8.11
Example ):
SAGA, a grocery store gives discount to its regular customers. The discounts are given irrespective of
the amourit of purchase. Th. ,ror" gives two types of discounts. A trade discount of" 20o/o on total value
of purchase arrd , cash discount of.5o/o on the value of the purchase less trade discount.
Let us calculate and display the gross amount due, the net amount due, the value of the quantity
discount, the value of the cash discount and the total discount along with the product code.
Pseudocode
START
Note.the use of Parenthesis (brackets). This is to give precedence ro rhe arithmetic operarions given
therein. Hence, in the $atement.
CASH _ DIS = 5/100 * (cRoss_AMT _ TRADE_DIS)
TRADE-DIS will be subtracted from GROSS-AMT first then the operarions outside the bracket
will
take place.
Here PR_CODE = product Code
PR_RATE = product rate
pR_eTy = product guantity
GROSS_AI,IT = Gross amount
TRADE_DIS = Trade discount
CASH_DIS = Cash discount
NET_AMT = Net amount
TOT_DfS = Tota1 discount
The flowchanf.or the above example in shown Figure g.12.
Figure 8.12
M.S. University - D.D.C.E. Program Tools 119
Example s of P seudocodes
Exatnplc 1:
A student appears for a test in 3 subjects. Each test is out of 100 marks. The percentage of each student
has to be calculated and depending on the percentage calculated, grades are given as under:
Percentage Grade
: >90 E+
80-90 E
70-79 A+
60-69 A
50-59 B+
< 50 FAIL
The pseudocode for the same is given below:
start
accept m1, m2, m3
pr=(m1 +m2+m3) /3
ifper>=90
grad = 'E+'
else
if p€r >= 80 and per < 90
grade = 'e'
else
if per > = 50 and per < 70
grade = 'a'
else
if per > = 50 and per < 50
grade - 'b+'
else
qrade = 'fail'
endif
endif
endi f
endif
endif
display grade
end
120 Internet and its Applications M.S. Universitv _ D.D.C.E.
Example 2:
The pseudocode to find the factorial for any given number is given below. Factorial means the product
positive integers l, 2, 3 up to and including a given intiger. Factorial is derived by applying the
9f-]h.
following equation:
n! (factorial of n) = n* (n-1)* (n-2;* (n-3). ,.*3*2*!
Pseudocode:
starE
display 'Enter a value for n'
Accept n
fact, = 1
while n ! = 0 ** ! = is a symbol for not.
equal to
DO
fact = fact *n
N=N-1
enddo
display 'The factorial value is i ,, FacT
end
Example 1:
Generate the first 20 numbers in rhe Fibonacci series.
Fibonacci series is a series of integers in which each integer is equal ro the sum of the two preceding
integers in the series. The series is formulated mathematically by Xi : Xi-1 + Xi-2,where Xd : o anJ
X1= 1; that is 0,I,2,3,5,8....
The series looks like:
0+1 - 1, 1+1 :2,1+2:3,2+3 :5,3+5 -8, etc.
If we were required to generate 5 numbers then the series would look like: O l2 3 5...
The pseudocode for the above problem is given below:
Pseudocode:
starE
display 'Enter how many numbers to generate:,
accept n
twoback = 0
oneback = 1
while n > 0
do
current = Ewoback + onebcak
twoback = oneback
oneback = current
display currenL
n=n-1
enddo
end
Examph 4:
The sum of all odd numbers in the range I to 10 (i.e. l+3+5+7 +9=25).
The pseudocode to solve above problem is given below:
Pseudocode:
start
n=1
sum=0
repeat
sum=sum+N
N=N+2
until N > 10
display 'The sum is | ' , SLIM
END
Condition Entries (alternatives) tell which value, if any, applies for a particular condition.
Action Statement lists the set of all steps that can be taken when a certain condition occurs.
Action Entries show what specific actions in a set to take, when selected conditions or combinations
of conditions are rnre.
You can enter a note below the table to help state when ro use the table or to distinguish it from other
tables. The columns on the right, linking conditions and actions form decision rules.
These state the conditions that must be satisfied for a particular ser of actions to be taken. For Decision
Tables unlike decision trees, there is no order sequence. The decision rule incorporated 'all' the
conditions that must be rrue, not jusr one condition ar a rime.
(iv) indicate vhere there are imponant relations or results that others were not aware of, in other
words, not considered.
Thus, using decision tables can produce more complete and accurate analysis.
E lirninating Re dundancy
Decision Tables are likely to get too large if allowed to grow in an uncontrolled way. Removing
redundant entries help to manage table size. Redundancy occurs when:
1. Two decision rules are identical except for one condition row
2. The actions for two rules are identical
Remouing C ontradidions
Decision rules contradict each other when, two or more rules have the same set of conditions and the
actiolls are different. This could occur when either there is an error in constructing the table or when
the analysts receive discrepant information from different individuals about how decisions are made.
Impossiblc Situations
When building decision tables, it is possible to set up impossible situations. Now let us see an example
for impossible situations. One thing we have to make sure is to see that accuracy is maintained and
redundancy is avoided. In Table 8.1 below, rule I is not possible as a person who is earning more than
< 50, 000 per year cannot earn less than { 2,000 per month at the same time.
Table 8.1 Decision table checking for impossible situations
Action 2
2. Determine the number of possible actions that can be taken. This becomes rhe number of rows in
the lower half of the decision table.
3. Determine the number of conditions, alternatives for each condition (rules).
4. Calculate the maximum number of columns in the decision table by multiplying the number of
alternatives for each condition.
5. Fill in the condition alternatives. Start with the first condition and divide the number of columns
by the number of alternatives for that condition. For e.g., for 2 conditions, rhere are 8 rules.
Divide 8by 2 (2.). So write Y in four columns and N in remaining 4 columns as follows:
Conditionl: Y Y Y Y N N N N
Condition2: Y Y N N Y Y N N
Condition3: Y N Y N Y N Y N
According to the decision tree example let us see the decision table given below:
Actions
Conditions and Rules
12345678
Gradebetweenl0-l9 Y Y Y Y N N N N
Gradebetween2}-29 Y Y N N Y Y N N
Gradebetween3O-19 Y N Y N Y N Y N
Actions
Note:It is assumed that all employees exist.
6. Complete the table by inseming an X where rules suggest certain actions.
7. Combine rules where it is apparent that an alternative does not make a difference in the ourcome.
For e.9.,
Condition 1: Y Y
Condition 2: Y N
Action 1 X X
This can be expressed as:
Condition 1: Y
Condition 1:
Action 1 X
The dash () signifies that condition 2 can be either Y or N and the acrion will still be taken.
8. Check the table for any impossible situations, contradictions and any redundancies. According to
the earlier example, there are certain impossible situations and redundancies. Take rule 1, 2, 3
M.S. University - D.D.C.E. Program Tools 125
and 5. In all these rules, there are two Y's, actually speakinB a person cannot have two grades, he
has to be in a particular grade, so these rules have to be eliminated as it is an impossible situation.
The last rule says that an employee exists but then there is no grade given to that employee, here
there isa contradiction, so again this has to be eliminated.
9. Rearrange the conditions and actions (or even rules) if this makes the decision table more
understandable.
Note: The decision table for the example above has been explained in the limited entry table after
eliminating all impossible situations.
1 2 3 4 5
Employee Exists Y Y Y Y N
Grade between 10-19 Y N N N
Grade between20-29 N Y N N
Grade between 30-39 N N Y N
Grade greater than 39 N N N Y
In a limited entry decision table, the conditions are expressed as simple Yes or No questions, whereas
in an Extended Entry table, conditions have more rhar-rwo possible ,rr,"r.
Extended-Entry Form
The extended-entry form replaces Y and N with adion enrries, telling the reader how to decide. Here,
the condition and action statements themselves are not complete, th"erefore, the entries contain more
than one Yes and No.
In the extended entry form the condition is that,
if an employee exists and if he is in the marketing
department fMKT"i, he is eligible for commission. The commission is based on the total sales made
for the monrh and is calculated as follows:
If >:
sales 10OOO then commission is 20olo
Table 8.3
Conditions and Actions Rules
1 2 3 4 5
Employee Exists Y Y Y Y N
Departmeirt MKT MKT ADM MKT
Total sales 10,000 2000 5000
Commission applicable 20o/" 0 n.a. l0o/o n.a.
The decision table above, explains how the commission is given according to the sales per month.
According to these conditions, the actions have to be taken. In the, first rule, the person exists, he is in
the "MKT" department and his total sales is upto 1OOOO, so he is eligible for commission, he will get
commission 20o/o of sales amount.
In rule 3 the person is in "ADM" depanmenr, so he does not have any sales figure, so he is not eligible
for any commission as such.
Mixed-Entry Form
This form consists of combined features of limited and extended-entry forms. Generally, only one
form should be used in each section of the table, but between the condiiion and action ,..riorrr, .i h.,
form may be used.
Now, let us see an example of the mixed entry form, where there are various combination of
conditions and actions taken.
According to the company's rules and policies, following are rhe conditions and acrions to be taken:
For all employee in the grade 10-19 and those in marketing deparcment commission is calculated as follows:
If >:
sales 10000 rhen commission is 20olo
If the person is in any other department then he is not entitled for commission
Second condition is to check, if the employee is supposed to pay income tax. This is done as follows:
If the employee's salary ) : 50,000 - Tax applicable
If salary < 50000 - Tax not applicable
Tax is calculated for employees of all departments.
Table 8.4
All these tables are made while design specifications are made. Each table is made according to a
required module and you can see how each table is designed and how actions are raken.
ELSE Form
This form aims at omitting repetition by using ELSE rules.
To build an ELSE form decision table:
o Specify the rules with condition entries, to cover all sets of actions except for one.
. This will be the rule to follow when none of the other explicit conditions are rnre.
. This rule is the final column on rhe right, rhe ELSE column.
. If none of the other conditions are true, then the ELSE decision rule is followed.
The ELSE rule eliminates the need to repeat condition that lead to the same acrions.
128 Internet and its Applications M.S. University - D.D.C.E.
The conditions for the ELSE form is that the employees of marketing department are given
commission according to the total sales done.
Else
1 2 3 4
Sales ) = 10000 N Y N E
Sales ) :8000and < 10000 Y N L
Sales>-5000and<8000 N Y S
E
Commission t5o/o 207o L?o/o 2o/o
The Else form decision table shown below, has an extra ELSE column. The ELSE is applicable for all
the marketing department employees who have made sales less than 5000.
The first rule tells us that the employee is in the marketing department, his sales amount is between
8000 and less than 10000, so he gets 15olo commission.
Top-down design allows the systems analyst to judge the overall organizational objectives and how
they can be met in an overall system. Then, the analyst moves to dividing that system into subsystems
and their requirements. The modular programming concept is useful for the top-down approach: once
the top-down approach is taken, the whole system is broken into logical, manageable-sized modules,
or subprograms.
Modular design is the decomposition of a program or application into modules. A module is a group
of executable instructions (code) with a single point of entry and a single point of exit. A module could
be a subroutine, subprogram, or main program. It also could be a smaller unit of measure such as a
paragraph in a COBOL program.
M.S. University - D.D.C.E. Program Tools 129
Data passed between stnrcrure charr modules has either Data Coupling where only the data required
by the module is passed or Stamp Coupling where more data than necessary is passed between
modules.
A connection is represented by an arrow and denotes the calling of one module by another. The arrow
points from the calling (higher) module ro rhe called (subordinate) module.
Nore.'The stnrcture charts drawn in the Kendall and Kendall text book do not include the arrowhead
on the connections between modules. Kendall and Kendall draw plain lines between module boxes.
A data couple indicates that a data field is passed from one module ro another for operation and is
depicted by an arrow with an open circle at the end.
A flag, or control couple, is a data field (message, control parameter) that is passed from one module to
another and tested to determine some condition. Control flags are depicted by an arrow with a
darkened circle at the end. Sometimes a distinction is made between a conirol switch (which may have
two values, e.g., yes-no, on-off, one-zero, etc.) and a control flag (which may have more than two
values).
Modules that per:form input are referred to as afferent while those that produce ourpur are called
efferent.
A structure chart is a graphic tool that shows the hierarchy of program modules and interfaces
between them. Structure charts include annotations for data flowing between modules. An arrow from
a module P to module Q represents that module P invokes module
Q. Q ir called the subordinate of P
and P is called the super ordinate of Q. The arrow is labeled by the paramerers receives as inpurs by
e
and the parameters ret.rrned ,, o.rrpr, by Q with the appropriate diiection of flow. F. o
void main ()
{
avg-calculate_average ( a, n) ;
product=calculatejroduct (x, y) ;
)
fl.oaL calculat.e_average( float *x, int size)
t
130 Internet and its Applications M.S. Universitv - D.D.C.E
float sum=0.0;
ant l-;
for ( i=0 ; i<size; i++ )
sum = sum + xlil;
return (sum,/size) ;
)
int cal-culatejroduct( int a, int b)
{
return(a * b) ;
)
calculate_average Calculate3roduct
Structure charts encourage top-down stnrctured design and modularity. Top-down structured design
deals with the size and complexity of an application by breaking it up into a hierarchy of modules that
result in an application that is easier to implement and maintain.
8.7 KEY'$T/ORDS
Flowchart: A program flowchart is a pictorial representation of the logic required to accomplish a task
Decision Table: A Decision Table is a table of rows and columns that shows conditions and actions.
Structure Chart.. A structure chart is a diagram consisting of rectangular boxes representing modules
and connecting arrows.
Percentage Grade
>:90 E
80-90 A+
70-79 A
60-69 B+
50-59 B
< 50 Fail
\7rite down the pseudo code and draw the flow chart for the above problem.
'Write a pseudo code that generates the first 20 numbers in the Fibonacci series.
3.
4. Draw the flowchart to find the factorial of a number given by the user.
5. '\7rite the pseudo code to calculate sum of all odd numbers in the range 20 to 50.
'What
6. are decision tables? Draw the decision table to calculate commission on sales.
The commission is given as follows:
If sales > :50000 rhen 25o/o commission
If sales > :30000 and sales < 50000 r.hen 20o/o commission
If sales > :10000 and sales < 30000 then 10o/o commission
else
9
STRUCTURED PROGRAMMING ISSUES
CONTENTS
9.0 Aims and Objectives
9.t Introduction
9.2 Criteria for a Good Program
9.2.1 Correctness
9.2.2 Reliability
9.2.3 Robustness
9.2.4 ExecutionEfficiency
9.2.5 Ease of Use
9.2.6 Maintainability
9.2.7 Ponability
9.2.8 VerificationwithValidation
9.2.9 Modularity
9.3 Let us Sum up
9.4 Keywords
9.5 Questions for Discussion
9.6 Suggested Readings
9.1 INTRODUCTION
Structured programming techniques imply, that the program development and coding must follow
a
top-down approach and structured programming constructs.
In this lesson we will discuss some crireria used for a good program.
134 Internet and its Applications M.S. University - D.D.C.E.
These criteria's can be met automatically if sufficient thought and effort is invested in every stage of
program design.
Following are the objectives that must be keep in mind while writing a program:
9.2.1 Correctness
A program should produce output as per specification. It should conform to end user requirements i.e.
the user mu$ be satisfied with the output that is produced from the program. Hence correctness is a
very subjective term.
9.2.2 Reliability
A program should function accurately for a long period of time. It must also functions correctly over
all ranges and combination of data.
9.2.3 Robustness
A program must be developed in such a way that it can handle out of range data or exceptional data
without crashing. That is to say that if a program finds some piece of data which is not being handled
by the application than such data should be recognised and an error message should be flashed.
A program should execute in small core memory and should process data fast.
A program should be user friendly i.e. supported by menu options, good user documentation and
on-line help facility.
g.2.6Maintainability
There should be a sensible program stnrcture and use of standard language features so that it is easy to
understand, make changes and enhance.
M.S. Universitv - D.D.C.E. Structured Programming Issues 135
9.2.7 Portability
A program should use standard features of an operating system, language compliers and separate
components dealing with data, peripherals and processing, so that the program can be executed on
different machines. However, some minor changes may have to be made, which are essentially
language dependent and cannot be avoided.
9.2.9 Modularity
Modularity refers to the division of software into separate modules which are differently named and
addressed and are integrated later on in order to obtain the completely functional software. It is the
only property that allows a program to be intellectually manageable. Single large programs are difficult
to understand and read due to large number of reference variables, control paths, global variables, etc.
The desirable properties of a modular system are:
. Each module is a well defined system that can be used with other applications.
. Each module has a single specific purpose.
o Modules can be separately compiled and stored in a library.
. Modules can use other modules.
. Modules should be easier to use than to build.
. Modules are simpler from outside than inside.
Modularity thus enhances the clarity of design which in turn eases coding, testing, debugging,
documenting and maintenance of the software product.
It might seem to you that on dividing a problem into sub problems indefinitely, the effort required to
develop it becomes negligibly small. However, the fact is that on dividing the program into numerous
small modules, the effort associated with the integration of these modules grows. Thus, there is a
number N of modules that result in the minimum development cost. However, there is no defined
way to predict the value of this N.
In order to define a proper size of the modules, we need to define an effective design method to
develop a modular system. Following are some of the criteria defined by Meyer for the same:
. Modular Decornposabilit!: The overall complexity of the program will get reduced if the design
provides a systematic mechanism to decompose the problem into sub-problems and will also lead
to an efficient modular design.
136 Internet and its Applications M.S. University - D.D.C.E.
. Modular Composabilitit; If a design method involves using the existing design componenrs while
creating a new system it will lead to a solution that does not re-invent the wheel.
. Modular Unfurstandabilig: lf a module can be understood as a separare standalone unit without
referring to other modules it will be easier to build and edit.
o Modular ContinuitTt: If a change made in one module does nor require changing all the modules
involved in the system, the impact of change-induced side effects gets minimized.
. Modul.ar Prctection: If an unusual event occurs affecting a module and it does not affect other
modules, the impact of error-induced side effects will be minimized.
One of the key concepts in the application of programming discipline is the design of a program as a
set of units referred to as blocks or modules. A'program module is defined as rhe part of a program
that performs a separate function, e.g., input, input validarion, processing of one type of inpu1. A
Program module may be quite large, so that it may be further divided into logical sub modules. The
Process of subdivision continues until all modules are of manageable size in terms of complexity of
logic and numbers of instructions.
Programs can be logically separated into the following functional modules:
1. Initialization
2. Input
3. Input data validation
4. Processing
5. Outpur
6. Error handling
7. Closing procedure
The modules reflect a logical flow for a computer program. After initialization, processing proceeds
logically with input, input validation, various processing modules, and output. Error handling may be
required during execution of any module.
Basic Attributes
A module is a collection of program srarements with five basic artribures:
. Input
o Output
. Function
. Mechanism
. Internal data
Control Rel.ationship between Modules
The structure charts show the interrelationships of modules by arranging them at different levels and
connecting modules in those levels by arrows. An arrow between two modules means the program
M.S. University - D.D.C.E. Structured Programming Issues 137
conrrol is passed from one module to the other at execution time. The first module is said to call or
invoke the lower level modules.
There are three rules for controlling the relationship between modules:
l. There is only one module at the top of the structure. This is called the root or boss module.
2. The root passes control down the structure chart to the lower level modules. However, control is
always returned to the invoking module and a finished module should always terminate at the
root.
3. There can be no more than one control relationship between any two modules on the structure
chart, thus, if module A invokes module B, then B cannot invoke module A.
C ommunication b e tp e en Mo du le s
A hierarchical (or modular) stnrcture should present many advantages in management, developing,
resting, and maintenance. However, such advantages will occur only if modules fulfill the following
requirements.
I. Coupling: Coupling means the strength of relation between the modules in a system so that
change in one module has limited effect on any other module. It means that coupling should be
minimized.
2. Cohesion: Cohesion means stren$h of relations within the module. It means cohesion should be
maximized.
3. Span of Control: It means number of modules subordinate to calling module. Limit of span of
control may vary from 5 to 7 modules.
4. Siry: The number of instructions contained in a module should be limited as that module size is
small.
5. Shared Use.. Functions should not be duplicated in separated modules, but established in a single
module that can be invoked by any other module when needed.
Your P
sequence. Selection indicates a decision, from among several oprions Repetition or looping consrrucrs
occur, when a set of instructions are to be repeated several times.
A.program should produce output as per specification. A program should function accurately for
a long period of time. There should be a sensible program structure and use of standard lrrrj.r"g.
features so that it is easy to understand, make-changes and enhance. A program shorrli rrl.
standard features of_ an operating system, language compliers and separar. .oriporrents dealing
with data, peripherals and processing, so that the program can be execrrted on difftrent machineJ
Like testing, verification is also intended to find eirors. Executing a program in a simulated
environment to find errors performs it. Modularity refers to the division of
-fr*r.. into separate
modules which are differently named and addressed and are inregrated later on in order to obta^in the
completely functional software. It is the only prope rty that .ilo*, a program to be intellectually
manageable.
9.4 KEY\TORDS
Modularity: Modularity refers to the division of software into separate modules which are differently
named and addressed and are integrated later on in order to obtain the completely functional soft*are.
Cohesion: Cohesion means strength of relations within the module. It means cohesion should be
maximized.
10.1 INTRODUCTION
To solve a computation problem, its solution mu$ be specified in terms of sequence of computational
stePs such that they are effectively solved by a human agenr or by a digital compurer. -o-prrt.,
understandable notation for the specification of such a sequence of computational steps is referredto as
programming language.
Software testing is a critical element of software quality assurance and resenrs the final review of
specification, design, and code. The source-code once generated needs to be tested for bugs and defects
to get rid of maximum errors before the software is sent to the cusromer. Tesr cases are designed with
an aim to find errors.
During initial stages of testing, a software engineer performs all the resrs. However, ar later stages a
specialist may be involved. Tests must be conducted to find the highest possible number of errors,
must be done systematically and in a disciplined way. Testing involves checking both the internal
program logic and the software requiremenrs.
L. Every procedure should carefully specify the input and ourpur requiremenrs.
2. Meaning of variables should be clearly defined.
3. The flow of program should generally be forward except for normal looping and unavoidable
instance.
10.2.1Top-down Design
The top-down design approach is based on the fact that large problems become more manageable if
they are divided into a number of smaller and simpler tasks which can be tackled separately. What is
really required is that each of these parts have the properries of a module.
Top-down design approach is performed in a special way. The main program is written firsr. Ir is
tested before sub programs are written. To do this, the actual sub programs are replaced with stubs.
The stubs simply test to see if the data is passed correctly. After the main program is written and
checked, each module is written and tested in turn. This should first be done without rhe main
Program in order to isolate a stub if an error occurs. A simple main program is written to resr the sub
Programs. U the modules run properly, then it is tested with the main program. If the module and the
main program run properly, then the next module is written and checked and so on. To describe the
Program at its highest level, we use something called the universal program. The proces s of. stepuise
refi.nement work out the details of each part of the program.
Aduantages
L. At each stage, the sub programs are tested by themselves and then the main program is tested.
'tVhenever
modules are added, they are tested with the main program, hence, if. any error occurs ir
will probably be in a module only and this will be easy to debug.
2. It is desirable for modules to be kept small in general. As far as possible a module should be less
than 100lines long.
In the bottom-up approach it is usually assumed that the basic routines creared will be general enough
to be used more than once. Using the subroutines, to construct a program, save yourself repeating the
same lines of code by reusing it. A routine that is used many times has a very difficult srarus ro rhose
higher in the hierarchy. It is more like a basic instruction in the programming language than a large
scale program component.
. It is one of the simplest algorithm design to implement and covers a wide range of problems under
its gamut
. Brute force is a simple but a very costly technique
o Example: Breaking Password.
One approach in optimization is straightforward and requires considerable computation power: brute
force methods which try to calculate all possible solutions and decide afterwards which one is the best.
These methods are feasible only for small problems (in terms of the dimensionality of the phase space),
since the number of possible states of the system increases exponentially with the number of
dimensions. In the case of continuous predictor variables, the number of states is infinite. Despite these
drawbacks, brute force methods do have a few benefits: they are simple to implement, and in the case
of discrete systems, all possible states are checked.
As a consequence, brute force methods are often seen as reference methods for calculating the number
of stares, or the number of calculations necessary to find the optimum with a probability of 100o/o.
Hence, it can be used for the estimation of the effort to solve a problem.
The implemenration of brute force algorithms is rather simple. In fact, one only has to try out all
possible sratesof a system. If this is not possible, because the system is described by continuous
variables, one has to try all possibilities according to a certain definition of precision for each
continuous variable.
Example:
Consider a system which is controlled by 3 continuous predictor variables: x1 to xr: if x,, and xr need a
resolurion of ZOO intervals, and r has to be discretized using 1,000 steps, the resulting number of
calculations in a brute force approach will be 200 times 1,000 times 200 = 40,000,000.
. The objective while designing tests is to come up with the test cases that systematically uncover
different classes of errors in minimum possible time and effort.
t' Test must be traeeable to requirements, Becaus" ,of,*r.. testing reveals errors, so,
cases
the severe
defects will
be those that prevent the program from acting as per rh"e cusromer's
expecrations and
requirements.
2' Test
.planning
must be done before beginning testing. Test planning can begin soon after
the
requirements specification is complete and the detailed t.rt .ri", .rn
b" develoied after the d"sig,
has been fixed.
3' Pareto pinciple applies to solfttaare testing. Pareto principle smres rhat 80 percent
of the uncovered
errors during testing will likely be traceable to 26 p.r.ent of all th. p.ogrr-
components. Thus,
the main aim is to thoroughly test these 20 percenr .o-porr.rr,s after ia.irifyirrg
the*.
4' Testing should begin with small and end in targe. The initial tests planned
and carried our are
usually individual comPonents and as testing p-gr.rr", the aim shifts to find
errors i" irrr.grri.J
components of the system as whole rather than individual componenrs.
5' Exhaustiae testing is impossible. For.a
.normal sized program the number of permutations of
execution paths is very huge. Thus, it is impossibl" to all the combinations possible. Thus,
while designing a test case it should be keft in minds"*...rt"
that it musr cover the maximum logic anj
the componenrJevel design.
6' Eficient testing can be conducted only bit a third pany. The highest probability
of finding errors
exists when the tesring is not carriedly th. p.nf*hi.h J"r.lo!,
th. ,yrt"-.
A program developed should be testable i.e. it should be possible ro resr the program.
The testability of
a Program can be measured in terms of few proglqjes like, operability,
observ"ability, controllabiiity,
decomposability, simplicity, stability, rnd"rsianiability, etc.
The test also, must also comply with the characteristics of a good test case. These characteristics are
mentioned here:
The probability of finding error should be high. In order to achieve rhis, tesrer
' the actual functionality of the software and thirk of a suitable condition ,irr,
must undersrand
.r., lead to failure of
the software.
A test case must be non-redundant. Because the testing time and resources are limired,
' a lot of time to conduct the same test again and again. ivery
it will waste
resr musr have a distinct purpose.
o A test case must-be of the best quality. In a group of similar tesr cases, the one that coyers
the
maximum scenarios to uncover maximum should only be used.
"rro^
A good test case should neither be too simple nor roo complex. A complex
' several other tests can lead to masking of
resr rhar includes
Thus, each t.ri.rr. should L" e*"c,rted separately.
"rro.r.
M.S. University - D.D.C.E. Problem Solving Approaches and Testing Methods 145
A product can be tested in two ways: (1) Knowing the specified function that a product has been
designed to perform; tests can be done to ensure that these functions are existing and that too without
errors; (2) Knowing the internal workings of a product the tests can be performed ro ensure that all the
internal operations are being performed as per specifications and all internal components have been
adequately built. The fi'rst approach is called black-box testinB and the second, white-box testing.
Black-box testing of software refers to tests that are conducted at the software interfaces. These kinds
of tests ensure that software functions are operational, input is accepted properly and output is
correctly produced and that the external information e.g., database is maintained. It does not deal in
depth with the internal logic of the program.
'\tr7hite-box
testing works on the principle of closely monitoring the procedural details of the software.
All the logical paths of the software are tested using test cases for specific conditions and loops. The
actual results are compared with the expected results to ensure that rhe correct results are produced as
a result of the functions being performed.
Test Case ID
Purpose
Pre-conditions
Inputs
Expected outputs
Post-conditions
Execution History
Date
Result
Version
Run by
1. Guarantee that all independent paths within a module have been exercised ar least once;
2" Exercise all the logical decisions based on their true and false sides;
The reason of conducting white-box testing largely depends upon rhe narure of defects in software:
o Logic errors and incorrect assumptions are inversely proportional ro rhe probability that a
program path will be executed.
o \We often believe that a logical path is not likely to be executed when, in fact, it may be executed
on a regular basis.
. Typographical errors are random
Each of these reasons provides an argument for conducting white-box resrs. Black-box resring might
miss out these kinds of errors.
2. test cases that tell us something about the presence or absence of a variety of errors rather than a
particular kind of error.
The techniques are as below:
Consider a function F with x and y as two input variables. These inputs will have some boundaries:
a(:x(:b
P<:y<:q
Hence, inputs x and y are bounded by two intervals [a,b] and [p,q] respectively. For x, we can design
test cases with values a and b, just above a and b and just below a and b which will have higher chances
to detect errors. Similar is the case for y. This is represented in the Figure 10.3.
Action Stub A1 x x x
A2 x x x
A3
x X
A4
x x x
Figure 10.4: Decision Table Terminology
To develop test cases from decision tables, we treat conditions as input and actions as outputs.
Sometimes conditions end up referring to equivalence classes of inputs, and actions refers to major
functional processing portions of the item being tested.
This technique helps in selecting, in a systematic approach, a high-yield set of test cases. It is also useful
in pointing out incompleteness and ambiguities in the specifications. The following steps are used to
derive test cases:
t. The causes and effects are identified. A cause is a distinct input condition and effects are output
conditions or a system transformation. These are identified by reading the specification and
identifying the words or phrases that describe causes and effects. Each cause and effect is assigned a
unique number.
2. The semantic content of specification is studied and transformed into a Boolean graph linking the
This is the cause effect graph.
causes and effects.
3. The graph is annotated with constraints describing combinations of causes and/or effects that are
impossible because of syntactic or environmental constraints.
4. By methodically tracing state.conditions in the graph, the graph is converted into a limited entry
decision table. Each column in the graph represents a test case.
5. The columns in the decision table are converted into test cases. The basic notation for the graph is
shown in Figure 10.5.
M.S. University - D.D.C.E. Problem Solving Approaches and Testing Methods 149
ffi ffi
Your
t. 'What is Cause Effect Graphing Technique?
Testing software can be considered as the only destructive (psychologically) step in the entire life cycle
of software production. Although all the initial activities aimed at building a product, the testing is
done to find errors in software. \7hite-box testing or glass-box testing is a test case design method that
uses the control structure of the procedural design to obtain test cases. Black-box testing or behavioral
testing, mainly focuses on the functional requirements of the software. It enables the software engineer
to develop a set of inputs that can fully involve all the functional requirements for a program.
150 Internet and its Applications
M.S. University - D.D.C.E.
10.8 KEY\TORDS
white-box Testing: \7hite-box resring or glass-box resring is a resr case design method
that uses the
control srructure of the procedural design io obtain t.rt .r-r.r.
Black-box Testing: Black-box resring or behavioral testing, mainly focuses on the
functional
requirements of the software.
Top'down Design: The design approach is based on rhe fact that large problems become more
.top-down
manageable if they are divided into a number of smaller and simpler tasks which".."
U. tackled separately.
BVA: The art of testing is to come up with a small set of test cases such that the chances
of deteaing an error
are maximized while minimizing the chances of creating redundant resr
ciles that uncover similar errors.
Brute Force Approach: It is a straight forward approach to solve the problem.
Equiaalence Cl.ass Testing: In this method of testing, input domain of a program
is divided into a finite
number of equivalence classes such that the test of , ,.ir"r.ntative ,alrre of-each class
is equivalent to a
test of any other value.
Deeision Tables: These are useful for describing situations in which a number of combinations of
actions are raken under varyingsets of conditioni.
5. Discuss the basic principles of testing used to design efficient resr cases.
6. Differentiate between white box testing and black box tesring.
7. Differentiate between Boundary Value Analysis and Equivalence class resring.
tt
CLIENT.SIDE AND SERVER.SIDE PROGRAMMING
LANGUAGES
CONTENTS
11.0 Aims and Objectives
11.1 Introduction
It.2 Client-side Scripting Languages and Server-side Scripting Languages
ll.2.l Client-sideLanguages
tL.2.2 Server-side Languages
Contd..
154 Internet and its Applications
M.S. University - D.D.C.E.
11.1 INTRODUCTION
In the computer networking environment client server model
is used. server compurer (also called a
host computer) .o-prt., orl
is 4 LUurPuLsr
LUrl rJ on rnethe nerworK
network that provtdes
provides information and services to client
rnformation
' manages network resources.
computers' Server also For example, a file server is a computer and
storage device dedicated to storing files. Any user on
the network can srore files on rhe server. A print
server is a computer that manages one or more printers,
and a network seryer is a computer that
manages network traffic. A database server is a comp.rter
sysrem that process", drirb.r" queries.
The client comPuters- are the systems who needs the services
of server computer. The term ,,client,,
was first applied to devices that were not capable of running
their own stand-alone programs, but
could interact with remote computers ,i, a network. These "dumb"
terminals were clients of the
time-sharing mainframe computer. The clienr-server model
distinguisher .li;;-ryrrems from seryer
systems, which communicate over a computer network.
A clieniserv* ,ppli;r;ion is a distributed
system comprising both client and server software.
A client rofr*rr"-ffi"r, -ry initiate a
commuriication session, while the server waits for requests
from any client.
The client/server model has become one of the central ideas
of network computing. Most business
applications being written- today use the client/serve,
-od.l. so does the Interner's main program,
TCP/P' In marketin8, the term has bee.n used_to distinguish distributed computing by smaller
dispersed computers from the "monolithicu. centralized
.o-fr.rtirg of mainframe computers. But this
distinction has largely. disappeared as mainframes and their
applications have also turned to the
client/server model and become part of network .o-prrtirrg.---
M.S. University - D.D.C.E. Client-side and Server-side Programming Languages 155
In the usual networking environment, one server, sometimes called a daemon, is activated and awaits
client requests. Typically, multiple client programs share the services of a common server program.
Both client programs and server programs are often part of alarger program or application.
'tVe
propose that all client/server systems have the following distinguishing characteristics:
. primarily a relationship between processes running on separate machines.
Sentice: Client/server is
The server process is a provider of services. The client is a consumer of services. In essence,
client/server provides a clean separation of function based on the idea of service.
a Shared resources: A server can service m^ny clients at the same, time and regulate their access to
shared resources.
o Asymmetrical protocol: There is a many-to-one relationship between clients and server. Clients
always initiate the dialog by requesting a, service. Servers are passively awaiting requests from the
clients.
. Transparenclt of location: The server is a process that can reside on the same machine as the client
or on a different machine across a network. Client/server software usually masks the location of
the server from the clients by redirecting the service calls when needed. A program can be a client,
a server, or both.
. Eneapsulation of seraices; The server is a "specialist." A message tells a server what service is
requested; it is then up to the server to determine how to get the job done. Servers can be upgraded
without affecting the clients as long as the published message interface is not changed.
o Scalabilitjt; Client-server systems can be scaled horizontally or vertically. Horizontal scaling means
adding or removing client workstations with only a slight performance impact. Vertical scaling
means migrating to a larger and faster server machine or multi servers.
o Integitg; The server code and server data is centrally maintained, which results in cheaper
maintenance and tile guarding of shared data integrity. At the same time, the clients remain
personal and independent.
this script in client-side scripting languages. Client-side scripr is used for client-side validarion and other
oPerations such as drop down menus, moving fonts. For example when user fills in an entry form,. ro
ensure that user has typed all necessary fields we require to write code to verrfy this before saving it in
database. This validation code can be written to execure on server-side or client*ide. If we wriie this
code in client-side scripting language this will save time and traffic load between server and client.
Examples of client-side scripting language are JavaScript and VB Script.
. CJJ. CSS is a language that assists you separate conrenr and formatting. It's not a programming
language, but it helps you classify text and imaging formatting for your io.rt.rrt mor. simply than
HTML does.
. Jauasdpi: A script language that assists you make your pages more vibrant. Simple uses involve
dynamic menus and effects. You can write complicated sofrware using Javascript, see the
'Asynchronous web' part below.
. Other sctipting languages: There are more options for client-side scripting, such as VBScript. But
these are less common then Javascript
All of these languages are actually part of the HTML page, they just make it better. \ile'll discuss them
later on.
A variable must be declared with a name and a particular data type. Since VBScript supports only one
datatype, Variant, all variables will be declared as Variant by default. Here are some rules on variable
declaration:
1. Explicit Declaration - A variable is declared with the "Dim" statement in the following syntax:
Dim variable_name, ...
where "variable_name" is a text label to recognize this variable. Multiple variables can be declared
with single "Dim" statement. The data type of this variable will be Variant.
Note that, in Visual Basic, you are permitted to identify a panicular data type in the Dim
sratement, because multiple data types are supported in Visual Basic. So the subsequent statement
is valid in Visual Basic:
o DateAdd(sTyPe, ilnterval, tDate) - Returns a date to which a specified time interval has been
added
'
\x/eekday(tDate) - Returns a number that represenrs rhe day of the week (between
I and 7,
inclusive)
\VeekdayName(i\TeekDay) - Returns the weekday name of a specified d,ay o{the week
'
o Year(tDate) - Returns
a number that represents the year
Date data type not only provides a place to store a date but
also performs many tasks on a Date variable,
such as adding or subtracting time, comparing dates and obtaining
the System date and time.
The format of the time may be formatted using 'h', 'm', 's' and 'tt' characters:
Format(#1:02:00PM#, "hh:mm:ss tt") - rerurns as 01:02:00 pM
Format(#1:02:00 PM#, "hh:mm:ss") - returns as 01:02:00
Format(#1:02:00 PM#, "hh:mm") - returns as 01:02
For example:
(months)
11.5.1 Addition
Addition is performed in Visual Basic using the plus (+) operator.
Purpose: To add rwo numeric rype data values.
Syntax: result = expressionl+expression2
The + operator synrax has these parts:
Part Description
Result A required numeric variable. k cannot be constant.
expression 1 A required expression evaluating to a numeric value.
expression2 A required expression evaluating to a numeric value.
For exatnple:
Dim intValue As Integer
intValue:10+5+5
Variables may also be used as operands:
intOperator2 : 5
Part Description
Result A required numeric variable.
number A required numeric expression.
Numberl A required numeric expression.
Number2 A required numeric expression.
For example:
A negative number is denoted by prefixing the number with the (-) sign:
intOperator2 : - 67
11.5.3 Multiplication
Visual Basic, like most other programming languages, use the (") operator (rather than the x we all use
when writing mathematical expressions) to perform multiplications.
Purpose: To multiply two numbers.
For example:
71..5.4 Division
Division is achieved in Visual Basic using the / operator. In division, the left hand operand is divided
by the right hand operand. For example, the following example returns 5 (20 divided by a):
Dim intValue, intOperatorl, intOperator2 As Integer
intOperatorl : 20
intOperator2 : 5
intValue : intOperatorl 'f intOperator2
Diaision-1
Symbol: /
Purpose: To divide two numbers and return a floating-point result.
Diaision-2
Symbol: \
Purpose: To divide two numbers and return an integer result.
Part Description
Result Required; any numeric variable.
11.5.5 Exponentiation
Exponentiation involves raising a number to a parricular power. For example 103 which would
evaluate to 1000. The carat (^) character is used to represenr exponenriarion in Visual Basic:
Part Description
Resub Required; any numeric variable.
10 Mod 2 - returns O
10 Mod 4 - rerurns 2
12 Mod 5 - returns 2
Symbol: Mod
Purpose: To obtain remainder by divide rwo numbers.
The name on the left side of the equal sign can be a simple scalar variable or an element of an array.
Properties on the left side of the equal sign can only be those properties that are writable at runtime.
In this section, we will discuss some of the built-in mathematical functions available in VBScript. Most
o{ those functions ere very simple to use. Table 11.1 provides a reference to mathematical functions
available in VBScript.
Tablel 1.1: Built-in Math Functions
Here is a swift review of some of the incorporated math function available in VBScript:
o Abs (number) returns the absolute value of a number. In other words, if the number is greater than
or equal T.o zero, the number is returned. If, however, the number is less than zero, thelegation of
the number is returned. For instance, Abs (5) would rerurn 5 and Abs (1) would rerurn 1.
. Exp (number) raises e (approximarcly 2.71828) to the power number. For example, Exp (5) says
e^5, which is approximately 148.41315.
. Fix (number) returns integer portion, greater than or equal to the number. For insrance, Fix (-5.80)
returns -5.
. Int (number) is different from Fix(number) because Int (number) rerurns integer porrion less than
or equal ro number. For example, Int (5.80) rerurns -5.
. Hex (number) returns strings consisting of the number converted to hexadecimal base. For
example, Hex (10) rerurns A, Hex (11) returns B, Hex (12) returns C, erc.
o Oct (number) returns strings consisting of the number converred to octal base. For instance Oct
(8) returns 10, Oct (9) returns 11, Oct (10) returns 12,etc.
o Round (number) rounds a number to the nearesr integer; for example, Round (5.+5) rounds 5.45 to
6 and Round (5.01) returns 5.
o Round (number, dec) rounds a number to dec decimal places. Round (5.45, 1) rounds 5.45 to 1
decimal place: 5.4. Round (100.67899,3) returns LOO.679.
. Sgn (number) returns -1 if number is less than 0, 0 if number is O, and 1 if number is greater than 0.
Consider the following as examples: Sgn(5.9) rerurns -1, Sgn(O) rerurns O; and Sgn(s)ieturns 1.
o Sqr (number) (number > 0) provides a square root of number, provided the number is positive.
For example, sqr (4) returns 2, sqr (100) returns 10.
11.7.1If - Then
Life is full of choices (isn't it so nice??). \We look around and what do we observe? -il/e are constantly
making decisions every day. rVe leave home and if it is raining, we take our raincoats along. Our
mother might say, go to the market and buy 5 kg potatoes if potaioes cost less than 10 rupees a k"ilo.
In programming terms, we can say this: 'if it is raining, 'then' put on the raincoat. Similarly, 'if' potatoes
are ( Rs. 10/kg, 'then' buy 5 kgs. The underlying concepr is this: 'if' a condition is 'rrue' 'theniwe will
take some action. The same approach can also be applied io progrr-ming. \(e can specify a condition to
VB. 'If' the condition given by us is true, 'then' all of the sratemenrs foltwing thelif'will be execured,
otherwise VB will jump over those statements. For example, the following lines of code
Code Listing if.l
IF textl . TEXT - ,'Shreyas,, THEN
MSGBOX " Hello " & " Shreyas
END IF
M.S. University - D.D.C.E. Client-side and Server-side Programming Languages 157
will display with the message "Hello Shreyas" printed on it, 'if' Textl contains the text
a message box
'shreyas'. If Textl does not contain the text Shreyas, the message box will NOT be displayed. Take
another example. Suppose there are two integer variables, named int_a and int_b. Analyze the code
segment that follows.
This brings us to the general syntax of the If - Then statement, which is as follows:
If condition Then
..'..'
'if condition is false none of these statements will be executed
End If
11.7.2If-Then-Else
In our discussion of if-then, we have so far considered only one option. That is,
if int_a ) int_b, then print int_a
But what if we want to print int_b if int_a ) int_b' is not true? The simple if-then does not offer
another option, i.e., it does something if the condition is true, but does nothing if the condition is
false. This extra option is offered by if-then-else, a modification of the simple if-then we have just seen.
To see this in action, we will modify the Code List if.1 as follows:
Code Listing if.3
IF textl.Text = "Shreyas" THEN
MSGBOX "Hel1o" & "Shreyas"
ELSE
MSGBOX "Hello" & "Mr/MissNoName"
END ]F
168 Internet and its Applications M.S. University - D.D.C.E.
In this code, VB will check for the contents of Textl. If the text enrered in "Texrl" is "Shreyas", the
message box "Hello Shreyas" will be displayed. If the text enrered is not "Shreyas" but anphing else,
the message box "Hello MrlMiss No Name" will be displayed. Modifying the Code List if.|
Code Listing if.4
rF int_a > int_b THEN
textl.TEXT = int a
ELSE
textl.TEXT = int b
END IF
this will display value of the variable int a in Textl if the condition [int_a > int_b] is true. Otherwise,
it will display value of the variable int_bln Text1.
General Syntax andWorking of lf-Then-Eke
This code segment shown below will work this way, depending on whether the condition following
'if is true or false:
. Condition is true: All of the statements following 'then' will be executed, unril VB comes across the
i
keyword 'else'. Once 'else' is reached, VB will 'jump over' all of the sratements berween 'else' and
'end if' and come out of the 'if - then - else' block. It will then continue the normal.
Program
execution after the 'end if' statement.
. Condition isfalse: None of the $atements following'then'will be executed. However, all of the
statements following 'else' will be executed, until the time VB comes across the keywords 'end if'.
After 'end if is read, the 'if - then - else' block will rerminate. VB will then continue rhe normal
execution of the program after the 'end if' statement.
The general syntax of if-then-else srarement is as follows:
If condition Then
Else ------
End If
11.7.3 Multiple (Nested) If - Then Statements
The code segment we have used in discussing if - then - else works fine if one of the numbers is greater
than the other one. But what if both the numbers are equal? Suppose we gave the value of
int_a : 10
and
int_b : 10
what will be the output of Code List if.4? The result will be ..... you guessed it right, 10! The Code List
if.4 checks for [int_a > int_b] , i.e. 10 ) 10. Since this condition is not true, i.e. false, the $atements
following 'else' will be executed, which print the value of int_b which, in the Present case, is 10. As is
obvious, if..then..else is most effective when there are only two v/ays to go. In the Code Listing rf..4,
the possible outcomes are -
int_a ) int_b or int-a < int-b or int-a - int-b
As we can clearly see now, a simple if..then..else will be ineffective in the case just mentioned above,
'\tr7e
since, this situation has three possible outcomes. therefore need three blocks to effectively deal
with the three different outcomes. Hence, we need another block in addition to the 'then' and 'else'
'We
block that 'if..then..else' offers. can get this option by adding another if..then block 'inside' the
existing if..then..else block., like this:
Code Listing if.5
IF int-a > int-b THEN
textl.TExT = int-a 'printed when a > b --- 1
ELSE
IF int-a < int-b THEN \ --- 2
texEl.TEXT = B'printed when a < b --- 3
ELSE
textl.TEXT = "both are egualu '--- 4
END ]F
END IF
Observe from Code Listing if.5 that for every end if has to be used. The 'inner'
if, a corresponding
if..then is represented by block 'I', the 'outer' if..then by 'O'. The code nrns as follows:
170 Internet and its Applications M.S. University _ D.D.C.E.
o This code will first check for fint-a > int-bl. If the condition is true, rhe program goes
to line
number '1',, prints the value of inf a' in Textl, and ships over all of the other lines. It
then comes
out of the if-then blocks.
If int a ) int-b is false, the program goes ro line '2' and checks for fint_a < int_b]. If this
' condition is true, the program goes to line'3'and prints the value of 'Lt b'in T.itt. It then
comes out of the if-then blocks.
However, if this condition fint-a < int-b] is also false, then it is obvious that both the numbers
' are equal' Hence, the program switches to line number 4 and prints the message 'both
are equal' in
Textl.
It is imponant to realize the fact that the inner block 'I' musr be completely inside the outer block
'O'. If this is nor done, we will ger wrong results.
General Sy ntax of Muhip le lf-T hen-E ts e
The general synrax for multiple if-then-else srarements is as follows:-
IF conditionl THEN
ELSE
IF condition2 THEN
'execute all of these lines, ending at "else,,
ELSE
cn
o
o
J
(D o
o- s sffg o
=
co @ Po 5'
g) o
v,
o
at, oo
€3 H=iE
E' 3 $ro o g *(D _ (r,m
=(,)=:.r
f,(D
o
=!.
)
o
c 8a9) q, <oPd luoqrrJncul o'E
U,2
= =
J
o aql lo aruBN *6.
o sSee 5
a (D
t oE 3
= (D
EB=Q
:9o g9
J
StrNINIItrEI o)
=
CL
-t I I r I I I I
t-
G.P.F.
Conbibution DEDUCATION
EE
I II
-e' o
.E
o
= E
o \.o E E
a*.
€E €s
.o
C)
(6
(!e
ES E
E€
f o_E Acquittance
rei
>E-'
Ocn'
=
$(6
=i
E<
(E
B.e
o'6
E(l)
o
(tt
E5
=F
E
I c6-
g(D
L
:< (Do. P
(s
E
8s zo
e s H
-l
],C
u) TI
o U 'u
T6bB
= g? IJ
-l
m
I
A)
0)
g
-J)ll^ @-r I t-
m-TY o
jgIsggsSu= 3: Bttfr m m
4m tr 0)
\oD o
ll
AV^-69[E'.o6=D E: ? T'C z{
o BT - rE
F $ u i + + A A fr ;; I s; m
o
.TI
r
5 o .T'I
E
o
t
ssgg
;; =rr mgilfl*
s-='=Q
ll
m
rl
Hs 88
al+il
cJ 5$=5r I! zm
z-l
b
ssq$
=Eu3 pB $E
ii-td6- jj OA=@Uf=-
o
o
o -l
m
q=6'
3L
=6
frd
?=
e= - =.
tl) =.a *O
o
!
o
a
{3 o7
=E
e
c:'6
o Eg
=g s1
6 fl G
o
EE
:8 3= o
=.
(o m
@
-t
@
=
Ar{
u.=
1s*-,gB8f;FFF4 i3 =o 6' (! 3z
v=.tJ
d-
r r @ o(o
o
tr
U)
- ;iFP
=-5J
= .o- zm= {
crI
tso
o
P
Io
l'l tr
g=
iFilEI.E+'3Ffr*r o
-m
(r
-: n
s6 q
CL
o
;\r
6-
oi oTo <- oo'0 o)
(D
o3 > be
CL ct)
E
0)
o o
o
0)
rO J Or g,g q'
-{
o 6
3td88Q8888BetH o OE
0)
o
T rs(J)r
WA
lttttlt!tttt \.,
-r+
6'
o
-
o
m
)
o
o
o
3
o
=
(Under Rupees
zo
o
C
E
CC
il 0111 Ed
EEEE ilo $EFqeaf
a-b'-d aa-ig*gg$6
=3
J)
5(D
a
o7
(D=.
U'6
rEEFE*flE'riE BEEH
5'o-
€o'
o- EilEHffiEilI:$:
*il ulHElg*: q d
v (<:
3
o
J
H.
'*i $ Ff
==a=iEq
:3 da a
\to B =
a
5
{
fFBsHts*=E3E;a€Ie
{trl
a
z =
C)
=z ! +9fl=1==ild5i;It!
Pb==-9 >-u,
o
= ct) o
= ll -F6PZ
z fl I a) C
T
U)
'n
o o m
U, zo @ m -l
m
fl @ I o
gr_
f,
C
== ? I
ll .Tl
zg g
o
m o o
m
a C
fl
m
B5 c
o
:f.
o
U)
L
@
a @ o=
!=
a
?. oluNluNl\)luJ+J++rri
I -! tr,
m
Sat.EilNjo@@{o)or5o)N
a 0) T
U'
0) trrrtlllllllllt
; )
o
a
D
@
o
C)
C o
e C
o a
5'
o
o
6'
o
o
m
a
o
Z
-t
o
z
o
l1
-m-l
t
o
o o
o
-l !,
=
o
o
E'
ct
tt,
z
0)
o
3
3 o
o o
tn
o
J vo
o C
:f
o CL
c o
3 CL
o
o
)
D=O=r\)J
E:P=t-
EE i
o)f!D::f
Ep8
rq;i#g
A,u=Ho.(/)
tr, a
7i
q€ $$ilfl
91! 3 >'
o (o :A
'-rvi ^
g O 6
9.
r==--
\<=-
=--=
---)
-^61
m f;FBF
9<t -g
tr,
o
e.3
dr
ai
s'J
+o
TI
o
'n
BSro
- (Do='
'n EQ*ol
o
m
(D -:r()
(, o
-O*9
o Pr
-=Xo-
o;i+g
oEr9
i8fr=
H =I-
silg
d. s 6'9
9Jo?
:(/)*<dqB
J =
M.S. University - D,D.C.E Client-side and Server-side Programming Languages 171
As seen in the figure above, all of the block lines are complete and none of the block lines are
intersecting one another. However, in the figure on the right, the outer and middle block lines are
intersecting towards the bottom-right of the figure. In this situation, we get run-time errors that are
difficult to handle.
;;,.
End If
The advantages of this approach are obvious. It makes our code look neater. \7e can more easily foilow the
flow of logic in the program. At the sarne time, we have the benefit of typing 'end..if' only once, even
though we have checked for multiple conditions in the code. This saves time spent on typing.
Having come this far, we will now modify our earlier Code Listing if.5 as follows, using the Elseif kelword:
(r) If the value matches "Shreyas", line no.3 is executed, displaying a message box with the given
message. The program then skips over line nos. 4 and 5, and comes to line no. 6. This line
terminates the select..case block. Thus, line no. 3 acts
as the then option of if..then..else.
(b) If the value does NOT match "Shreyas", line no.3 is skipped and program continues at line no. 4.
This line acts as the else of if..then..else. Line no. 5 tells what to do when the else part - case else -
is to be executed.
statements
.... o."r;.rrTthese
Case Else
End Select
Ve will now use Select..Case to modify our Code Listing if .7 we have made earlier.
(.) 'Varf NOT "red" or "green": This value becomes true at line no. 8 resulting in execution of
is
line nos. 9 and 10 only, i.e., all the lines between [Case Eise] and [End Select]. The form's
backcolor changes to blue. An appropriate message box is also displayed. The program rhen
encounters Line no. 1i. which ends the Select..Case block.
Compared to nested if..then code. a select..case code looks near. Also, select..case runs faster than
multiple if..then..else starements"
4. Line no. 4 checks if the text is 'obc'. If true, line no. 5 is executed, and the remaining lines are all
skipped.
5. The line no. 5 checks if the text is'sc'or'st'.If true, the'nested'select-Case block is started.
(") Line no. 7 selects the text in Txt_status rextbox.
(b) Line no. 8 checks if 'text' in Txt_status is 'bpl'. If true, line no. 9 is executed. Remaining
lines of inner and outer block are skipped.
G) Line no. 10 checks if 'text'in Txt status is'ric'. If true, line no. 11 is execured, and the
remaining lines are all skipped.
(d) Line no. 1,2 terminates the inner select...case block.
176 Internet and its Applications M.S. University - D.D.C.E.
6. Line no. 13 is reached if the user has entered a wrong category, i.e., the condition at line r7o.2,4,
and 6 is 'false'.
this line checks for two possible values of Txt-Categ, 'sc' or 'st'. This line is just like saying
IF txt_categ.TEXT : 'sc' or txt_categ.TExT - 'st' THEN
Thus, if we have to check for one out of tvro or more values, we just type (Case Is - ) and then put all
the values one after the other, separated by a comma. For example, the code list given below checks
for city names given in a text box fixt_city) and then prints the state to which the city belongs.
Code List select.4
L. CASE txt_city.TEXT
SELECT
2. CASE IS = "BHOPAL" , "ujjain", "gwalior"
3. MSGBOX UM.P. STATE'
3. Line no. 4 checks the text of txt city. If the value is 'mumbai' or 'thane' or 'nasik', line no. 5 is
executed, by-passing all other lines oi code.
4. Line no. 6 checks text of txt_city. If it is 'lucknow' or 'allahabad' or 'meerut', line no. Z is
executed. Remaining code lines are by-passed.
5. Line no. 8 is reached only if the line nos. 2, 4, and 6 don't match the value of txt_city, and then
line no. 9 is executed.
6. Line no. 9 prints an error message for the user.
7. Line no. L0, of course, terminares the Select..Case block.
L. Line no. 1 selects the text in txtjerc textbox and converts it to rhe nearest integer vah:e (e.g.79.6
to 80, 79.4 to 79, andso on.).
2. Line no. 2 checks text of txtjerc. If between 80 and 100, line no. 3 is executed. The other lines
are by-passed.
178 Internet and its Applications M.S. University - D.D.C.E.
3. Line no. 4 checks tefi of txtjerc. If between 60 and 79,line no. 5 is execured, by-passing all other
lines of code.
4. Line no.6 checks text of txtjerc. If between 45 and 59, line no.7 is execured. Remaining code
lines are by-passed.
5. Line no. 8 checks text of ffitjerc. If between 33 and 44,line no. 9 is executed. Other lines are by-
passed.
6. Line no. 10 is reached if all other criteria of 'percenrage' are not fulfilled.
7. Line no. 11 prints a messagebox with the message 'Fail'.
8. Line no. 12 terminates the Select..Case block.
This is a situation similar to the "and" in "if..then..else", i.e,
. If the percentage is between 80 and 1OO, then give the message "honours".
. If the percentage is between 60 and Tg,thengive the message "1st division", and so on.
The "to" option in select..case should be in ascending order (80 to 1OO, 50 to 79). k won'r work in
descending order (100 to80,79 to 60).
1. Define variables.
2. Define Creating and initializing Date.
A variable must be declared with a name and a specific datatype. Since VBScript supports only one
datatype, Variant, all variables will be declared as Variant by default. Applications need to be able
to access and work with date and time values. Many applications are written for business and
scientific purposes, where recording the date and time of the program run is vital to the success of
the project.. Arithmetic operators work on numeric operands and produce numeric result. Just like
other programming languages, VBScript provides a rich library of built-in functions to deal with
including strings, dates, typecasting, basic math. etc. When you consider crearing functions in any
programming language, it is useful to familiarize yourself with the available built-in functions of that
language.
M.S. University - D.D.C.E. Client-side and Server-side Programming Languages 179
11.9 KEY\TORDS
Seruersidescripr.' The code which is executed at server end is called server-side script.
DateAdd.(sType, ilnterual, tDate): Returns a date to which a specified time interval has been added.
DateDff(tDatel, tDate2): Returns the number of intervals between two dates.
DatePa*(sT7tpe, tDate): Returns the specified part of a given date.
DateSerial(iYear iMonth,iDate): Returns the date for a specifiedyear, month, and day.
DateValue(aVariant) : Returns a date.
Dalt (tDate).'Returns a number that represenm the day of the month (between 1 and 31, inclusive).
ForrnatDateTime(tDate, r-\tp")t Returns an expression formatted as a date or time.
Hour(tDate)..Returns a number that represents the hour of the day (between 0 and23, inclusive).
IsDate(uVariant): Returns a Boolean value that indicates if the evaluated expression can be converted
to a date.
Minute(tDaty'..Returns a number that represents the minute of the hour (between 0 and 59, inclusive).
Month(tDare,/.'Returns a number that represenm the month of the year (between 1 and 12, inclusive).
MonthName (iMonth): Returns the name of a specified month.
Now): Returns the current system date and time.
Int (number); It is different from Fix(number) because Int (number) rerurns integer porrion less than or
equal to number. For example, Inr (-5.80) rerurns -6.
Hex (number):It rettsrns strings consisting of the number converted to hexadecimal base. For example,
Hex (10) returns A, Hex (11) returns B, Hex (12) returns C, erc.
Oct (number):It returns strings consisting of the number converted to octal base. For instance Oct (8)
returns 10, Oct (9) returns 11, Oct (10) returns 12, etc.
Round (number): It rounds a number to the nearest integer; for example, Round (S.+S) rounds 5.45 to 6
and Round (5.01) returns 5.
Round Qruntber, fuc): It rounds a number to dec decimal places. Round (5.45, 1) rounds 5.45 to 1
decimal place: 5.4. Round (100.67899,3) returns 100.679.
Sgn (number):It rettrnsl if number is less than 0, 0 if number is 0, and 1 if number is greater than 0.
Consider the following as examples: Sgn(5.9) returns -1, Sgn(O) rerurns 0; and Sgn(5) returns 1.
Sqr(number)(number> 0):It provides a square root of number, provided the number is positive. For
example, sqr (a) returns 2, sqr {t0O) returns 10.
t2
PROCEDURES, LOGICAL OPERATORS AND LOOPS
CONTENTS
t2.0 Aims and Obiectives
12.1 Introduction
12.2 Sub-routines
12.3 Functions
t2.3.1 StringFunctions
12.4 Using Logical Connectives and Operators
t2.4.1 And
12.4.2 Or
t2.4.3 Not
t2.4.4 XOR @xclusive Or)
12.5 Loop Structure
I2.5.t For-next Loop
t2.5.2 Nested Loops
t2.5.3 Do Loops
12.6 Let us Sum up
12.7 Keywords
12.8 Questions for Discussion
L29 SuggestedReadings
12.1 INTRODUCTION
As we have been observing for some time now, a project in VB is not a 'monolithic', i.e., single-stone
structure. It is made up of a number of sm_all code segmenrs rhar are linked in some way. For Jrr*pI",
the code for the click event of a Command Button commandl is written within the stub:
PRIVATE SUB commandl_CllCK( )
END SUB
As is very obvious, we might be having another command button 'command2' and the code for its
click event will be wrirten within
PRIVATE SUB command2 CLICK$
END SUB
Here is a sample picture of the code window of a VB project.
'$7'e
can clearly see that we have code written for the click event of different command bunons. The
different code_segments are self-contained and are separared from one anorher by the lines running
across the code window. These code segments perform a particular task. These are what
we call
procedures. Thus, a procedure is a code ,"f-..r, that performs a parricular task and is self-contained.
A procedure offers the advantage of better management of code. For example, a code might be
required at multiple locations in a project. It can be pasted ar multiple locarions, and the ourpur i,itt
U"
the same. Now, any change in the code means all the copies hrrr" tL be updated. A procedrrre will help
avoid this rePetitive work. 'We can write the code for the procedure ar ;ly o.r" pL.. and we .rr,
.ril
on this procedure through code. Thus, any changes to be made will be limited to jrrt one location.
The kind of procedures we have used so far are known as 'event procedures'. This is because they are
procedures that are related to an event, and will be executed when a certain event is raised. Thus,
we
primarily code through event procedures in VB.
In addition ro evenr procedures, vB offers the following rypes of procedures:
. Sub-procedures
. Functions
. Property
M.S. University - D.D.C.E. Procedures, Logical Operators and Loops 185
12.2 SUB-ROUTINES
A_sub-routine is a pro_cedure that performs a task but does nor return a value. The general synrax of a
sub-procedure is as follows:
END SUB
An alternative method for the synrax involves the use of parameters. The parameters are an optional,
though a very powerful fearure of procedures. Multiple parameters are separated by commas. The
syntax is shown here:
PUBLIC/PRIVATE procedure name (parameter list)
END SUB
VB offers a number of in-built procedures and also allows us ro create our own procedures. This is
how we create our own procedure in VB:
t. Switch to rhe code window.
2. Click on the tools menu.
3. From the sub-menus, click on add procedure, as shown in the picture.
fra?*. i6,:!I!e{l_{tickll
*tu vqt | 3t l, Ir!€?t!
kfl;sx r*aeivryl
kgpsr Sauhdrrtrl
4' From the dialog box that appears now, type a name for the procedure in the rextbox appearing at
the top (we have typed 'mypro').The dialog box is shown in-the figure that follows:
185 Internet and its Applications M.S. University _ D.D.C.E.
The code window has been shown in the picture that follows
End Sub
8. 'Sfl'e
can now type some code into our own sub-procedure. Our procedure is ready to be used.
Suppose we have typed the following code for our sub procedure.
Code Listing sub.l
PUBLIC SUB mypro ()
This procedure can now be called from anywhere in our Form. To see it in action, draw two
command buttons on the form (with default names of commandl and command2). Now come ro rhe
code window and code for the event procedure of both Command Burtons, as follows:
{Generall
'When we run the program and click on the command button 'commandl', we see an output as
follows:
UEM
inside commandl click
ELLO everyorre ll I ha{e come frCIm the mypro procedure
no!/ hack inside cGmmandl click
ffi]"il i
!l*Y I
r Forml ErErrE
inside commandl diok
ELLO everyone !l f halde Dome from the mypro procedure
now bacrk inside commandl click
inside commandz click
IELLO everyone l! I hare come from the mypro procedure ^
--J, I
co*'"Y.."i
now back in'side command2 click
188 Internet and its Applications M.S. University - D.D.C.E.
The line no. 2 of. code listing sub.2 is 'calling' the sub-procedure mypro. Thus, the program conrrol
'shifts to'the Procedure mypro and the procedure is executed from'tire 1st line to the last. Once the
procedure is completely executed, the program conrrol shifts back ro rhe calling sub.
Now, if a change is required in the procedure mypro, it will be confined ro rhe procedure itself. The
code that is calling mypro, need not necessarily be changed. In fact, if the method of calling the
procedure does not change, the calling block will never know that the internal working oi th.
procedure has changed. For example, if we change the declaration of mypro from
PUBLIC SUB myproQ
To
PLELIC SUB mypro (intjarl AS INTEGER)
\7e will have to change the way of calling mypro from CALL mypro
to
CALL mypro (int_var1)
where int-varl refers to an integer variable. Since we have changed the declaration of the procedure
from no-parameter mode to a single-parameter mode, *e h"lre to change the way of calling it.
Anytime we change the number of parameters or the type of paramerers in a procedure declaratlon,
we have to change the style of calling on rhe procedure.
If we don't make the change in the mode of calling from the upper sratemenr ro rhe lower sratement,
we will get an error of 'type mismatch' at runtime.
A procedure call should match in 'quality and quantity'. The number and datatype of argumenrs musr
match the parameters in the procedure.
As long as the number of parameters or the type of paramerers for calling the procedure do not
change, the procedure call will remain unchanged.
12.3 FUNCTIONS
Functions are a tyPe of procedure, which return a value. This is what separates a function from a sub-
procedure. Otherwise, the function and sub-procedure are the same. rvien we wanr a self-contained
code, executing a particular task and also 'returning a value' to the calling program, we use a function.
If a value is not to be returned, we use a procedure.
The general syntax of a function is:
PUBLIC/PRIVATE function name (parameter list) AS DATATYPE
As the syntax shows, a function declaration is not much different from that of a procedure. The only
difference is the presence of a return datatype, ar rhe end of the declaration. Since a function h* tl
return a value, the declaration of a function will include the datatype as rhe lasr two words of the
function declaration. For example, if a function area accepts an integer parameter and rerurns an
integer to the calling program, the syntax will be:
PUBLIC/PRIVATE FUNCTION area (intjarl AS INTEGER) AS INTEGER
M.S. University - D.D.C.E. Procedures, Logical Operators and Loops 189
For a function join_name that accepts two strings as parameters and returns a string, the syntax could
be:
AS STRING) AS STRING
Once again, the return datatype of the function has been given as the last word.
Here is an example of a function. This function will accept the length of a side of a square and calculate
the area of the square based on that number. The code will be as follows:
Code Listing function.l
PRIVATE FUNCTfON SquATE_ATEA (iNL3 AS INTEGER) AS INTEGER
square_area = intj ^ 2 'the ^ function (exponentiat.ion) raises
a no. to any power.
END SUB
Here, the procedure has only one executable line of code. This line of the procedure does two things:
o Raises the parameter for the function intj to the 2nd power through the use of the
'exponentiation' function [ ^ ].
o Assigns this value to the function name square_area. This value is then returned to the calling
Program.
Here is some code to use the function created above. For this, create a form with 2 textboxes textl and
text2 and a single Command Button commandl. The textbox textl will be used to type the value of
the argument for the function square_area. Textbox text2 will display the result of the function call.
Now come to the code window and rype the following code:
Code Listing function.2
PRIVATE SUB commandl_ClfcK()
1. DIM int_var1 AS INTEGER
2. DfM int_return AS INTEGER
3. int_var1 = CINT (textl.TEXT)
4. int_return = square_area (int-var1)
5. text2.TEXT = int return
END SUB
In the code given above, the function square_area has already been created under the code listing
function.l. Analyzing the code further,
1. Line nos. l and2 declare 2integer variables by the name int_varl and int_return, respectively.
This int_varl will be the input (argument) we give to the function square_area. The int_return is
the return value we will get from the function square_area.
2. Line no. 3 converts the contents of textl into an integer, through the use of the in-built 'cint'
function [cint(textl.text)]. This value is stored in the variable int var1.
190 Internet and its Applications M.S. University - D.D.C.E.
3. Line no. 4 shifts the program control to the function square_area. It calls this functioh, sending it
int-var1 as an argument. Inside square_area, the argument int_varl becomes the parameter intj.
Once the function completes execution, the return value of the function is stored in rhe variable
int_return.
4. Line no. 5 displays the value of int_return in text2. This is the value returned from the function
square_afea.
As we can see, a function call takes the program from one code segment to another. The program
control shifts from the currently executing procedure or function to the function called by us through
code. Once the called procedure or function is executed, the program control shifts to the line after the
line which had called the code. To represent this clearly, consider our code listing function.l and code
listing function.2
Code Listing function.l
PRIVATE FUNCTTON square_area (int__p AS INTEGER)AS INTEGER
Square_area = intJ^2
'the '^'function(exponentiation)raises a number to any power
END SUB
In this code, line no. 4 of code listing function.2 shifts the program conrrol ro square_a reaby calling it.
Once squar e_area is completely executed, the program control shifts back to line no. 7 of code listing
function.2. This line is the first executable line of code listing function.2, after the function has been
called.
This scheme of calling a function can be represented inside rhe computer as:
Now we run the program, type the first name in textl and the lasi name in text2, and then click on
commandl. The following happens:
1. Line nos. 1 to 3 declare three string type of variables to hold our data and the results.
2. Line no. 4 assigns the contents of textl to str_fname.
3. Line no. 5 assigns the contents of text2 to str_lname.
4. Line no. 6 now calls the function join_name with 2 arguments. The program control shifts to the
first line of join_name. Once the function is fully executed, the program control shifts back to
code listing function,4. The return value of join_name is stored in the variable str_fullname.
5. Line no. 7 displays the contents of str_fullname in text3. This text, as we know, shows the
complete (oined) name typed by the user.
192 Internet and its Applications
M.S. University - D.D.C.E.
TRIM can be used to remove leading and trailing spaces when accepting an input from the user
' searching a record in the database.
for
Of these functions, srtreverse, replace and instr are new to VB 6. Instr returns a value of '0' if the
string to be searched is not found in the given string.
Part Description
Result A required boolean variable.
Expressionl A required boolean expression.
Expression2 A required boolean expression.
If both expressions evaluate to True, result is True. If either expression evaluares to False, result is
False. The following table illustrares how result is determined:
expression 1 expression2 Expressionl And Expression2
True True True
True False False
True Nuil Null
False True False
False False False
False Null False
Null True Null
Null False False
Null Null Null
M.S. University - D.D.C.E. Procedures, Logical Operators and Loops 193
The And oPerator also performs a bitwise comparison of identically positioned bits in two numeric
exPressions and sets the corresponding bit in result according ro rhe following table:
I 0
L 1 I
12.4.2 Or
Purpose: To perform a logical disjunction on rwo expressions.
Part Description
Resub A required boolean variable.
Expressionl A required boolean expression.
Expression2 A required boolean expression.
If either or both expressions evaluate to True, result is True. The following table illustrares how resull
is determined:
expressionl expression2 expressionl Or expression2
I rLle True True
'frue False True
True Null True
False True True
False False False
False Null Null
Null True True
Null False Null
Null Null Null
The Or operator also performs a bitwise comparison of idenrically positioned bits in two numeric
exPressions and sets the corresponding bit in resuh according to rhe following table:
0 1 1
I 0 I
1 I 1
194 Internet and its Applications M.S. University - D.D.C.E.
12.4.3 Not
Purpose: To perform logical negation on an expression.
False True
Null Null
In addition, the Not operaror,inverts the bit values of any variable and sets the corresponding bit in
resuh according to the following table:
1 U
If one, and only one, of the expressions evaluates to True, result is True. However, if either expression
is Null, result is also Null. \7hen neither expression is Null, result is determined according to the
following table:
expressionl expression2 Xor
True True False
The Xor operator performs both a logical and bitwise operations. A bit-wise comparison of two
expressions using exclusive-or logic to form the result, as shown in the following table:
0 I I
I U I
1 I 0
12.5.1For-next Loop
The general syntax of the For-Next Loop is as follows:
FOR i : initial value TO final value 'line 1
'All of these statements
'will be repeated as long
NEXT i 'line 8
196 Internet and its Applications
M.S. University - D.D.C.E.
where i can be any integer variable. In For-Next terminologl, 'i' is known as an index variable.
The
[-For i : initial value ro final value]. All of
code starts by initializing the value of i, as given in the line
the statemenrs upto line no. 8 (Next i) are then execured.
At line number 8, rwo important things happen:
1. The value of i is incremented by 1.
2. "Next i" then checks if the value of i falls in the given range on linel (initial ,rlrr. ,rrd final value)
If the incremented value of i falls within the range, all the lines between 1 and 8 are executed once
again. Once again, the program comes to line 8. Once again the process happening at line
number g is
repeated, as we have just discussed.
If the incremented value falls between the range, all of the lines between 1 and 8 are again execured.
This process continues till the time the ,alre of i is between the initial and the final valui. That
is, the
lines between 1 and 8 are repeatedly executed. This is what we call as the 'loop'.
Once incremented value of i' does NOT fall in the given range, execution of lines berween
1 and g is
stopped. Thus, the For-Next loop is terminated. The progrrin will then starr processing
statements
written after "Next i" statement
Let us say we want to print a sequence of numbers from 1 to 3. Our program will look like this:
Code Listing for.l
1-. i = l_ TO 3'define initial and final values
FOR
2. PRTNT i
3. NEXT i ,check if loop is to be repeated
4. MSGBOX " For - Next loop has ended"
Here, the code runs as follows:
1. Line no. 1 stans the loop, assigning initial of 1 for i and a final value of 3.
2. Line no. 2 prints the value of i on rhe screen, i.e., 1.
3. Line no. 3 "Next i" increments the value of i' by 1: 'i' becomes 2.
4' The line "Next i" checks if i' falls in the range 1 ro 3 as specified in line no. 1. The
currenr value
of i', i.e., 2, is between 1 and 3. Hence, line no. 2 is repeated.
5. Line no. 2 again prints the valueof i, on rhe screen, i.e.,2.
6' Line no. 3 is reached again. "Next i" again increments 'i' by 1. So, 'i' now becomes 3. The
current
value is then checked at line no.1. Since the currenr valul of i is berween 1 and
3, line no. 2 is
repeated.
7. Line no. 2 again prints the value of i' on the screen, i.e., 3.
8. Line no. 3 is reached again. "Next i" again increments 'i' by 1. So, 'i' now becomes
4. The current
value of i' is 4, but 4 is NOT between 1 and 3. Thus, line no. 2 is nor repeared. The For..Next
loop is terminated, and further printing of the value of i' is stopped. Nowihe program
comes ro
line 4.
9. Line no. 4 gives a message box indicating that the loop has terminated. The program stops.
M's' university - D'D'C'E' Procedures, Logical operators and Loops 192
Take,another examPle. This time we will print a name on the screen four times. The
code segmenr is
as tollows:
NEXT i
198 Internet and its Applications M.S. University - D'D'C'E'
where 'j' is an integer variable, either positive or negative. If we want to decrease the value of " i " at
every step, 'j' should be a negative integer.
Let us now use Step to make a program that generates the multiples of 2 upto the number 10, i'e., the
output should bez 2,4,6,8,10.
Code Listing for.3
1. FORi =2TO 10 STEP 2 'increase iby2 at everyiteration
2, PRINT i
3. NEXT i 'check if loop is Lo be repeated
4. MSGBOX "looP is over"
Here, the code runs as follows:
l. Line no. 1 gives 'i' the initial value of 2.
2. Line no. 2 prints '2' on the screen.
3. Line no. 3 increases the value of i' by 2, because the value of Step is 2. This changes the value of i
to 4 . Line no. 3 then checks if the current value of i, i.e., 4 is between2 and 10. Since it is, the
program shifts to line no. 2 and prints the value of i.
4. As long as rhe value of i is betwe en 2 tnd 10, the program will keep shifting to line no.2 from line
no. 3. Once 'i' comes out of the range (2 to 10) the for-next loop will terminate.
5. Now line no. 4 will run, informing the user that the loop has terminated.
Thus, after giving the output as a sequence, i'e',
10
As long asthe value of i' is between 10 and 2, the program will keep shifting to line no.2 from line no.
Once 'i' comes out of the range [10 to 2] the for-next loop will terminate. Then line no. 4 will be
executed.
If we compare Code Listing for.3 and Code Listing for.4, we will nodce that only line t has been
changed. Thus, after giving the output
108642
the loop terminates.
Here is another program, which accepts five names, one by one, and displays them on a message box.
The code is like this:
Code Listing for.5
1. DIM nam AS STRING
2. FOR i = 1 TO 5 'define initial and final values
3. nam = INPUTBOX ("Please enter a name")
4, MSGBOX nam & "is a nice name indeed"
5. NEXT i 'check if loop is to be repeated
6. MSGBOX "1oop is over"
Here, the code runs as follows:
l. Line no. 1 declares a String type of variable 'nam' at line 1.
2. Line no. 2 begins the for-next loop, initializing 'i' to the value 1.
'done here
NEXT j
200 Internet and its Applications
M.S. University - D.D.C.E.
NEXT i
'W"hereas,
the following loop is invalid, since nrro loops intersect:
FORi = 1 TO 5
FORj=1TO5
'some processing
'done here
NEXT i
NEXT i
To minimize risk of wrong nesting, just type 'Nexr' instead of 'Nexr i', 'Next j', etc. This way, VB
will follow a proper nesdng by itself.
FORi- 1TO4
FOR,-1TO4
'sorne processing
'done here
NEXT
NEXT
By the w1\ ca! you guess how many times the inner 'j' loop will run? A total of 16 times! This is
because of the following reason:
1. 'i' is 1: \trflhile 'i'stays at
L,'j'will change in value from 1 to 4. Thus, the 'j' loop will run a total of
4 times when [i=1]. The variable'i'does.not change in value ar presenr bec..rre the'i'loop's
[Next I] statement is not reached in this duration. [h. progr.- k..p, looping between 'ro,
Next j' statements.) Once 'j' becomes 5, the.'j' loop .rrdr *d th. piogrrrn comes to
1-
[Next i]
statement. Now, the value of i' becomes 2 and the control shifts backio the
[For j] statement.
2. 'i' is 2: The 'j' lo_opxill again change in value from 1 to 4. Thus, the 'j' loop will run a total of 4
times while [i=2). The variable'i'does not change in value ar presenr 6..r.rr. the'i, loop's
fNext
Il statement is not reached in this duration. (The program keeps looping between 'For'j-IrLxt j'
statements.) Once 'j' becomes 5, the 'j' loop ends anJthe program comes to
[Next I] statemeni.
Now, the value of i' becomes 3 and the control shifts back to the
[For j] sraremenr.
3. 'i' is 3: The 'j' loop will again change in value from 1 to 4. The 'j' loop will run a total of four
times while [i:3]: Once 'j' becomes 5, the 'j' loop ends and the program comes to
[Next I]
statement. Now, the value of i' becornes 4 and the control shifts backto i-h. j] staternent.
;Fo,
4. 'i' is 4: The 'j' loop will again change in value from 1 to 4. The 'j' loop will run a total of four times
while [i=4]. Once 'j' becomes 5, the 'j' loop ends and the program comes to
[Next I] statement.
Now, the value of i' becomes 5. Since the value of i' is rro lorrgJr between the 'i' loop condition
to 4], the 'i' loop is terminated. The program comes out of the 'i loop and stops after
[i
fNext I].
As just explained, for every single value of i, j changes value from 1 to 4. Thus, the j loop runs ,4,
times
for every single run of the i loop. The i loop will change from 1 to 4 and then terminate. This means
M.S. University - D.D.C.E. Procedures, Logical Operators and Loops 201
that the i loop will run a total of '4' times. Thus, the program will run a total of 4 'F 4= 16 times.
(tlo. of iterations of i' loop '$ No. of iterations of 'j' loop for each single value of i').
12.5.3 Do Loops
Apart from the For-Next loop, VB provides the Do loop as Inother iterative mechanism. Needless to
say, rhe need of this loop is the same as that of the For-Next loop. This loop is, broadly speaking, of
two tyPes:
. Do-\(hile-Loop
. Do-Until-Loop
In both the types, we provide a condition after the keyword "Do-\7hile" or "Do-lJntil". The
repetition of the loop depends on whether the condition is true or false at any given point of time.
Do-While-Loop
In this loop, the loop lines are repeated as long as the given condition is true. Once the condition
becomes false, the loop is terminated and the program continues with the statements that appear after
the Do-Vhile loop.
The general syntax for the Do-Vhile loop is
DO \(HILE some condition
'execute some
'statements repeatedly
Take another example. As done in Code Listing for.2, we will print a name on rhe screen four times.
This time we'll use Do-\flhile to get the same result, using a command bufton's Click event:
Code Listing do.2
1. i =1
2. DOWHILE i < 5 'check if i is less than 5
5. Line 5 takes the control back to line 2 and here the condition ti < 5l is checked again. If it is true,
line nos. 3 and 4 are repeatedly executed. Once the condition [i ( 5] becomes false, further
execution of the loop is stopped. The program now shifts to line no. 6.
6. Line no. 6 displays a message box on rhe screen. The program srops.
lWe'Il now get the same results as from Code Listing
for.3 seen earlier in the chapter. This time,
though, we'll be using Do-\flhile. Again, use a command button's Click as rhe evenr for the code. The
code is as follows:
M.S. University - D.D.C.E. Procedures, Logical Operators and Loops 203
3. PRINT i
4. ! = i + 2
5. LOOP 'check if loop is to be repeated
6. MSGBOX "do whil-e ended"
Here, the code runs as follows:
1. Line no. 1 assigns the number 2 to the variable 'i'.
2. Line no. 2 checks if ti < 111. If it is true, line 3 is executd. If it is not true, all the loop lines are
skipped over, and program control shifts to line no.6.
3. Line no. 3 prints the value of i' on the screen.
4. Line no. 4 increases the value of.'1' by 2.
5. Lineno.5takestheprogrambacktoline2,wherethecondition[i < 11]isagainchecked. If the
condition is rrue, lini nos. 3 and 4 are re-executed. This means that the program continues with
the repetition of the loop as long as the condition [i < 11] is true. Once the condition [i < 11]
becornes false, the loop is terminated, and control shifts to the line following line 5.
3. PRINT i
4. i = i - 2
5. LOOP 'check if loop i-s to be repeated
6. MSGBOX "looP over"
Here, the code runs as follows:
1. Line no. 1 assigns 10 to 'i'.
2. Line 2 checks the condition [i > 1]. Since i is initially 10, this condition is true. Thus, line nos. 3
and 4 are run. After line 4, 'i' decreases by 2, i.e.,'i' drops to 8.
3. Line no. 5 takes the control back to line 2 and again checks for the condition [i > 1]. Since 'i' is
still greater than 1, lines 3 and 4 are again executed. This process of repetition continues while 'i'
204 Internet and its Applications
M.S. University - D.D.C,E.
10
2
Do-Until l-oop
rwith the Do-\flhile
loop, the repetitions continue as far as the given condition ,,rrue,,.
is That is, the
loop will continue "while" the condition is "rrue". The
Do-until loop is just rhe reverse of this. In a
Do-Until loop, the repetitions take place as far as the giuerr-condition
is ',false,,. In other words, the
loop will continue "until" the condition becomes "true".
once the condition becomes true, the loop is
terminated and the Program continues with the staremenrs
mentioned after Do-until loop. The
general synrax for the Do-Until loop is:
'statements repeatedly
'until the condition
'becomes true
LOOP
All of the statements written between Do-until and Loop are repearedly
executed as far as the
condition mentioned after Do-Until is not true. That
is, the f,oop ,rrr.*ent shifts the control back to
Do-until and the condition is then checked. If the condiri""I
nor rrue, the loop is re-execured. once
the condition becomes true, the program stops the ,.p.rr.J
loop .*..rrion and begins ro execure rhe
statemenrc after Loop.
As.an example, we will remake our code Listing do.1
using Do-until, ro ger rhe same result as from
code listing do.1 using a butron,s click event:
Code Listing do.5
1. DO UNTIL i > 4,continue if i is NOT greater than 4
2. PRrNT i
.:_:
J-J.+J_
2. Line no. 2 checks if the current value of i' is greater than 5. As the condition is nor rrue, line no.
3 is executed.
4. Line 5 takes the control back to line 2 and here the condition ti > 5l is checked again. If it is not
true, the Process of repeating the loop continues. Once the condition ti > 5] becomes rrue,
further execution of the loop is stopped. The program now shifts to line no. 6.
5. Line no. 6 displays a message box on rhe screen and the program srops.
Now we will generate a series of numbers - 2,4,6,8,10. You might recollect that we have already done
this using For-Next and Do-\7hile. Now we will be using Do-Until ro ger the same resuh. Ure the
click event of a button for the code:
Code Listing do.7
1. 1 = 2
2. Do UNTIL i > 11 'continue loop if i is Nor greater than 11
3. PRINT i
4. i = i + 2
5. LOOP 'check if loop is to be repeated
206 Internet and its Applications M.S. University - D.D.C.E.
4
6
8
l0
the loop terminates.
Here is another program, which accepts five names, one by one, and displays them in a message box,
on the click of a button. The code, using Do-Until, is:
Code List do.8
1. DIM nam AS STRING
2. i =1
3. DO ITNTIL i > 5'continue loop if i is NOT greater than 5
6. i =i +1
7. LOOP 'check if loop is to be repeated
Here, the code runs as follows:
l. Line 1 declares a string type of a variable.
2. Line2 initializes 'i'to 1.
3. Line 3 checks the condition [i ) 5]. Since the current value of i' [1] does nor sarisfy rhis
condition, line 4 is executed.
4. Line no. 4 asks for a name through an Input box.
5. Line no. 5 displays rhe name in a message box.
6. Line no. 6 increments 'i' by 1 (i now becomes 2).
M.S. University - D.D.C.E. Procedures, Logical Operators and Loops 207
7 . Line 7 rransfers control back to line 3. Line 3 again checks for [i > 5]. This process of continuing
with the loop will go on until [i > 5], i.e., 'i' becomes greater than 5. Once [i ) 5] becomes true,
further re-execution of the loop is stopped.
k Your
1. Define indeterminate loops.
2. Define Do-while loop.
I2.6LET US SUM UP
A sub-routine is a procedure that performs a task but does not return a value. Functions are a type of
procedure, which return a value. This is what separates a function from a sub-procedure. As the name
suggests, string functions work on string type of data. They help perform a number of useful activities
that are of immense help in validating and manipulating our data.
A logical expression is a combination of constants, variables and operators, which evaluates to either
TRUE or FALSE values. Logical expressions are formed using logical and relational operators. A
logical operator compares two values (constants, expressions, variables etc.) and produces either true or
false when used in an expression. Visual Basic provides many looping constnrcts such as do-while,
while-wend and their variants.
72.7 KEY\T/ORDS
Looping: Repeated execution of statements.
Logical Expression: A combination of constants, variables and operators, which evaluates to either
TRUE or FALSE values.
Logical Operator: A logical operator compares two values (consants, expressions, variables etc.) and
produces either true or false when used in an expression.
If 0 > 4)Then
Exit For
End If
Next j
8. How many times will the staremenrl execure in the following loop?
. For j : 1to 10
Fork=jto10
Statementl
Next k
Next k
t3
VB SCRIPT AND FORMS
CONTENTS
13.0 Aims and Objectives
13.t Introduction
13.2 A Simple Page
13.3 Using VB Script with Forms
t3.3.1 Validadng your Forms
13.3.2 Checking Form Input
t3.3.3 How It Works
13.3.4 Submitting Your Forms
13.4 Error Hiding
13.5 Let us Sum up
t3.6 Kel"words
13.7 Questions for Discussion
13.8 SuggestedReadings
13.1 INTRODUCTION
VB Script is defined as a scripting language developed by Microsoft. You can make your web pages
more vibrant and interactive with the help of this scripting language. VB Script is a light edition of
Visual basic and it has a simple syntax.
VB Script is extensively used and most accepted as a client side scripting language. In html language
r"ou use ( and ) around the tags. But you can use many tags inside one pair of < o/, and o/o ). For
Printing a variable you can use ( Yo : o/o ).
210 Internet and its Applications M.S. University - D.D.C.E.
Scripting languages like Javascript and Vbscript are intended as an expansion to html language. The
'Web
browsers such as Microsoft Internet Explorer obtain the scripts along with the remaining *eb
page document. It is the browser accountability to parse and process the scripts. These scripis are
extensively used as a client side scripting languages. Now we will starr learning how the Script
language works and we will show you step by step . So just focus on the further topics.
The validation example that we will be probing does not enclose anything new in the way of VBScript
Before reading any further you may find if favorable to consider how you would legalize an HTML
form using the VBScript techniques.
Let's see an example to give you a thought of what is possible when it comes to validating forms.
If (document.frmExample5a.txtAge.value < 0) Or _
(document.frmExample5a.txtAge.value ) 100) Then
</SCRIPT>
</HEAD >
<BODY>
<Hl>A VBScript Example on Variables</H1>
< P > This example demonsrrates validation techniques in vBScript . < /p >
< FORM NAME : "frmExample5a" )
< TABLE >
< TR>
< TD > Enter your age: ( /TD )
< TD > < INPUT TYPE= "Texr" NAME: "rxrAge" SIZE=,,2,,)
< TR>
< TD > < INPUT TYPE: "Burron" NAME = "cmdSubmit" vALUE: "Submir" > < /TD >
<TD> </TD>
</TR>
</TABLE>
< /FORM >
</BODY>
< /HTML >
13.3.3 How It Vorks
The empathy of this validation script is established in the click event procedure for the cmdSubmit
command button. \ile begi-n by inspecting if the user entered anything at all into the field using
VBScript's Len function. This function returns the length of a stri.rg. Ii the length is 0, rhe data ii
invalid. \7e inform the user and exit the submit procedrrr. via the Exit-Sub ,rrr.-.ir,
' Check to see if the user enrered anything.
If (Len(documenr.frmExample5a.txtAge.value) : O) Then
MsgBox "You must enrer your age before submitting."
Exit Sub
End If
Next we test out to see if what the user entered is a numeric value. The VBScript function IsNumeric
returns a true value when it is a number. If not, we tell the user and exit:
'Check to see if rhe user entered a number.
If (I.,Iot$sNumeric(documenr.frmExample5a.txtAge.value))) Then
MsgBox "You must enter a number for your age."
Exit Sub
End If
M.S. Universitv - D.D.C.E. VB Script and Forms 213
Our concluding check involves verifying that the age they entered appears to be sensible for our
environment. I have determined that no age less than 0 or greater than 100 is accepiable. Using an
If..Then statement we can check the value of the input field in opposition to this criteria:
'Check to see if the age entered is valid.
If (document.frmExample5a.txtAge.value < 0) Or _
(document.frmExample5a.txtAge.value > 100) Then
Judged against to validation, the procedure of submitting a form is simple. In our example we've used a
normal HTML button with the Submit caption that is joined to an event procedure that both validates
and at the same time submits the form. The code that we would have to add to our previous example
to submit the form is shown below:
'Data looks okay so submit it.
MsgBox "Thanks for providing your age."
document.frmExample5a.submit
The MsgBox statement lets the user know that their data has been processed. The form is then
submitted by invoking the Submlr method of the form object. As we saw in lesson 3 on objects,
methods cause an object to perform a task. Here we are using the submit method of our form ro cause
the form to submit its data, just as if we had used a subrnit conrrol.
Example:
try
ImponFile(filename);
excePt
214 Internet and its Applications M.S. University - D.D.C.E.
end;
This code fragment tries to open a file and read it into memory. If it fails (for whatever reason) the
only gets a message telling them that the import failed, not why or indeed which file failed to imporc.
/ / bener approach
try
ImportFile(filename) ;
except
on E:Exception do
begin
/ / build an informative message
E.Message ::'Imporr of file <'+filename+' ) failed.' +#lj#lO +
E.Message;
raise;
end;
end;
In this example the user at least gets a message rhar tells them which file was unsuccessful to import;
this gives them a start at identifying the problem. A more absolute solution would comprise additional
information on why the impon failed and write the information ro a log file, perhaps (for very
complex or enterprise level applications) also producing extra 'rrace' files containing detailed records of
the state of the application when the error appeared.
Sometimes error hiding is a applicable activity, for example accessing the conrents of a file that does
not exist in Java version 1.3 or older would result in an IOException message without any reference to
the misplaced file. In this case is would be sensible to veil the error and raise ,r, based on
what the application was trying to do at the time, giving what extra information can"*..piion
be tbtained.
Another reason for Error Hiding is to shun componenr crashing in case of failure. In spite of the error,
the component carry on its job. The user (and the testers) never see the crash, even ifsome anomalies
canbe discovered, as the results are not those predictable.
This is completed either with a try/catchwith an empry catch clause, or by execuring code depending
on the returning error status:
Example of try/ catch error hiding (C + + code):
try
{
doSomethingQ ;
doSomethingElseQ ;
M.S. University - D.D.C.E. VB Script and Forms 215
anotherDoSomethingQ ;
)
carch(...)
{
\I
As it is this code is tremendously difficult to correct (and is even more, in case of nested "empty
try/catch" Error Hiding code), and any variance is extremely difficult to trace to its origin, increasing
maintenance costs, only to keep up an appearance of robustness.
Example of error returning error hiding (VBScript code):
If doSomethingQ Then
If doSomethingElseQ Then
If anotherDoSomething$ Then
anotherOtherD oSomethingQ
End If
End If
End If
The outcome is that when some error happens, it is secreted by the code (because it's error prone or
simply verbose to add an Else clause) until someone notices something is muddled.
A tricky outcome is that when some similar code is written, but without the IflEnd If clauses, and is
executed after the first code, the second code will fail, but no one will know the failure happened
before and was hidden.
Thus one can aggravate the appearance of a bug months after the bug was first introduced (but hidden
and thus, never discovered).
13.6 KEY\TORDS
w script: It is widely used and mosr popular as a client side scripting language.
Eror Hiding: It is an anti-pattern, in computer programming. The programmer hides error messages
by overriding rhem with exception handling.
G) Dim d As Form
For Each d In Forms
d.Hide
Next
Visual Basic 2005 in a Nutsbell; Paul Lomax, Steven Roman, Ron Petrusha, Tim Patrick; O'Reilly; 2006