Computer Applications
Computer Applications
COMPUTER APPLICATIONS
(Commerce)
CLASS - XII
Government of Kerala
DEPARTMENT OF EDUCATION
State Council of Educational Research and Training (SCERT),
Kerala
2015
THE NATIONAL ANTHEM
Jana-gana-mana adhinayaka, jaya he
Bharatha-bhagya-vidhata.
Punjab-Sindh-Gujarat-Maratha
Dravida-Utkala-Banga
Vindhya-Himachala-Yamuna-Ganga
Uchchala-Jaladhi-taranga
Tava subha name jage,
Tava subha asisa mage,
Gahe tava jaya gatha.
Jana-gana-mangala-dayaka jaya he
Bharatha-bhagya-vidhata.
Jaya he, jaya he, jaya he,
Jaya jaya jaya, jaya he!
PLEDGE
India is my country. All Indians are my brothers and sisters.
I love my country, and I am proud of its rich and varied heritage.
I shall always strive to be worthy of it.
I shall give my parents, teachers and all elders respect, and treat
everyone with courtesy.
To my country and my people, I pledge my devotion. In their
well-being and prosperity alone lies my happiness.
Prepared by:
State Council of Educational Research and Training (SCERT)
Poojappura, Thiruvananthapuram 695012, Kerala
Website : www.scertkerala.gov.in e-mail : [email protected]
Phone : 0471 - 2341883, Fax : 0471 - 2341869
Typesetting and Layout : SCERT
© Department of Education, Government of Kerala
To be printed in quality paper - 80gsm map litho (snow-white)
Foreword
Dear learners,
The syllabus of Computer Applications for the Commerce discipline
at Higher Secondary Level has been revised and implemented in view
of the fact that computer is used currently as a tool for various
applications, especially in the field of e-Banking, e-Commerce, e-
Governance, etc. Higher studies and placements, at present, greatly
demand human resources with adequate knowledge in computer
applications and information technology. In Class XI, the syllabus
focussed on the fundamentals of computer, hardware and software
components, computer network and Intenet. Emphasis is also given to
put a strong foundation to develop problem solving skills and create
computer programs.
The syllabus of Class XII Computer Application (Commerce) is a
continuation to that of Class XI. Hence the text book, designed in
accordance with the syllabus, begins with some advanced features of
C++ programming language to solve complex problems. Since we are
in the age of Internet and most of us are users of web applications, an
introduction to develop the same is also provided. The concept of
database and facilities of information retrieval are included. A chapter
is dedicated to present a brief idea about Enterprise Resource Planning.
An exclusive section on the new trends and issues in the field of
Information Communication Technology is also incorporated.
Considering the increase in the use of Internet, an awareness about
Cyber laws is presented to safeguard against Cyber crimes.
I hope this book will meet all the requirements for stepping to levels
of higher education and pave the way to the peak of success.
Dr S. Raveendran Nair
Director
SCERT, Kerala
Textbook Development Team
Joy John Prasanth P. M.
HSST, St. Joseph's HSS, HSST, St. Joseph's Boys' HSS,
Thiruvananthapuram Kozhikode
A. N. Sathian Sunil Kariyatan
HSST, GM HSS, Koyilandy, HSST, Govt. Brennen HSS,
Kozhikode Thalassery
Mustafa Shamsul Haq K. K. Asees V.
HSST, GHSS Kuthuparamba, HSST, Govt. HSS Velliyode,
Kannur Kozhikode
A. S. Ismael Rajamohan C.
HSST, PJMS GHSS, Kandassankadavu, HSST, Nava Mukunda HSS,
Thrissur Thirunavaya, Malappuram
Vinod V. Najeeb P. P.
HSST, NSS HSS, Prakkulam, HSST, Himayathul Islam HSS,
Kollam Kozhikode
Experts
Dr Lajish V. L. Dr Madhu S. Nair
Assistant Professor, Dept. of Computer Assistant Professor, Dept. of Computer
Science, University of Calicut Science, University of Kerala
Madhu V. T. Dr Binu P. Chacko
Director, Computer Centre, University of Associate Professor, Dept. of Computer
Calicut Science, Prajyoti Niketan College,
Dr Sushil Kumar R. Pudukad, Thrissur
Associate Professor, Dept. of English, Dr Deepa L. C.
D. B. College, Sasthamcotta Assistant Professor, Dept. of English,
Vinayakumaran Nair N. Govt. Women's College, Trivandrum
Assistant Commandant, Hi-Tech Cell, Maheswaran Nair V.
Police Head Quarters, Trivandrum Sub Divisional Engineer, Regional
Dr Kabeer V. Telecom Training Centre, Kaimanom,
Asst. Prof & Head, Dept. of Computer Tvpm.
Science, Farook College, Kozhikode
Artists
Sudheer Y. Vineeth V.
Academic Co-ordinator
Dr Meena S.
Research Officer, SCERT
CONTENTS
Let us do
Information box
Let us practice
Let us conclude
Review of C++
1 Programming
T
he basic concepts of C++ language were
Significant Learning Outcomes
discussed in Class XI. A good
After the completion of this chapter the understanding of these concepts is very
learner
essential to attain the significant learning
outcomes envisaged in the following chapters.
• uses input statements in programs
This chapter is a quick tour to refresh the
to enter data into the computer. concepts and skills you acquired in C++
• uses output statements in programs language in Class XI. Each concept will be
to display various forms of output. presented with necessary details only. The most
• applies various forms of if important aspects like selection statements and
statements to make decisions while looping statements are explained with the help
solving problems. of programs. Some advanced features like
• compares else if ladder and switch
nested loops and the effect of break and
continue statements in loops are also
statement.
introduced in this chapter.
• distinguishes different looping
statements of C++. Since we use GNU Compiler Collection (GCC)
with Geany IDE for developing C++ programs,
• selects appropriate loop in
we should be aware of the structure of
programs for solving problems.
program, format of specifying the header file,
• uses the concept of nested loop in size of the data types, etc.
problem solving and predicts the
output. 1.1 Basics of C++
• identifies the effect of break and C++ being a programming language, we started
continue statements in loops by by learning its character set followed by tokens,
explaining their effect on the expressions and statements. We also discussed
program flow. data types and their modifiers. While
constructing expressions, we identified the need
of data type conversions. Table 1.1 provides a
brief idea of these elements.
Computer Applications (Commerce) - XII
An overview of C++
10
1. Review of C++ Programming
An overview of C++
11
Computer Applications (Commerce) - XII
An overview of C++
12
1. Review of C++ Programming
13
Computer Applications (Commerce) - XII
There are special assignment operators, called arithmetic assignment operators. They
are +=, -=, *=, /= and %=. These are all binary operators and the operand to left of
these operators should be variables. Their operations may be illustrated as follows:
n+=2; // It is equivalent to n=n+2;
a*=b; // It is equivalent to a=a*b;
sum-=n%10; // It is equivalent to sum=sum-n%10;
The operators ++ and -- are special operators of C++, which are, in a way, similar
to assignment statements. These are unary operators and the operand should be a
variable. The following statements illustrate the operations associated with them:
n++; // It is equivalent to n=n+1;
a--; // It is equivalent to a=a-1;
There are two versions for these operators: postfix form and prefix form. a++;
and a--; are the postfix form of increment and decrement operators respectively.
++a; and --a; are the prefix form. Whatever be the form, ++ operator adds 1 to
the content of the operand variable and the result is stored in it.
The two versions differ when used with an assignment or output statement. Assume
that a is an integer variable with value 5 and b is another integer variable. After the
execution of the statement: b=a++; the value of b will be 5 and that of a will be 6.
That is, b=a++; is equivalent to the statement sequence: b=a; a=a+1;. So this
method of incrementing is known as use and change method.
But the statement, b=++a; is equivalent to the statement sequence: a=a+1; b=a;.
So the values of both a and b will be 6. This method of incrementing is known as
change and use method.
Similarly, the statement cout<<a--; will display 5, but the value of a will be 4. It
is equivalent to the statement sequence cout<<a; a=a-1;. But the statement
cout<<--a; is equivalent to a=a-1; cout<<a;.
The input, output and assignment operators (>>, << and =) may appear more than
once in the respective statements. It is known as cascading. The following are
examples in each category for cascading of input, output and assignment operators
respectively.
cin >> a >> b >> c;
cout << "Sum of " << n << "numbers = " << sum;
a = b = c;
14
1. Review of C++ Programming
Program 1.1 uses the header file iostream, since the identifiers cin and cout are
used. The second line is also essential to use cin and cout independently. The
using namespace statement uses std to make cin and cout available in main().
In GCC, the function name main()is preceded by the data type int. Variables are
declared using float data type. Cascading of input operator and output operators
are utilised. Formulae are used in the assignment statements to solve the problem.
The endl is used
instead of '\n'
to print a new line
after each of the
results. Figure
1.1(a) shows the
screenshot of
Program 1.1 in
Geany IDE and
Figure 1.1(b)
shows the output
on execution.
15
Computer Applications (Commerce) - XII
Fig. 1.1(b): Output of Program 1.1 in the terminal window of Geany IDE
This program follows a sequential structure. That is, all statements in the program
are executed in a sequential fashion.
While writing a C++ program, we use the statement "using namespace
std;". Why?
A program cannot have the same name for more than one identifier
(variables or functions) in the same scope. In our home two or more
persons (or even living beings) will not have the same name. If there are, it will surely
make conflicts in the identity within the home. So, within the scope of our home, a name
should be unique. But our neighbouring home may have a person (or any living being)
with the same name as that of one of us. It will not make any confusion of identity
within the respective scopes. But an outsider cannot access a particular person by
simply using the name; but the house name is also to be mentioned.
The concept of namespace is similar to a house name. Different identifiers are associated
to a particular namespace. It is actually a group name in which each item is unique in its
name. User is allowed to create own namespaces for variables and functions. The
keyword using technically tells the compiler about a namespace where it should search
for the elements used in the program. In C++, std is an abbreviation of 'standard' and
it is the standard namespace in which cout, cin and a lot of other things are defined.
So, when we want to use them in a program, we need to follow the format std::cout
and std::cin. This kind of explicit referencing can be avoided with the statement
using namespace std; in the program. In such a case, the compiler searches this
namespace for the elements cin, cout, endl, etc. So whenever the computer comes
across cin, cout, endl or anything of that matter in the program, it will read it as
std::cout, std::cin or std::endl.
The statement using namespace std; doesn't really add a function, it is the include
<iostream> that "loads" cin, cout, endl and all the like.
16
1. Review of C++ Programming
17
Computer Applications (Commerce) - XII
18
1. Review of C++ Programming
In some cases, where integer equality conditions are used for decision making,
switch statement can replace else if ladder. Since char type data are treated
as numeric, they are also used in equality checking. Program 1.4 illustrates this
concept. This program accepts any one of the four letters a, b, c and d. If 'a' is the
input, the word 'Abacus' will be displayed. Similarly, 'Binary' for 'b', 'Computer' for
'c' and 'Debugging' for 'd' will be displayed. For the given problem, actually the
default statement is not required. In that case, there will not be any response
from the program for an input other than the four specified characters. So, to make
the program user-friendly, default case is mentioned in this program.
Program 1.4: To display a word for a given character
#include <iostream>
using namespace std;
int main()
{
char ch;
cout<<"Enter a, b, c or d: ";
cin>>ch;
switch(ch)
{
case 'a': cout<<"Abacus";
break;
case 'b': cout<<"Binary";
break;
case 'c': cout<<"Computer";
break;
case 'd': cout<<"Debugging";
break;
default : cout<<"Invalid input!!";
}
return 0;
}
Program 1.4 also uses the concept of multi branching. Different cases are given,
out of which only one will be executed. Selection will be based on the match between
the value of the expression provided with switch and the constant attached with
any one case. If none of the constants is matched with the value of ch, the default
case will be executed.
19
Computer Applications (Commerce) - XII
Replace the switch statement used in Program 1.4 with else if ladder.
In Program 1.4, if break; statements are removed what will be the
output?
The else if ladder used in Program 1.3 cannot be replaced with switch.
Let us do
Why?
Conditional operator (?:)
It is a ternary operator of C++ and it requires three operands. It can substitute if -
else statement. The if - else statement used in Program 1.2 can be replaced by
the following:
final_ce = (ce1>ce2) ? ce1 : ce2;
If we have to find the largest among three scores, nesting of conditional operator
can be used as follows:
final_ce = (ce1>ce2) ? ((ce1>ce3)?ce1:ce3) :
((ce2>ce3)?ce2:ce3);
1.2.2 Looping statements
C++ provides three looping statements: while, for and do-while. A looping
statement has four components: initialisation expression, test expression, update
expression and loop-body. The loop-body is the set of statements for repeated
execution. The execution is continued as long as the test expression (condition) is
true. The variable used in the test expression, called loop control variable, gets its
initial value through the initialisation expression (or statement). Update expression
changes the value of the loop control variable. Usually, it takes place after each
execution of the loop-body.
Looping statements, also called iteration statements, are classified into two: entry-
controlled and exit-controlled. In entry-controlled loops, test expression is evaluated
before the execution of the loop-body. Program control enters the loop-body only
if the condition is true. while and for are examples of entry-controlled loops.
But in exit-controlled loop, condition is checked only after executing the loop-
body. So it is certain that the loop-body will be executed at least once in the case of
exit-controlled loop. do-while statement belongs to this category.
All the three expressions (initialization, test and update) are placed together in for
loop. But in the case of while and do-while, initialisation expression has to be
given before the loop and update expression within the loop-body. Test expression
appear along with the word while. Let us see some programs to understand the
working of these loops.
20
1. Review of C++ Programming
In Program 1.5, num is the loop control variable as it is involved in the test
expression. The initialisation of this variable is through an input statement. Note
that the updation expression is within the loop-body. If the input is not a positive
number, the body will never be executed.
Let us see another program that uses for statement to constitute a loop.
Program 1.6: To find the sum of the first N natural numbers
#include <iostream>
using namespace std;
int main()
{
int n, sum=0;
cout<<"Enter the limit: ";
cin>>n;
for(int i=1; i<=n; i++)
sum=sum+i;
cout<<"Sum of the first "<<n<<" natural numbers = "<<sum;
return 0;
}
21
Computer Applications (Commerce) - XII
In Program 1.6, the variable i is the loop control variable and is initialised with an
assignment statement. The updation is done with increment operation. The program
needs a loop based on counting. The for statement is more appropriate in such
situations.
As mentioned earlier, do-while loop ensures the execution of loop-body at least
once. Its application is illustrated in the following program.
Program 1.7: To find the average height of a group of students
#include <iostream>
using namespace std;
int main()
{
float hgt, sum=0, avg_hgt;
short n=0;
char ch;
do
{
cout<<"Enter the height: ";
cin>>hgt;
n++;
sum=sum+hgt;
cout<<"Any more student (Y/N)? ";
cin>>ch;
}while (ch=='Y' || ch=='y');
avg_hgt=sum/n;
cout<<"Average Height = "<<avg_hgt;
return 0;
}
The execution of the loop-body in Program 1.7 is repeated as long as user responds
by inputting 'Y' or 'y'.
Rewrite the looping segment of Program 1.5 using for and do-
while statements.
Rewrite the looping segment of Program 1.6 using while and do-
while statements.
Let us do
Rewrite the looping segment of Program 1.7 using for and while
statements.
22
1. Review of C++ Programming
24
1. Review of C++ Programming
When working with nested loops, the control variable of the outer *
loop changes its value only after the inner loop is terminated. Let * *
us write a program to display the given triangle using nested loop. * * *
Program 1.8: To display a triangle of stars * * * *
* * * * *
#include<iostream>
using namespace std;
int main()
{
short int i, j;
for(i=1; i<=5; ++i) //outer loop
{
cout<< "\n" ;
for(j=1; j<=i; ++j) // inner loop
cout<< '*';
}
return 0;
}
25
Computer Applications (Commerce) - XII
goto label;
............;
............;
label: ............;
............;
where the label can appear in the program either before or after goto statement.
The label is followed by a colon (:) symbol. For example, consider the following
code fragment which prints numbers from 1 to 50.
int i=1;
start:
cout<<i;
++i;
if (i<=50)
goto start;
Here, the cout statement prints the value 1. After that i is incremented by 1 (now
i=2), then the test expression i<=50 is evaluated. Since it is True the control is
transferred to the statement marked with the label start. When the test expression
evaluates to False, the process terminates and transfers the program control
following the if statement. It is to be noted that the usage of goto is not encouraged
in structured programming.
1.4.2 break statement
We have already discussed the effect of break in switch statement. It transfers
the program control outside the switch block. When a break statement is
encountered in a loop (for, while, do-while), it takes the program control outside
the immediate enclosing loop. Execution continues from the statement immediately
after the control structure. Let us see how it affects the execution of loops. Consider
the following two program segments.
Code segment 1:
i=1;
while(i<=10)
{
cin>>num;
if (num==0)
break;
cout<<"Entered number is: "<<num;
cout<<"\nInside the loop";
++i;
}
cout<<"\nComes out of the loop";
26
1. Review of C++ Programming
The above code fragment allows to input 10 different numbers. During the input if
any number happens to be 0, the program control comes out of the loop by skipping
the rest of the statements within the loop-body and displays the message "Comes
out of the loop" on the screen. Let us consider another code segment that
uses break within a nested loop.
Code segment 2:
for(i=1; i<=5; ++i) //outer loop
{
cout<<"\n";
for(j=1; j<=i; ++j) //inner loop
{ *
cout<<"* "; * *
if (j==3) break; * * *
} * * *
} * * *
This code segment will display the given pattern:
The nested loop executes normally for the value of i=1, i=2, i=3. For each value
of i, the variable j takes values from 1 to i. When the value of i becomes 4, the
inner loop executes for the value of j=1, j=2, j=3 and comes out from the inner
loop on executing the break statement.
1.4.3 continue statement
The statement continue is another jump statement used for skipping over a part
of the code within the loop-body and forcing the next iteration. The break statement
forces termination of the loop, but the continue statement forces next iteration
of the loop. The following program segment explains the working of a continue
statement:
for (i=1; i<=10; ++i)
{
if (i==6)
continue;
cout<<i<<"\t";
}
This code gives the following output:
1 2 3 4 5 7 8 9 10
Note that 6 is not in the list. When the value of i becomes 6 the continue statement
is executed. As a result, the output statement is skipped and program control goes
to the update expression for next iteration.
27
Computer Applications (Commerce) - XII
A break statement inside a loop will abort the loop and transfer control to the
statement following the loop. A continue statement will just abandon the current
iteration and let the loop continue with next iteration. When a continue statement
is used within while and do-while loops, care should be taken to avoid infinite
execution.
Let us compare break and continue statements. Table 1.3 is
designed to show the comparison aspects. Some of the entries are
filled. The remaining entries are left for you to fill with proper
Let us do comparison points.
continue break
• ....................................................... • Used only with loops
• Takes the control outside the loop • .......................................................
by skipping the remaining part of the .......................................................
loop
.......................................................
• ....................................................... • Program control goes outside only
....................................................... when the test expression of the loop
returns false
Table 1.3: Comparison between break and continue
Let us write a program that requires the use of nested loops. Program 1.9 can
display all prime numbers below 100.
Program 1.9: To display all prime numbers below 100
#include<iostream>
using namespace std;
int main()
{ short int n, i, flag;
cout<<"Prime numbers below 100 are...\n";
for(n=2; n<=100; n++) //Outer loop
{ flag=1;
for(i=2; i<=n/2; i++) //Inner loop
if(n%i==0)
{ flag=0;
break;//Takes the control outside the iiner loop
}
if(flag==1) cout<<n<<'\t';
}
return 0;
}
28
1. Review of C++ Programming
In Program 1.8, the variable n is given the values from 2 to 100 through the outer
loop. Each value is checked for prime using the inner loop. If any of the values
from 2 to n/2 is found to be a factor of n, inner loop is terminated by changing
the value of flag from 1 to 0. The value of n, for which flag remains 1 after the
termination of the inner loop, is prime and is printed.
Let us conclude
We have refreshed ourselves with the basic concepts of C++ language. Character
set, tokens, data types, type modifiers, expressions and type conversions are
presented in capsule form. Different types of C++ statements are recollected with
the help of examples. Various control transfer statements are briefly explained with
programs. Nested loops and the two jump statements break and continue are
introduced as the new concepts. A clear-cut idea about these topics is very much
essential to learn the concepts covered in Chapters 2 and 3 of this book.
Let us practice
1. Write a C++ program to display all palindrome numbers between 100 and 200.
2. Write a C++ program to display all Armstrong numbers below 1000.
3. Write a C++ program to display all perfect numbers below 1000.
4. Write a C++ program to display the multiplication table of a number.
5. Write a C++ program to prepare electricity bill for a group of consumers.
The previous meter reading and current reading are the inputs. The payable
amount is to be calculated using the following criteria:
Up to 300 units : Rs. 5.00/- per unit
Up to 350 units : Rs. 5.70/- per unit
Up to 400 units : Rs. 6.10/- per unit
Up to 500 units : Rs. 6.70/- per unit
Above 500 units : Rs. 7.50/- per unit
The program should provide facility to input the details of any number of
consumers as the user wants.
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
Let us assess 123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
29
Computer Applications (Commerce) - XII
30
2 Arrays
W
e use variables to store data in
Significant Learning Outcomes
programs. But if the quantity of
data is large, more variables are to
After the completion of this chapter, the be used. This will cause difficulty in accessing
learner the required data. We have revised the concept
• identifies the scenarios where an of C++ data types in Chapter 1 and we used
array can be used. basic data types to declare variables and
perform type conversion. In this chapter, a
• uses arrays to refer to a group of
derived data type in C++, named 'array' is
data.
introduced. The word ‘array’ is not a data type
• familiarises with the memory name, rather it is a kind of data type derived
allocation for arrays. from fundamental data types to handle large
• accesses any element in an array number of data easily. We will discuss the
while solving problems. creation and initialisation of arrays, and
• solves problems in which large operations like traversal.
amount of data is to be processed.
2.1 Array and its need
• represnts strings using character
arrays. An array is a collection of elements of the
same type placed in contiguous memory
• carries out various word processing
locations. Arrays are used to store a set of
operations using character arrays.
values of the same type under a single variable
name. Each element in an array can be accessed
using its position in the list, called index number
or subscript.
Why do we need arrays? We will illustrate this
with the help of an example. Let us consider a
situation where we need to store the scores of
20 students in a class and has to find their class
Computer Applications (Commerce) - XII
average. If we try to solve this problem by making use of variables, we will need 20
variables to store students’ scores. Remembering and managing these 20 variables
is not an easy task and the program may become complex and difficult to understand.
int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;
float avg;
cin>>a>>b>>c>>d>>e>>f>>g>>h>>i>>j>>k>>l>>m>>n>>o>>p>>q>>r>>s>>t;
avg = (a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+t)/20.0;
As it is, this code is fine. However, if we want to modify it to deal with the scores of
a large number of students, say 1000, we have a very long and repetitive task at
hand. We have to find a way to reduce the complexity of this task.
The concept of array comes as a boon in such situations. As it is a collection of
elements, memory locations are to be allocated. We know that a declaration statement
is needed for memory allocation. Let us see how arrays are declared and used.
In the syntax, data_type is the type of data that the array variable can store,
array_name is an identifier for naming the array and the size is a positive integer
number that specifies the number of elements in the array. The following is an
example:
int num[10];
The above statement declares an array named num that can store 10 integer numbers.
Each item in an array is called an element of the array. The elements in the array
are stored sequentially as shown in Figure 2.1. The first element is stored in the first
location; the second element is stored in the second location and so on.
num[0] num[1] num[2] num[3] num[4] num[5] num[6] num[7] num[8] num[9]
Index→ 0 1 2 3 4 5 6 7 8 9
Fig. 2.1: Arrangement of elements in an array
Since the elements in the array are stored sequentially, any element can be accessed
by giving the array’s name and the element’s position. This position is called the
index or subscript value. In C++, the array index starts with zero. If an array is
32
2. Arrays
declared as int num[10]; then the possible index values are from 0 to 9. In this
array, the first element can be referenced as num[0] and the last element as num[9].
The subscripted variable, num[0], is read as “num of zero” or “num zero”. It’s a
shortened way of saying “the num array subscripted by zero”. So, the problem of
referring the scores of 1000 students can be resolved by the following statement:
int score[1000];
The array, named score, can store the scores of 1000 students. The score of the
first student is referenced by score[0] and that of the last by score[999].
2.1.2 Memory allocation for arrays
The amount of storage required to hold an array is directly related to its type and
size. Figure 2.2 shows the memory allocation for the first five elements of array
num, assuming 1000 as the address of the first element. Since num is an integer type
array, size of each element is 4 bytes (in a system with 32 bit integer representation
using GCC) and it will be represented in memory as shown in Figure 2.2.
The memory space allocated for an array can be computed using the following
formula:
total_bytes = sizeof(array_type) × size_of_array
For example, total bytes allocated for the array declared as float a[10]; will be
4 × 10 = 40 bytes.
2.1.3 Array initialisation
Array elements can be initialised in their declaration statements in the same manner
as in the case of variables, except that the values must be included in braces, as
shown in the following examples:
int score[5] = {98, 87, 92, 79, 85};
char code[6] = {‘s’, ‘a’, ‘m’, ‘p’, ‘l’, ‘e’};
float wgpa[7] = {9.60, 6.43, 8.50, 8.65, 5.89, 7.56, 8.22};
Initial values are stored in the order they are written, with the first value used to
initialize element 0, the second value used to initialize element 1, and so on. In the
first example, score[0] is initialized to 98, score[1] is initialized to 87, score[2]
is initialized to 92, score[3] is initialized to 79, and score[4] is initialized to 85.
33
Computer Applications (Commerce) - XII
If the number of initial values is less than the size of the array, they will be stored in
the elements starting from the first position and the remaining positions will be
initialized with zero, in the case of numeric data types. For char type array, such
positions will be initialised with ' ' (space bar) character. When an array is initialized
with values, the size can be omitted. For example, the following declaration statement
will reserve memory for five elements:
int num[] = {16, 12, 10, 14, 11};
2. 1.4 Accessing elements of arrays
Array elements can be used anywhere in a program as we do in the case of normal
variables. We have seen that array is accessed element-wise. That is, only one element
can be accessed at a time. The element is specified by the array name with the subscript.
The following are some examples of using the elements of the array named score:
score[0] = 95;
score[1] = score[0] - 11;
cin >> score[2];
score[3] = 79;
cout << score[2];
sum = score[0] + score[1] + score[2] + score[3] + score[4];
The subscript values in the above statement can be replaced by the control variable
of for loop to access each element in the array sequentially. The following code
segment illustrates this concept:
sum = 0;
for (i=0; i<5; i++)
sum = sum + score[i];
An array element can be assigned a value interactively by using an input statement,
as shown below:
for(int i=0; i<5; i++)
cin>>score[i];
34
2. Arrays
When this loop is executed, the first value read is stored in the array element
score[0], the second in score[1] and the last in score[4].
Program 2.1 shows how to read 5 numbers and display them in the reverse order.
The program includes two for loops. The first one allows the user to input array
values. After five values have been entered, the second for loop is used to display
the stored values from the last to the first.
Program 2.1: To input the scores of 5 students and display them in
reverse order
#include <iostream>
using namespace std;
int main()
{
int i, score[5];
for(i=0; i<5; i++) // Reads the scores
{
cout<<"Enter a score: ";
cin>>score[i];
}
for(i=4; i>=0; i--) // Prints the scores
cout<<"score[" << i << "] is " << score[i]<<endl;
return 0;
}
Let us solve another problem that requires traversal operation. Program 2.3 accepts
five numbers from a user and finds the sum of these numbers.
Program 2.3: To find the sum of the elements of an array
#include <iostream>
using namespace std;
int main()
{
int a[5], i, sum;
cout<<"Enter the elements of the array :";
for(i=0; i<5; i++)
cin >> a[i]; //Reading the elements
sum = 0;
for(i=0; i<5; i++)
sum = sum + a[i]; // A case of traversal
cout<<"\nSum of the elements of the array is "<< sum;
return 0;
}
The following is a sample output of Program 2.3:
Enter the elements of the array : 12 3 6 1 8
Sum of the elements of the array is 30
Program 2.4 illustrates another case of traversal to find the largest element in an
array. In this program a variable big is used to hold the largest value. Initially it is
assigned with the value in the first location. Then it is compared with the remaining
elements. Whenever a larger value is found, it repalces the value of big.
Program 2.4: To find the largest element in an array
#include <iostream>
using namespace std;
int main()
{
int a[5], i, big;
cout<<"Enter the elements of the array :";
for(i=0; i<5; i++)
cin >> a[i];
big = a[0];
for(i=1; i<5; i++)
if (a[i] > big) // A case of traversal
big = a[i];
37
Computer Applications (Commerce) - XII
38
2. Arrays
Array Name
my_name
Elements
N i k e t h
Subscripts
0 1 2 3 4 5 6 7 8 9
Fig. 2.3 : Memory allocation for the character array
So, let us conclude that a character array can be used to store a string, since it is a
sequence of characters. However, it is true that we do not get the feel of inputting
a string. Instead, we input the characters constituting the string one by one.
In C++, character arrays have some privileges over other arrays. Once we declare a
character array, the array name can be considered as an ordinary variable that can
hold string data. Let’s say that a character array name is equivalent to a string variable.
Thus your name can be stored in the variable my_name (the array name) using the
following statement:
cin >> my_name;
It is important to note that this kind of usage is wrong in the case of arrays of other
data types. Now let us complete the program. It will be like the one given in Program
2.5.
Program 2.5 To input a string and display
#include <iostream>
using namespace std;
int main()
{
char my_name[10];
cout << "Enter your name: ";
cin >> my_name;
cout << "Hello " << my_name;
return 0;
}
On executing this program we will get the output as shown below.
Enter your name: Niketh
Hello Niketh
Note that the string constant is not "Hello", but "Hello " (a white space is
given after the letter 'o').
39
Computer Applications (Commerce) - XII
Run Program 2.5 and input your full name by expanding the initials
if any, and check whether the output is correct or not. If your name
contains more than 10 characters, increase the size of the array as
Let us do needed.
2.3 Memory allocation for strings
We have seen how memory is allocated for an array of characters. As Figure 2.3
shows, the memory required depends upon the number of characters stored. But if
we input a string in a character array, the scene will be different. If we run Program
2.5 and input the string Niketh, the memory allocation will be as shown in Figure
2.4.
Null character '\0' is stored
Array Name
at the end of the string
my_name
N i k e t h \0
0 1 2 3 4 5 6 7 8 9
Fig. 2.4 : Memory allocation for the character array
Note that a null character '\0' is stored at the end of the string. This character is
used as the string terminator and added at the end automatically. Thus we can say
that memory required to store a string will be equal to the number of characters in
the string plus one byte for null character. In the above case, the memory used to
store the string Niketh is seven bytes, but the number of characters in the string is
only six.
As in the case of variable initialization, we can initialize a character array with a
string as follows:
char my_name[10] = "Niketh";
char str[] = "Hello World";
In the first statement 10 memory locations will be allocated and the string will be
stored with null character as the delimiter. The last three bytes will be left unused.
But, for the second statement, size of the array is not specified and hence only 12
bytes will be allocated (11 bytes for the string and 1 for '\0').
2.4 Input/Output operations on strings
Program 2.5 contains input and output statements for string data. Let us modify
the declaration statement by changing the size of the array to 20. If we run the
program by entering the name Maya Mohan, the output will be as follows:
Enter your name: Maya Mohan
Hello Maya
40
2. Arrays
Note that though there is enough size for the array, we get only the word "Maya" as
the output. Why does this happen?
Let us have a close look at the input statement: cin>>my_name;. We have
experienced that only one data item can be input using this statement. A white
space is treated as a separator of data. Thus, the input Maya Mohan is treated as
two data items, Maya and Mohan separated by white space. Since there is only
one input operator (>>) followed by a variable, the first data (i.e., Maya) is stored.
The white space after "Maya" is treated as the delimiter.
So, the problem is that we are unable to input strings containing white spaces. C++
language gives a solution to this problem by a function, named gets(). The function
gets() is a console input function used to accept a string of characters including
white spaces from the standard input device (keyboard) and store it in a character
array.
The string variable (character array name) should be provided to this function as
shown below:
gets(character_array_name);
When we use this function, we have to include the library file cstdio.h in the
program. Let us modify Program 2.5, by including the statement
#include<cstdio> , and replacing the statement cin>>my_name; by
gets(my_name); After executing the modified program, the output will be as
follows:
Enter your name: Maya Mohan
Hello Maya Mohan
The output shows the entire string that we input. See the difference between gets()
and cin.
Though we do not use the concept of subscripted variable for the input and output
of strings, any element in the array can be accessed by specifying its subscript along
with the array name. We can access the first character of the string by my_name[0],
fifth character by my_name[4] and so on. We can even access the null character
('\0') by its subscript. Program 2.6 illustrates this idea.
Program 2.6: To input a string and count the vowels in a string
#include <iostream>
#include <cstdio> //To use gets() function
using namespace std;
int main()
{
char str[20];
41
Computer Applications (Commerce) - XII
int vow=0;
cout<<"Enter a string: ";
gets(str);
for(int i=0; str[i]!='\0'; i++)
switch(str[i])
{ case 'a':
case 'e':
case 'i':
case 'o':
case 'u': vow++;
}
cout<<"No. of vowels in the string "<<str<<" is "<<vow;
return 0;
}
If we run Program 2.6 by inputting the string “hello guys”, the following output
can be seen:
Enter a string: hello guys
No. of vowels in the string hello guys is 3
Now, let us analyse the program and see how it works to give this output.
l In the beginning, the gets() function is used and so we can input the string
"hello guys".
l The body of the for loop will be executed as long as the element in the array,
referenced by the subscript i, is not the null character ('\0'). That is, the
body of the loop will be executed till the null character is referenced.
l The body of the loop contains only a switch statement. Note that, no
statements are given against the first four cases of the switch. In the last
case, the variable vow is incremented by 1. You may think that this is required
for all the cases. Yes, you are right. But, you should use the break statement
for each case to exit the switch after a match. In this program the action for
all the cases are the same and that is why we use this style of code.
l While the for loop iterates, the characters will be retrieved one by one for
matching against the constants attached to the cases. Whenever a match is found,
the variable vow is incremented by 1.
l As per the input string, matches occur when the value of i becomes 1, 4 and 7.
Thus, the variable vow is incremented by 1 three times and we get the correct
output.
We have seen how gets() function facilitates input of strings. Just like the other
side of a coin, C++ gives a console function named puts() to output string data.
42
2. Arrays
The function puts() is a console output function used to display a string data on
the standard output device (monitor). Its syntax is:
puts(string_data);
The string constant or variable (character array name) to be displayed should be
provided to this function. Observe the following C++ code fragment:
char str[10] = "friends";
puts("hello");
puts(str);
The output of the above code will be as follows:
hello
friends
Note that the string "friends" in the character array str[10] is displayed in a
new line. Try this code using cout<<“hello”; and cout<<str; instead of the
puts() functions and see the difference. The output will be in the same line without
a space in between them in the case of cout statement.
Predict the output, if the input is “HELLO GUYS” in Program 2.6.
Execute the program with this input and check whether you get the
correct output. Find out the reason for difference in output. Modify
Let us do the program to get the correct output for any given string.
Let us conclude
We have discussed array as a data type to refer to a group of same type of data.
Memory allocation for arrays is explained with the help of schematic diagrams. The
use of looping statements, especially for loop in manipulating the elements of an
array are also illustrated through programs. We have also seen that how arrays help
to handle strings effectively in programs.
Let us practice
1. Write a C++ program to input the amount of sales for 12 months into an
array named SalesAmt. After all the input, find the total and average amount
of sales.
2. Write a C++ program to create an array of N numbers, find the average and
display those numbers greater than the average.
43
Computer Applications (Commerce) - XII
3. Write a C++ program to swap the first and the last elements of an integer
array.
4. Write a C++ program to input 10 integer numbers into an array and determine
the maximum and minimum values among them.
5. Write a C++ program to input a string and find the number of uppercase
letters, lowercase letters, digits, special characters and white spaces.
6. Write a C++ program to count the number of words in a sentence.
7. Write a C++ program12345678901234567890123456789012123456789012345678901234567890121234567
to find the length of a string.
12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
Let us assess 12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
1. The elements of an array with ten elements are numbered from ____ to ____.
2. An array element is accessed using _____.
3. If AR is an array, which element will be referenced using AR[7]?
4. Consider the array declaration int a[3]={2,3,4}; What is the value of a[1]?
5. Consider the array declaration int a[]={1,2,4}; What is the value of a[1]?
6. Printing all the elements of an array is an example for _____ operation.
7. Write down the output of the following code segment:
puts(“hello”);
puts(“friends”);
8. Write the initialisation statement to store the string "GCC".
9. Define an Array.
10. What does the declaration int studlist[1000]; mean?
11. How is memory allocated for a single dimensional array?
12. Write C++ statements to accept an array of 10 elements and display the count
of even and odd numbers in it.
13. Read the following statements:
char name[20];
cin>>name;
cout<<name;
What will be the output if you input the string “Sachin Tendulkar”? Justify
your answer.
14. Write C++ statements to accept two single dimensional arrays of equal length
and find the difference between corresponding elements.
15. Write a program to check whether a string is a palindrome or not.
44
3 Functions
W
e discussed some simple programs
Significant Learning Outcomes
in the previous chapters. But to
After the completion of this chapter, the solve complex problems, larger
learner programs running into thousands of lines
• identifies the merits of modular of code are required. Complex problems
programming in problem solving. are divided into smaller ones and programs
• classifies various input output to solve each of these sub problems are
functions for character and string written. In other words, we break the larger
data. programs into smaller sub programs.. In
• compares character input functions. C++, function is a way to divide large
• uses appropriate character and
programs into smaller sub programs. We are
string functions for the I/O
familiar with the function main(). We know
operations.
that it is the essential function in a C++
• applies mathematical functions for
program. The statements required to solve
solving problems.
a problem are given within a pair of braces
{ and } after the header int main(). We
• uses string functions for the
manipulation of string data.
have not broken a problem into sub
• manipulates character data with
problems so far and hence the entire task is
predefined character functions.
assisgned to main()function. But there are
• implements modular programming
some functions readily available for use,
by creating functions.
which makes programming simpler. Each of
• identifies the role of arguments and
them is assigned with a specific task and they
compares different methods of
are stored in header files. So, these functions
function calling.
are known as built-in functions or predefined
• recognises the scope of variables
functions. Besides such functions, we can
and functions in a program.
define functions for a specific task. These are
called user-defined functions. In this chapter
we will discuss some important predefined
Computer Applications (Commerce) - XII
functions and learn how to define our own functions. Before going into these, let us
familiarise ourselves with a style of programming called modular programming.
3.1 Concept of modular programming
Let us consider the case of a school management software. It is a very large and
complex software which may contain many programs for different tasks. The
complex task of school management can be divided into smaller tasks or modules
and developed in parallel, and later integrated to build the complete software as
shown in Figure 3.1.
In programming, the entire problem will be divided into small sub problems that
can be solved by writing separate programs. This kind of approach is known as
modular programming. Each sub task will be considered as a module and we write
programs for each module. The process of breaking large programs into smaller
sub programs is called modularization. Computer programming languages have
different methods to implement modularization. The sub programs are generally
called functions. C++ also facilitates modular programming with functions.
3.1.1 Merits of modular programming
The modular style of programming has many advantages. It reduces the complexity
and size of the program, makes the program more readable, improves re-usability
and makes the debugging process easy. Let us discuss these features in detail:
Reduces the size of the program: In some cases, certain instructions in a program
may be repeated at different points of the program. Consider the expression
x5 + y7
x+ y
. To evaluate this expression for given values of x and y, we have to use
46
3. Functions
47
Computer Applications (Commerce) - XII
Without main(), C++ program will not run. All other functions will be executed
when they are called or invoked (or used) in a statement.
3.3 Predefined functions
C++ provides a number of functions for various tasks. We will discuss only the
most commonly used functions. While using these functions, some of them require
data for performing the task assigned to it. We call them parameters or arguments
and are provided within the pair of parentheses of the function name. There are
certain functions which give results after performing the task. This result is known
as return-value of the function. Some functions do not return any value, rather
they perform the specified task. In the following sections, we discuss functions for
manipulating strings, performing mathematical operations and processing character
data. While using these functions the concerned header files are to be included in
the program.
3.3.1 Console functions for character I/O
We have discussed functions for input/output operations on strings. C++ also
provides some functions for performing input/ouput operations on characters. In
Chapter 2, we discussed gets() function and its advantage in string input. Now
let us see some functions to input and output character data. These functions require
the inclusion of header file cstdio (stdio.h in Turbo C++ IDE) in the program.
getchar()
This function returns the character that is input through the keyboard. The character
can be stored in a variable as shown in the example given below:
char ch = getchar();
In the previous chapter we have seen puts() function and its advantage in string
output. Let us have a look at a function used to output character data.
putchar()
This function displays the character given as the argument on the standard output
unit (monitor). The argument may be a character constant or a variable. If an integer
value is given as the argument, it will be considered as an ASCII value and the
corresponding character will be displayed. The following code segment illustrates
the use of putchar() function.
char ch = 'B'; //assigns 'B' to the variable ch
putchar(ch); //displays 'B' on the screen
putchar('c'); //displays 'c' on the screen
putchar(97); //displays 'a' on the screen
49
Computer Applications (Commerce) - XII
Program 3.1 illustrates the working of these functions. This program allows inputting
a string and a character to be searched.
Program 3.1: To search for a character in a string using console functions
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char str[20], ch;
int i, num=0;
puts("Enter a string:"); //To print '\n' after the string
gets(str);//To accept a string with white spaces
cout<<"\nEnter the character to be searched: ";
ch=getchar(); //To input the character to be searched
/* A loop to search for the character and count its
occurrences in the string. Search will be
terminated when null character is found */
for(i=0; str[i]!='\0'; i++)
if (str[i]==ch)
num++;
cout<<"\nThe number of occurences of the character ";
putchar(ch);
cout<<" is : "<<num;
return 0;
}
Sample output of the above program is given below
Enter a string:
examination
Enter the character to be searched: a
The number of occurences of the character a is : 2
3.3.2 Stream functions for I/O operations
C++ provides another facility to perform input/output operations on character
and strings. It is in the form of functions that are available in the header file iostream.
These functions are generally called stream functions since they allow a stream of
bytes (data) to flow between memory and objects. Devices like the keyboard and
the monitor are referenced as objects in C++. Let us discuss some of these functions.
50
3. Functions
A. Input functions
These functions allow the input of character and string data. The input functions
such as get() and getline() allow a stream of bytes to flow from input object
into the memory. The object cin is used to refer to keyboard and hence whenever
we input data using keyboard, these functions are called or invoked using this object
as cin.get() and cin.getline(). Note that a period symbol (.), called dot
operator is used between the object cin and the function.
i. get()
It can accept a single character or multiple characters (string) through the keyboard.
To accept a string, an array name and size are to be given as arguments. Following
code segment illustrates the usage of this function.
char ch, str[10];
ch=cin.get(ch); //accepts a character and stores in ch
cin.get(ch); //equivalent to the above statement
cin.get(str,10); //accepts a string of maximum 10 characters
ii. getline()
It accepts a string through the keyboard. The delimiter will be Enter key, the number
of characters or a specified character. This function uses two syntaxes as shown in
the code segment given below.
char ch, str[10];
int len;
cin.getline(str,len); // With 2 arguments
cin.getline(str,len,ch); // With 3 arguments
In the first usage, getline() function has two arguments - a character array (here
it is, str) and an integer (len) that represents maximum number of characters that
can be stored. In the second usage, a delimiting character (content of ch) can also
be given along with the number of characters. While inputting the string, only
(len–1) characters, or characters upto the specified delimiting character, whichever
occurs first will be stored in the array.
B. Output functions
Output functions like put() and write() allow a stream of bytes to flow from
memory into an output object. The object cout is used with these functions since
we use the monitor for the output.
i. put()
It is used to display a character constant or the content of a character variable given
as argument.
51
Computer Applications (Commerce) - XII
char ch='c';
cout.put(ch); //character 'c' is displayed
cout.put('B'); //character 'B' is printed
cout.put(65); //character 'A' is printed
ii. write()
This function displays the string contained in the argument. For illustration see the
example given below.
char str[10]="hello";
cout.write(str,10);
The above code segment will dispaly the string hello followed by 5 white spaces,
since the second argument is 10 and the number of characters in the string is 5.
Program 3.2: To illustrate the working of stream input/output functions
#include <iostream>
#include <cstring> //To use strlen() function
using namespace std;
int main()
{
char ch, str[20];
cout<<"Enter a character: ";
cin.get(ch); //To input a character to the variable ch
cout<<"Enter a string: ";
cin.getline(str,10,'.'); //To input the string
cout<<"Entered character is:\t";
cout.put(ch); //To display the character
cout.write("\nEntered string is:",20);
cout.write(str,strlen(str));
return 0;
}
On executing Program 3.2, the following output will be obtained:
Enter a character: p
Enter a string: hello world
Entered character is: p
Entered string is:
hello wo
Let us discuss what happens when the program is executed. In the beginning, get()
function allows to input a character, say p. When the function getline() is executed,
we can input a string, say hello world. The put() function is then executed to
52
3. Functions
display the character p. Observe that the write() function displays only hello
wo in a new line. In the getline() function, we specified the integer 10 as the
maximum number of characters to be stored in the array str. Usually 9 characters
will be stored, since one byte is reserved for '\0' character as the string terminator.
But the output shows only 8 characters including white space. This is because, the
Enter key followed by the character input (p) for the get() function, is stored as
the '\n' character in the first location of str. That is why, the string, hello wo is
displayed in a new line.
If we run the program, by giving the input hello.world, the output will be as
follows: Observe the change in the content of str.
Enter a character: a
Enter a string: hello.world
Entered character is: a
Entered string is:
hello
The change has occurred because the getline() function accepts only the
characters that appear before the dot symbol.
53
Computer Applications (Commerce) - XII
Note that the array size is specified in the declaration. The argument may be a string
constant as shown below:
n = strlen("Computer");
The above statement returns 8 and will be stored in n.
ii. strcpy()
This function is used to copy one string into another. The syntax of the function is:
strcpy(string1, string2);
The function will copy string2 to string1. Here string1 is an array of
characters and string2 is an array of characters or a string constants. These are
the arguments for the execution of the function. The following code illustrates its
working:
char s1[10], s2[10] = "Welcome";
strcpy(s1,s2);
cout << s1;
The string "Welcome" contained in the string variable s1 will be displayed on the
screen. The second argument may be a string constant as follows:
char str[10]
strcpy(str,"Welcome");
Here, the string constant "Welcome" will be stored in the variable str. The
assignment statement, str = "Welcome"; is wrong. But we can directly assign
value to a character array at the time of declaration as:
char str[10] = "Welcome";
iii. strcat()
This function is used to append one string to another string. The length of the
resultant string is the total length of the two strings. The syntax of the functions is:
strcat(string1, string2);
Here string1 and string2 are array of characters or string constants. string2
is appended to string1. So, the size of the first argument should be able to
accommodate both the strings together. Let us see an example showing the usage
of this function:
char s1[20] = "Welcome", s2[10] = " to C++";
strcat(s1,s2);
cout << s1;
The above program code will display "Welcome to C++" as the value of the
variable s1. Note that the string in s2 begins with a white space.
54
3. Functions
iv. strcmp()
This function is used to compare two strings. In this comparison, the alphabetical
order of characters in the strings is considered. The syntax of the function is:
strcmp(string1, string2)
The function returns any of the following values in three different situations.
• Returns 0 if string1 and string2 are same.
• Returns a –ve value if string1 is alphabetically lower than string2.
• Returns a +ve value if string1 is alphabetically higher than string2.
The following code fragment shows the working of this function.
char s1[]="Deepthi", s2[]="Divya";
int n;
n = strcmp(s1,s2);
if(n==0)
cout<<"Both the strings are same";
else if(n < 0)
cout<<"s1 < s2";
else
cout<<"s1 > s2";
It is clear that the above program code will display "s1 < s2" as the output.
v. strcmpi()
This function is used to compare two strings ignoring cases. That is, the function
will treat both the upper case and lower case letters as same for comparison. The
syntax and working of the function are the same as that of strcmp() except that
strcmpi() is not case sensitive. This function also returns values as in the case of
strcmp(). Consider the following code segment:
char s1[]="SANIL", s2[]="sanil";
int n;
n = strcmpi(s1,s2);
if(n==0)
cout<<"strings are same";
else if(n < 0)
cout<<"s1 < s2";
else
cout<<"s1 > s2";
The above program code will display "strings are same" as the output,
because the uppercase and lowercase letters will be treated as same during the
comparison.
55
Computer Applications (Commerce) - XII
Program 3.3 compares and concatenates two strings. The length of the newly formed
string is also displayed.
Program 3.3 : To combine two strings if they are different and find its length
#include <iostream>
#include <cstring>
using namespace std; Header file essential
int main() for using string
{ manipulating functions
char s1[15], s2[15], s3[30];
cout<<"Enter two strings: ";
cin>>s1>>s2;
int n;
n=strcmp(s1,s2);
if (n==0)
cout<<"\nThe input strings are same";
else
{
cout<<"\nThe input strings are not same";
strcpy(s3,s1);//Copies the string in s1 into s3
strcat(s3,s2);//Appends the string in s2 to that in s3
cout<<"String after concatenation is: "<<s3;
cout<<"\nLength of the new string is: "
<<strlen(s3);
}
return 0;
}
Sample Output:
Enter two strings:india
kerala
The input strings are not same
String after concatenation is:indiakerala
Length of the new string is: 11
i. abs()
It is used to find the absolute value of an integer. It takes an integer as the argument
(+ve or –ve) and returns the absolute value. Its syntax is:
int abs(int)
The following is an example to show the output of this function:
int n = -25;
cout << abs(n);
The above program code will display 25. If we want to find the absolute value of a
floating point number, we can use fabs() function as used above. It will return
the floating point value.
ii. sqrt()
It is used to find the square root of a number. The argument to this function can be
of type int, float or double. The function returns the non-negative square
root of the argument. Its syntax is:
double sqrt(double)
The following code snippet is an example. This code will display 5.
int n = 25;
float b = sqrt(n);
cout << b;
If the value of n is 25.4, then the answer will be 5.03841
iii. pow()
This function is used to find the power of a number. It takes two arguments x and
y. The argument x and y are of type int, float or double. The function returns
the value of xy. Its syntax is:
double pow(double, double)
The following example shows the working of this function.
int x = 5, y = 4, z;
z = pow(x, y);
cout << z;
The above program code will display 625.
xy means 54 which is 5*5*5*5 i.e. 625
57
Computer Applications (Commerce) - XII
Program 3.4 : To find the area of a triangle and a circle using mathematical
functions
#include <iostream>
#include <cmath> Header file essential
using namespace std; for using mathematical
int main() functions
{
const float pi=22.0/7;
int a,b,c, radius;
float s, area1, area2;
cout<<"Enter the three sides of the triangle: ";
cin>>a>>b>>c;
s = (a+b+c)/2.0;
area1 = sqrt(s*(s-a)*(s-b)*(s-c));
cout<<"The Area of the Triangle is: "<<area1;
cout<<"\nEnter the radius of the circle: ";
cin>>radius;
area2 = pi*pow(radius,2);
cout<<"Area of the Circle is: "<<area2;
return 0;
}
The following is a sample output of the above program:
Enter the three sides of the triangle: 5 7 9
The Area of the Triangle is: 17.4123
Enter the radius of the circle: 2.5
Area of the Circle is: 12.5714
59
Computer Applications (Commerce) - XII
60
3. Functions
vii. tolower()
This function is used to convert the given character into its lower case. The syntax
of the function is:
char tolower(char c)
The function returns the lower case of the given character. If the given character is
in lowercase, the output will be the same.
Consider the statement: c = tolower('A');
After executing the above statement, the value of the variable c will be 'a'. But
when the following statements will be executed, the value of the variable c will be
'a' itself.
char x = ‘a’;
char c = tolower(x) ;
In the case of functions tolower() and toupper(), if the argument is other than
alphabet, the given character itself will be returned on execution.
Program 3.5 illustrates the use of character functions. This program accepts a line
of text and counts the lowercase letters, uppercase letters and digits in the string. It
also displays the entire string both in uppercase and lowercase.
Program 3.5: To count different types of characters in the given string
#include <iostream>
#include <cstdio>
#include <cctype>
using namespace std;
int main()
{
char text[80];
int Ucase=0, Lcase=0, Digit=0;
cout << "Enter a line of text: ";
Loop will be
gets(text);
terminated when the
for(int i=0; text[i]!=’\0'; i++) value of i point to the
if (isupper(text[i])) null character
Ucase++;
else if (islower(text[i]))
Lcase++;
else if (isdigit(text[i]))
Digit++;
61
Computer Applications (Commerce) - XII
Prepare a chart in the following format and fill up the columns with all
predefined functions we have discussed so far.
Function Usage Syntax Example Output
Let us do
62
3. Functions
Let us recollect how we have used the predefined functions strcpy() and sqrt().
We have seen that these functions will be executed when they are called (or used) in
a C++ statement. The function getchar() takes no arguments in the parentheses.
But for strcpy(), two strings are provided as arguments or parameters. Without
these arguments this function will not work, because it is defined with two string
(character array) arguments. In the case of sqrt(), it requires a numeric data as
argument and gives a result (of double type) after performing the predefined
operations on the given argument. This result, as mentioned earlier, is called the
return-value of the function. The data type of a function depends on this value. In
other words we can say that the function should return a value which is of the same
data type of the function. So, the data type of a function is also known as the return
type of the function. Note that we use return 0; statement in main() function,
since it is defined with int data type as per the requirement of GCC.
The number and type of arguments depend upon the data required by the function
for processing. Note that a function can return only one value. But some functions
like puts() and gets() do not return any value. The header of such functions
uses void as the return type. A function either returns one value or nothing at all.
3.4.1 Creating user-defined functions
Based on the syntax discussed above, let us create some functions. The following is
a function to display a message.
void saywelcome()
{
cout<<"Welcome to the world of functions";
}
The name of the function is saywelcome(), its data type (return type) is void
and it does not have any argument. The body contains only one statement.
Now, let us define a function to find the sum of two numbers. Four different types
of definitions are given for the same task, but they vary in definition style and hence
the usage of each is different from others.
Function 1 Function 2
void sum1() int sum2()
{ {
int a, b, s; int a, b, s;
cout<<"Enter 2 numbers: "; cout<<"Enter 2 numbers: ";
cin>>a>>b; cin>>a>>b;
s=a+b; s=a+b;
cout<<"Sum="<<s; return s;
} }
64
3. Functions
Function 3 Function 4
void sum3(int a, int b) int sum4(int a, int b)
{ {
int s; int s;
s=a+b; s=a+b;
cout<<"Sum="<<s; return s;
} }
Let us analyse these functions and see how they are different. The task is the same in
all these functions, but they differ in the number of parameters and return type.
Table 3.1 shows that the function defined with a data type other than void should
return a value in accordance with the data type. The return statement is used for
this purpose (Refer to functions 2 and 4). The return statement returns a value to
the calling function and transfers the program control back to the calling function.
So, remember that if a return statement is executed in a function, the remaining
statements within that function will not be executed.
In most of the functions, return is placed at the end of the function. The functions
defined with void data type may not have a return statement within the body. But
if we use return statement, we cannot provide any value to it.
Now, let us see how these functions are to be called and how they are executed. We
know that no function other than main()is executed automatically. The sub
functions, either predefined or user-defined, will be executed only when they are
called from main() function or other user-defined function. The code segments
within the rectangles of the following program shows the function calls. Here the
main() is the calling function and sum1(), sum2(), sum3(), and sum4()are the
called functions.
65
Computer Applications (Commerce) - XII
int main()
{
int x, y, z=5, result;
cout << "\nCalling the first function\n";
sum1();
cout << "\nCalling the second function\n";
result = sum2();
cout << "Sum given by function 2 is " << result;
cout << "\nEnter values for x and y : ";
cin >> x >> y;
cout << "\nCalling the third function\n";
sum3(x,y);
cout << "\nCalling the fourth function\n";
result = sum4(z,12);
cout << "Sum given by function 4 is " << result;
cout << "\nEnd of main function";
return 0;
}
The output of the program will be as follows:
Calling the first function Input for a and
Enter 2 numbers: 10 25 b of sum1()
Sum=35
Calling the second function
Enter 2 numbers: 5 7
Sum given by function 2 is 12 Input for a and b
Enter values for x and y : 8 13 of sum2()
Calling the third function
Sum=21
Input for x and y of
Calling the fourth function
main()
Sum given by function 4 is 17
End of main function
Function 4 requires two numbers for the task assigned and hence we provide two
arguments. The function performs some calculations and gives a result. As there is
only one result, it can be returned. Comparatively this function is a better option to
find the sum of any two numbers.
Now, let us write a complete C++ program to find the product of two numbers.
We will write the program using a user-defined function. But where do we write the
66
3. Functions
user-defined function in a C++ program? The following table shows two styles to
place the user-defined function:
Program 3.6 - Product of two numbers - Program 3.7
When we compile Program 3.6, there will be no error. But if we compile Program
3.7, there will be an error ‘product was not declared in this scope'.
Let us see what this error means.
3.4.2 Prototype of functions
We have seen that a C++ program can contain any number of functions. But it
must have a main() function to begin the execution. We can write the definitions
of functions in any order as we wish. We can define the main() function first and
all other functions after that or vice versa. Program 3.6 contains the main() function
after the user-defined function, but in Program 3.7, the main() is defined before
the user-defined function. When we compile this program, it will give an error -
"product was not declared in this scope". This is because the function
product() is called in the program, before it is defined. During the compilation
of the main() function, when the compiler encounters the function call product(),
it is not aware of such a function. Compiler is unable to check whether there is such
a function, whether its usage is correct or not, and whether it is accessible or not. So
67
Computer Applications (Commerce) - XII
When the first statement is executed, the values 1000, 3 and 2 are passed to the
argument list in the function definition. The arguments P, N and R get the values
1000, 3 and 2, respectively. Similarly, when the last statement is executed, the values
of the variables x, y and z are passed to the arguments P, N and R.
The variables x, y and z are called actual (original) arguments or actual parameters
since they are the actual data passed to the function for processing. The variables P,
N and R used in the function header are known as formal arguments or formal
parameters. These arguments are intended to receive data from the calling function.
Arguments or parameters are the means to pass values from the calling function
to the called function. The variables used in the function definition as arguments are
known as formal arguments. The constants, variables or expressions used in the
function call are known as actual (original) arguments. If variables are used in
function prototype, they are known as dummy arguments.
Now, let us write a program that uses a function fact() that returns the factorial
of a given number to find the value of nCr. As we know, factorial of a number N is
the product of the first N natural numbers. The value of nCr is calculated by the
n!
formula r!(n − r )! , where n! denotes the factorial of n.
the names of all the parents. The teacher can give you the name list in two ways. She
can take a photo copy of the name list and give it to you. Otherwise, she can give
the original name list itself. What difference would you feel in getting the name list
in these two ways? If the teacher gives the original name list, you will be careful not
to make any marks or writing in the name list because the teacher may want the
same name list for future use. But if you are given a photo copy of the name list,
you can make any marking in the list, because the change will not affect the original
name list.
Let us consider the task of preparing the invitation letter as a function. The name
list is an argument for the function. The argument can be passed to the function in
two ways. One is to pass a copy of the name list and the other is to pass the original
name list. If the original name list is passed, the changes made in the name list, while
preparing the invitation letter, will affect the original name list. Similarly, in C++,
an argument can be passed to a function in two ways. Based on the method of
passing the arguments, the function calling methods can be classified as Call by
Value method and Call by Reference method. The following section describes the
methods of argument passing in detail.
a. Call by value (Pass by value) method
In this method, the value contained in the actual argument is passed to the formal
argument. In other words, a copy of the actual argument is passed to the function.
Hence, if the formal argument is modified within the function, the change is not
reflected in the actual argument at the calling place. In all previous functions, we
passed the argument by value only. See the following example:
void change(int n)
{ The parameter n has its
n = n + 1; own memory location to
cout << "n = " << n << '\n'; store the value 20 in
} change().
void main()
{ The value of x is
int x = 20; passed to n in
change()
change(x);
cout << "x = " << x;
}
When we pass an argument as specified in the above program segement, only a
copy of the variable x is passed to the function. In other words, we can say that only
the value of the variable x is passed to the function. Thus the formal parameter n in
71
Computer Applications (Commerce) - XII
the function will get the value 20. When we increase the value of n, it will not affect
the value of the variable x. The following will be the output of the above code:
n = 21
x = 20
Table 3.2 shows what happens to the arguments when a function is called using call-
by-value method:
Before function call After function call After function execution
main() x main() x main() x
{ 20 { 20 { 20
....... ....... .......
....... ....... .......
} } }
72
3. Functions
void main()
{ The reference of x will be
int x=20; passed to n of the
change(x); change() function, which
cout << "x = " << x; results into the sharing of
} memory.
Note that the only change in the change() function is in the function header. The
& symbol in the declaration of the parameter n means that the argument is a reference
variable and hence the function will be called by passing reference. Hence when the
argument x is passed to the change() function, the variable n gets the address of
x so that the location will be shared. In other words, the variables x and n refer to
the same memory location. We use the name x in the main() function, and the
name n in the change() function to refer the same storage location. So, when we
change the value of n, we are actually changing the value of x. If we run the above
program, we will get the following output:
n = 21
x = 21
Table 3.3 depicts the changes in the arguments when call-by-reference is applied for
the function call.
We have discussed the difference between the two methods of function calling.
Basically the methods differ in the mode of passing arguments. Let us consolidate
the difference between these two methods of function calling. Table 3.4 gives the
clear picture.
73
Computer Applications (Commerce) - XII
Let us discuss a typical example for call by reference method. This program uses a
function that can be called by reference method for exchanging the values of the
two variables in the main() function. The process of exchanging values of two
variables is known as swapping.
Program 3.9: To swap the values of two variables
#include <iostream>
using namespace std;
void swap(int & x, int & y)
{
int t = x;
x = y;
y = t;
}
int main()
{
int m, n;
m = 10;
n = 20;
cout<<"Before swapping m= "<< m <<" and n= "<<n;
swap(m, n);
cout<<"\nAfter swapping m= "<< m <<" and n= "<<n;
return 0;
}
Let us go through the statements in Program 3.9. The actual arguments m and n
are passed to the function by reference. Within the swap() function, the values of
74
3. Functions
x and y are interchanged. When the values of x and y are changed, actually the
change takes place in m and n. Therefore the output of the above program code is:
Before swapping m= 10 and n= 20
After swapping m= 20 and n= 10
Modify the above program by replacing the formal arguments with ordinary
variables and predict the output. Check your answer by executing the code in the
lab.
int main()
{
int x, result;
cout << "Enter a number : "; This is an error because
the variable cb is declared within
cin >> x;
the cube() function. So it
result = cube(x); cannot be used in other functions.
cout << "Cube = " << result;
cout << "\nCube = "<< cb;
return 0;
}
When we compile the program, there will be two errors because of the reasons
shown in the call-outs. The concept of availability or accessibility of variables and
functions is termed as their scope and life time. Scope of a variable is that part of
the program in which it is used. In the above program, scope of the variable cb is
in the cube() function because it is declared within that function. Hence this
variable cannot be used outside the function. This scope is known as local scope.
On completing the execution of a function, memory allocated for all the variables
within a function is freed. In other words, we can say that the life of a variable,
declared within a function, ends with the execution of the last instruction of the
function. So, if we use a variable n within the main(), that will be different from
the argument n of a called function or a variable n within the called function. The
variables used as formal arguments and/or declared within a function have local
scope.
Just like variables, functions also have scope. A function can be used within the
function where it is declared. That is the function is said to have local scope. If it is
declared before the main() function and not within any other function, the scope
of the function is the entire program. That is the function can be used at any place
in the program. This scope is known as global scope. Variables can also be declared
with global scope. Such declarations will be outside all the functions in the program.
Look at Program 3.11 to get more clarity on the scope and life of variables and
functions throughout the program.
76
3. Functions
Program 3.11 : To illustrate the scope and life of variables and functions
#include <iostream>
using namespace std;
int cb; //global variable
void test()//global function since defined above other functions
{
int cube(int n); //It is a local function
cb=cube(x); //Invalid call. x is local to main()
cout<<cb;
}
The given comments explain the scope and life of functions. A function which is
declared inside the function body of another function is called a local function as
it can be used within that function only. A function declared outside the function
body of any other function is called a global function. A global function can be
used throughout the program. In other words, the scope of a global function is the
entire program and that of a local function is only the function where it is declared.
Table 3.5 summarises the scope and life time of variables and functions.
77
Computer Applications (Commerce) - XII
Let us conclude
78
3. Functions
Lab activity
1. Define a function to accept a number and return 1 if it is odd, 0 otherwise.
Using this function write a program to display all odd numbers between 10
and 50.
2. Write a program to find the product of three integer numbers using a user
defined function. Invoke the function using call by value and call by reference
methods. Verify the results.
3. Write a program to find the smallest of three or two given numbers using a
function (use the concept of default arguments).
4. With the help of a user-defined function find the sum of digits of a number.
That is if the given number is 345 then the result should be 3+4+5 = 12.
5. Using a function, write a program to find the area of a circle.
6. Write a program to check whether a number is positive, negative or zero. Use
a user defined function for checking.
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
Let us assess 123456789012345678901234567890121234567890123456789012345678901212345678
79
Computer Applications (Commerce) - XII
80
4. Web Technology
4 Web Technology
W
e are all living in an era of the Internet
Significant Learning Outcomes
and might have accessed it for seeking
infor mation. You might have
After the completion of this chapter, the learner searched for your Class XI results and viewed
• explains how secure communication is
brought about on the web. it from a website. People rely on different
• describes the use of a web server and websites for various purposes like submitting
the concept of web hosting. online applications, viewing web contents,
• differentiates static and dynamic pages. watching movies, banking transactions, purchase
• identifies the differences between
programming languages and scripts. of goods through online transaction, and so
• compares the different types of scripting on. We know that a website is a collection of
languages. web pages. A web page may contain texts,
• explains the need for cascading style graphics, sounds, animations, and movies. A
sheet.
• identifies the basic HTML elements to website consisting of several web pages are
create web pages. designed to give information about an
• lists fundamental HTML tags and their organisation, product, service, etc. How is this
important attributes. website made available on the Internet? These
• classifies the HTML tags.
• uses formatting tags appropriately in web pages are to be stored in web servers
an HTML document to make the web page connected to the Internet, to be made available
attractive. to others. This chapter presents an overview
• identifies the similarities and of communication over the Internet and the
differences among the formatting tags.
• observes the use of the tags <PRE> and role of web servers in it. The different tools
<DIV>. and technologies that are available for
• chooses the tag for moving objects/ developing websites are introduced here. The
contents in a document. concept of dynamic web pages and an
• uses the <FONT> tag to format the text
content effectively. overview of the scripting languages used to
• utilises the facility of comments in an make web pages dynamic are also discussed.
HTML document. Web pages are developed with the help of a
• inserts images into HTML document language called Hyper Text Markup Language
using <IMG> tag.
81
Computer Applications (Commerce) - XII
(HTML). HTML is also known as the language of the Internet. HTML tells the
browser how to display the contents on a browser window. In this chapter, we will
also familiarise ourselves with the fundamentals of creating web pages using HTML.
4.1 Communication on the web
We have learned the actions that occur when a web browser (client) tries to access a
website from the Internet in Chapter 9 of Class XI. First, the URL (Uniform
Resource Locator) is sent to a Domain Name System (DNS) server to obtain its
corresponding IP (Internet Protocol) address and then the browser connects to
this server using the IP address. The web server software installed in the server
computer processes this request and the web page to be displayed is then sent to
the client. The client browser formats and displays this web page.
In order to communicate on the web, computers/devices need to understand each
other. This is made possible by making all devices follow the same protocol, namely
the Transmission Control Protocol/Internet Protocol (TCP/IP). We have discussed
TCP/IP protocol and its working in detail in Chapter 8, Computer Networks of
Class XI. The data to be sent is broken down into small data packets along with the
address of the recipient computer by the TCP protocol. The devices called routers,
route and transport these data packets to their destination computers using Internet
Protocol. Figure 4.1 shows the route of a data packet from a sender to a recipient.
STEP 2: The
STEP 3: TCP
packets travel
reassembles the
from router to
data packets
STEP 1: router over
back to original
TCP breaks the Internet
form
the data into according to
packets the IP
In the Internet, there are several types of communication like, accessing websites,
sending e-mails, etc. We have already learned in Chapter 9, Internet of Class XI that
websites are accessed using HTTP (Hyper Text Transfer Protocol) and e-mail
82
4. Web Technology
communication happens using SMTP (Simple Mail Transfer Protocol). Both these
protocols work on top of lower level protocol called Internet Protocol. Internet
Protocol provides the basics of communication over Internet. The use of a single
protocol - Internet Protocol - for all communication over the Internet has several
advantages. The routers need not be programmed separately to handle different
types of data. They do not need to know about the data they are transporting and
are concerned only about the address to which the packet is to be delivered. This
openness of the data part of the packet gives the freedom to design new protocols
for the Internet. It is this openness and flexibility of TCP/IP that led to the
development of protocols for social media websites to handle messages, content
websites to handle video and audio, banking websites to handle money transfer
securely, etc. This turned out to be a deciding factor for the economic success of
the Internet.
Communication on the web can be categorised as (i) client (browser) to web server
and (ii) web server to web server communication. Authentication and security are
essential for communication over the Internet. Authentication on the web is the
process of determining whether a computer/server is the computer that it claims
to be. Security should be provided to communication over Internet so that the
messages are not intercepted and modified by hackers.
4.1.1 Client to web server communication
Client to web server communication does not usually require authentication. But in
the case of web based banking applications/e-mail services, user names and
passwords are required to be sent to the server. This information cannot be sent to
the server in plain text due to security reasons. The hackers may steal usernames
and passwords, if it is communicated and shared as plain text. In such cases we use
HTTPS (Hyper Text Transfer Protocol Secure) technology to encrypt the username
and password, and then send it to the server. HTTPS works using Secure Sockets
Layer (SSL) which provides a standard security technology for establishing an
encrypted connection between computers on Internet. SSL provides security
capabilities to HTTP. The SSL protocol not only ensures privacy, but also ensures
that no other website can impersonate the user's login account nor alter the
information sent.
When the browser requests for a secure web page, the server first returns its SSL
certificate. The browser then verifies whether this certificate is valid by checking it
with the corresponding certification authority. A certification authority certifies
whether an SSL certificate given to it is a valid one. This is an assurance that the
particular website is of the organisation it claims to be. Verisign Inc. is a certification
83
Computer Applications (Commerce) - XII
01010010110 01010010110
Fig. 4.2(a) : Client - server authentication process Fig. 4.2(b): https authentication of SBI
website
4.1.2 Web server to web server communication
Web server to web server communication also may be required in certain web
applications. For example, the web server of an online shopping website (seller/
merchant on Internet) needs to send confidential information to a bank web server
and vice versa. In such cases the web servers of the merchant and the bank are to be
authenticated. Digital certificates help to verify whether the data received is from
Merchant's
web server
Payment
gateway
84
4. Web Technology
the actual server itself. Once the servers are authenticated, the servers communicate
using encrypted data. Payment gateway is a server that acts as a bridge between
merchant server and bank server and transfers money in an encrypted format
whenever an online payment/money transfer is made. This process is shown in
Figure 4.3.
4.2 Web server technologies
Let us see what happens internally when we visit the website www.dhsekerala.gov.in,
the official website of the Directorate of Higher Secondary Education (DHSE).
At first, the home page (the first page displayed when a website will be accessed) of
the website will be transferred to our computer (client) from the web server of
DHSE. The client is usually a computer or a mobile device which has a browser
software that requests for web pages. The web server uses the web server software
to store the pages of the websites and delivers it on request from the client. In the
following sections, we will discuss the features of a web server and the requirements
for setting up a web server.
4.2.1 Web server
The term web server is often used for referring to the server computer that hosts
websites. It is also used to refer to a web server software that is installed in a server
computer in order to make it a web server. In this section we will discuss the features
of a web server computer and a web server software.
A web server enables us to deliver web
pages or services like e-mail, blog, etc.
to users on the Internet. A web server
consists of a server computer that runs
a server operating system and a web
server software installed on it for
providing services like www, e-mail,
etc. over the Internet.
A web server is a powerful computer
Fig. 4.4 : A data center
which is always switched on and
connected to a high bandwidth Internet connection. This will facilitate Internet users
around the world to access the websites and services hosted by it at any point of
time. Depending on the requirements, a web server can have single or multiple
processors, fast access RAM, high performance hard disks, Ethernet cards that
supports fast communication, etc. To ensure faster Internet connectivity and
redundant power supply, a web server is usually installed in a data center.
85
Computer Applications (Commerce) - XII
86
4. Web Technology
87
Computer Applications (Commerce) - XII
88
4. Web Technology
This local DNS server contains a list of domain names and their IP addresses which
the users in the organisation regularly access. This list can be updated periodically
to include new domain names. Whenever a computer in the intranet tries to access
a website in the Internet, it first searches for the domain name in the local DNS
server and finds the IP address. This speeds up the Internet access in the organisation.
Only if the domain name is not found in the local DNS server, it searches the DNS
of ISP.
Instead of directing the computer to search for IP address in the ISP's
DNS server, we can direct it to search the public DNS operated by
Google. Google Public DNS is a free Domain Name System (DNS)
resolution service that can be used as an alternative to our current DNS
provider. The IP addresses for Google's public DNS are 8.8.8.8 and 8.8.4.4. We can
configure our network settings to direct to Google's public DNS using either of the IP
addresses.
There are many web designing softwares available. You can also employ the features
available in any of the web designing tools that helps you to create a web page with
the ease of preparing a document in a word processor. These software also provide
features to design web pages and link them together to form a website. Facilities to
transfer files to the server using FTP protocol is also built into such software. Popular
web designing softwares are Bluefish, Bootstrap, Adobe Dreamweaver, Microsoft
Expression Web, etc. Figure 4.8 shows the Integrated Development Environment
(IDE) of popular web designing softwares.
Bluefish Dreamweaver
Fig. 4.8 : IDE of web designing software
You have already learned the basics of creating web pages in high school classes.
HTML consists of tags and its attributes used to format web pages. In this chapter
we will also get familiar with the different HTML tags and attributes.
4.4 Static and dynamic web pages
You might have noticed that the web pages in the website of some small business/
organisations, school website, etc. remain the same whenever you visit it. These
websites are called static websites. There are some other websites like the website
that displays your mark in SSLC or Higher Secondary Examination (HSE), that
changes when different register numbers are given to them. They are called dynamic
web pages.
Static web pages are web pages that remain the same all the time until their code is
changed manually. Initially, web pages were created with HTML only and such web
pages are static web pages. Later, the emergence of scripting languages like JavaScript,
VBScript, etc. brought animations into the web page. The colour and style of a
portion of the web page changes when the mouse is kept over it, images are loaded
90
4. Web Technology
and displayed one after another in a sequence - all these are designed using scripting
languages. The web pages that contain all these features are also classified as static
web pages.
Web Application
Server Server
t
ues
P req
Client HTT (JRL
)
Computer
HTTP r
espons
e
Requested
web page Database
4.5 Scripts
Scripts are program codes written inside HTML pages. They are written using a
text editor like notepad. Scripting languages like JavaScript, VB script, PHP, Perl,
etc. are used to create dynamic web pages.
Traditional programming languages are set of instructions carried out by the
computer hardware with the help of an operating system, whereas scripting languages
are interpreted by a web browser or by a web server software. Today most of the
standalone programs are being replaced by web based programs. Earlier, the
software used in banks were installed in the branches of the bank itself. Almost all
banks have their banking software available on the bank's web server and the bank
employees access them using the Internet. Web based software like banking software,
higher secondary admission software, etc. use scripting languages for their
development.
In an HTML page, a script is written inside <SCRIPT> and </SCRIPT> tags.
<SCRIPT> is used to embed or refer to an executable script within an HTML
document. It has the attributes Type and Src. Type attribute is used to identify
the scripting language code embedded within the script tag. We will see more
about HTML tags and attributes later in this chapter.
<SCRIPT Type="text/javascript"> is used to insert JavaScript code in the
HTML code.
Scripts can be written as an external file and can be linked to an HTML file. Src
attribute is used to specify the URL of an external file containing scripting code to
be linked to a web page.
<SCRIPT Type="text/javascript" Src="scriptcode.js"> is used to
insert JavaScript code inside the file scriptcode.js into an HTML file.
4.5.1 Types of scripting languages
Let us consider a login page of a website in the Internet. Usually the page will
prompt the user to enter the user name and password. User will click the 'Login'
button after entering the user name and password. What will happen if the user
clicks the 'Login' button without entering the user name? Naturally, the computer
will tell the user that he/she has not entered the user name. Remember that the web
page we are viewing is controlled by two computers - the client computer where
the web page is viewed and the server computer where the web page comes from.
Where will we check whether the user has entered a user name or not - in the client
computer or in the server computer? The server computer is thousand times busier
92
4. Web Technology
than the client computer, because a large number of people may be visiting the
same web site and the server is the only one computer to handle all those requests.
Therefore, all the tasks that can be done at the client side must be done at the client
side itself. This will reduce the workload of the server.
It should also be noted that, if this type of checking is done at the server, when the
user clicks the 'Login' button, the entered data has to be sent to the server from the
client through the Internet. The data has to travel a long distance through the Internet
to reach the server. When the data reaches the server, it will be placed in a queue
because a large number of clients may be sending the same request to the server.
The sent data will wait in the queue till it gets the chance to be processed by the
server. The server will check whether any user name or password is entered by the
client or not. If not, it will send a message back to the client specifying that the user
name is not given as displayed in Figure 4.10. Again, the message has to travel a
long distance back from the
server to the client through the
Internet. In short, if the user
clicks the submit button, without
entering the user name, he/she
has to wait a few seconds till he/
she gets the message that he/she
has not given the user name.
Besides this, the data has to travel
from client to server and back
from server to client, which
Fig. 4.10 : Response from the server
unnecessarily makes network
traffic busy.
If this checking is done at the client side itself, when the user clicks the submit
button, the script code in the client side can check whether the user has given some
entry as the user name and password. If not, a message can be displayed. During
this process, the data does not travel across the Internet to the server, nor does it
disturb the server for this simple task. When the user clicks the submit button, the
user gets the message that he has not given the user name, within a second as shown
in Figure 4.11. It also does not engage network resources unnecessarily.
Now let us consider another situation. Suppose a user enters a wrong user name
and password. The client computer may be able to check whether there is any entry
with such a user name and password. However it cannot check whether the user
name and password are correct or not. This is because only the server computer
has the details of all user names and corresponding passwords. Therefore, whether
93
Computer Applications (Commerce) - XII
94
4. Web Technology
that particular student. This is the same for each student who has appeared for the
SSLC examination. We know that it is not practical to design a web page for each
of the several lakhs of students who have written the SSLC examination. If so, how
is this done? The results of these several lakhs of students are stored in a database
in the web server. Server side scripts are used to access the result of a particular
student from the database whose register number is entered by the user. The server
side script then uses this result to create
a simple HTML web page. This web page
is then sent to the client browser and the
browser displays it. This way the server
side script creates a web page for each
student who has appeared for SSLC
examination as shown in Figure 4.12. The
rapid growth of web based applications
has increased the use of server side
scripting. Fig. 4.12 : Working of server side scripts
Server side scripting is a technology in which the web page containing server side
scripts requested by the user is executed in the server and the result, which is an
HTML code, is sent to the client browser. Server side scripting creates web pages
dynamically. Since the scripts are executed at the server, the type and version of the
browser or operating system on the client's computer does not affect its execution.
Since the scripts are executed on the server, it consumes server resources. Popular
server side scripting languages are Perl, PHP, ASP, JSP, etc.
A comparison of the classifications of scripting languages is given in Table 4.3.
Client side scripting Server side scripting
Script is copied to the client browser Script remains in the web server
Script is executed in the client browser Script is executed in the web server and
the web page produced is returned to the
client browser
Client side scripts are mainly used for Server side scripts are usually used to
validation of data at the client. connect to databases and return data
from the web server
Users can block client side scripting Server side scripting cannot be blocked
by a user
The type and version of the web browser The features of the web browser does
affects the working of a client side script not affect the working of server side
script
Table 4.3 : Comparison of client side and server side scripting
95
Computer Applications (Commerce) - XII
We have seen that the client side scripts are mainly used for validations
at the user's browser and that it reduces the load on the server and
network traffic. Therefore, the entire validation checking scripts are
moved to the client side. Now the data sent to the web server is free
from all errors and can be directly saved to the database. But if the client's browser
does not support scripts or the user has turned off the scripting in the browser for
security reasons, the data will be sent to the server without validation. This causes
invalid data to be stored in the database. In order to protect the validity of the data
saved in the database, it is better to have a validation check at the server side also.
The popularity of JavaScript has led to more developments in client side scripting.
While applying online for Higher Secondary Plus One admissions, immediately
after entering your SSLC register number, you might have noticed that your name,
date of birth and other details appear in the text boxes below. This is done without
reloading the entire web page. The data is taken from the server and filled in the
text boxes without refreshing the web page. Ajax is the technology used here. Ajax
improves the interactivity of the browsers. Ajax is Asynchronous JavaScript and
Extensible Markup Language (XML). XML is a markup language which helps users
to create new tags. After implementing Ajax on a website, it does not require the
entire page to be reloaded for displaying dynamic content on web pages. Ajax
96
4. Web Technology
allows web pages to be updated by exchanging small amounts of data between the
client and the server behind the scenes. This means that it is possible to update
parts of a web page, without reloading the entire web page. However, since Ajax
relies more on JavaScript, if the browser is not capable of handling JavaScript or
the user has turned off JavaScript functionality in the browser, the Ajax application
will not work.
B. VB Script
VBScript is a scripting language developed by Microsoft Corporation based on
the popular programming language Visual Basic. VBScript was developed to use
either as a client side scripting language for the Microsoft Internet Explorer or as a
server side scripting language with the Microsoft Internet Information Server (IIS).
Unfortunately, browsers other than Internet Explorer may not be able to correctly
interpret and display the VBScript code. Therefore, it is less popular as a client side
scripting tool. Since Windows operating system is popular as a server based
operating system, VBScript is popular for server side scripting. With the introduction
of .NET framework - a library of usable program code, Microsoft has taken the
decision to incorporate VBScript as a part of ASP.NET in .NET framework.
C. PHP
PHP stands for 'PHP: Hypertext Preprocessor'. PHP is an open
source general-purpose scripting language that is suited for web
development and can be embedded into HTML code. It is a server
side scripting tool and its code is similar to Java, C and Perl. The
main objective of PHP is to develop dynamic web pages at ease.
PHP was originally created by Rasmus Lerdorf (Figure 4.14) in
1994 but it is now developed by The PHP Group. The web page
Fig. 4.14: Rasmus
files that contain PHP code have the extension .php. Lerdorf (1968 - )
PHP code is inserted inside HTML code and when the user requests for a PHP
web page, it is interpreted and executed on the web server. To process the PHP
code on the web server, a PHP interpreter has to be installed on the web server.
After execution of the PHP code in the web server, an HTML page is created,
which is sent to the client browser. One of the strongest and most significant features
in PHP is its support for database programming. The most common database
used with PHP is MySQL. PHP interpreter is available for all operating systems.
Linux platforms commonly use LAMP (Linux, Apache, MySQL and PHP) server
software which is freely downloadable. LAMP uses Linux as the server operating
system, Apache as the web server, MySQL as the database and PHP for server side
scripting. Windows operating systems use WAMP server software which is also
available for free download.
97
Computer Applications (Commerce) - XII
of a style, modifies the way the tags are presented in all the web pages of the website.
Since CSS styles are written in a common place, it separates CSS and HTML, which
makes it easy for maintenance. Moreover, the tags in web pages are well organised
with the style specifications and therefore it is easy to understand. This also reduces
the size of the web page thereby providing faster downloads for web pages.
CSS allows adapting the presentation of a web page to devices with different screen
sizes such as desktop monitors, tablets or mobiles. It is considered that CSS along
with JavaScript will be used in the next version of HTML called HTML5, to bring
animations and interaction to web pages.
Know your progress
1. The web pages that remain the same until their code is changed
manually are called ______.
2. Name two technologies that can be used to develop dynamic
web pages.
3. The tag used to embed scripts is ______.
4. Write any one of the uses of client side scripting.
5. A JavaScript file has the extension ______.
6. What is the advantage of using Ajax?
7. Classify the following scripting languages into client side and
server side.
Javascript, PHP, ASP, VBScript
8. .asp files are compiled using the web server software ______.
9. List the different ways of implementing CSS.
Versions in HTML: HTML was created by Tim Berners Lee in late 1991
but "HTML 2.0" was the first standard HTML specification which was
published in 1995. HTML 4.01 was a major version of HTML and it was
published in late 1999. The latest version, HTML 5 was released in 2012.
But it is still being modified for adding more multimedia integration.
100
4. Web Technology
They are:
<HTML> </HTML>
<HEAD> </HEAD>
<TITLE> </TITLE>
<BODY> </BODY>
103
Computer Applications (Commerce) - XII
Bgcolor
This attribute specifies a colour for the background of the document body. For
example, <BODY Bgcolor = "grey"> will display the background in grey
colour.
The value of Bgcolor attribute can be given in two ways.
• Color_name - specifies the background colour with a colour name (like "red",
"grey" etc.)
• Hex_number - specifies the background colour with a hexadecimal code (like
"#ff6080", "#303030" etc.). Each hexadecimal code will be preceded with a
hash sign #.
The six digit number and letter
combinations represent colours by Colour Colour
Colour
Name HEX
giving their RGB (Red, Green, Blue)
value. Of the six digits, the first two Black #000000
digits represent the amount of red, the Red #FF0000
second two digits represent the amount
of green, and the last two digits Green #00FF00
represent the amount of blue as a Blue #0000FF
hexadecimal value in the range 00 - FF.
For example, #000000 is black, Yellow #FFFF00
#FF0000 is bright red, #00FF00 is Aqua #00FFFF
bright green, and #FFFFFF is white
(fully saturated with all the three Grey #C0C0C0
colours). We can try various colour White #FFFFFF
combinations according to our choice
Table 4.4: List of colours with their
of hex number. Table 4.4 shows a few Name and Hexadecimal value
colours with their Names and Hex
values.
Text
This attribute specifies the colour of the text content in the page. By default the
browser displays the text in black colour on a white/grey background. We have
already discussed how to change the background colour using Bgcolor attribute.
Simillarly the colour of the text can be changed using the attribute Text. For
example, <BODY Text = "yellow"> shows the text in yellow colour. Like
Bgcolor, the value of Text attribute can be given as colour name or hexadecimal
code. For example, Text = "Blue" or Text = "#00FFDD" etc.
105
Computer Applications (Commerce) - XII
106
4. Web Technology
to <H6>. Here <H1> creates the biggest text and <H6> the smallest. While displaying
any heading, browser adds one line before and one line after that heading. The main
attribute of this tag is Align and the possible values are,
Left : Text is aligned to the left margin.
Right : Text is aligned to the right margin.
Center : Text is aligned to the centre of the page.
Example 4.4 shows different heading types and alignments and Figure 4.20 shows
the corresponding web page.
Example 4.4: To illustrate different heading styles
<HTML>
<HEAD>
<TITLE> Heading Tags </TITLE>
</HEAD >
<BODY Bgcolor= "#FFEFD5">
<H1 Align= "left"> This is a Heading type 1 </H1>
<H2 Align= "center"> This is a Heading type 2 </H2>
<H3 Align= "right"> This is a Heading type 3 </H3>
<H4> This is a Heading type 4 </H4>
<H5> This is a Heading type 5 </H5>
<H6> This is a Heading type 6 </H6>
</BODY>
</HTML>
108
4. Web Technology
109
Computer Applications (Commerce) - XII
In Example 4.5, we can see that the source code contains three lines in the first
paragraph and two lines in the second paragraph with extra spaces. But the web
page of this code shown in Figure 4.21 gives a single line for the first two paragraphs.
That is, the browser will remove extra spaces and extra lines when the page is
displayed. Note that the second paragraph is right aligned and the third paragraph
is aligned as justified. Any number of spaces and any number of lines count as only
one space. Therefore with HTML, we cannot change the output by adding extra
spaces or extra lines in the HTML code. But this is possible in HTML. Now let us
discuss how an extra line can be added to the text content using <BR> tag. Note
that the web pages obtained in large or small screens and resized windows may not
match with the one given in Figure 4.21.
4.10.3 <BR> tag - Inserting line break
The purpose of BR element is that it creates a line break within a block of text in a
web page. The <BR> tag is used to break the current line of text and continue from
the beginning of the next line. The <BR> tag is an empty tag, which means that it
has no ending (closing) tag.
The HTML code in Example 4.6 displays our National Pledge and Figure 4.22
shows the resultant page in which we can see the effect of <BR> tag and the difference
between <P> tag and <BR> tag.
Example 4.6: To show the National Pledge with line breaks
<HTML>
<HEAD>
<TITLE> Line Breaks </TITLE>
</HEAD >
<BODY Bgcolor = "#FFEFC5">
<H1 Align = "center"> Our National Pledge </H1>
<P>India is my country and all Indians
110
4. Web Technology
Referring to Example 4.6 and Figure 4.24, fill in Table 4.5 with
appropriate points to distinguish between <P> tag and <BR> tag.
Let us do
<P> tag <BR> tag
Breaks the current line and continues to
the next line.
Container tag
Table 4.5: <P> tag Vs <BR> tag
4.10.4 <HR> tag - creating horizontal line
The <HR> tag produces a horizontal line (rule) spread across the width of the browser
window. We can change the size (thickness) and width (length) of the line using its
attributes Size and Width. The value of Size is given in pixels; and the value of
111
Computer Applications (Commerce) - XII
The code given in Example 4.8 illustrates the application of these tags. For instance,
let us quote the words of Mahatma Gandhi. Figure 4.24 shows the resultant web
page of this code.
Example 4.8: To illustrate the text formatting tags
<HTML>
<HEAD>
<TITLE> Formatting Tags </TITLE>
</HEAD>
<BODY>
<P>
<CENTER><B>Mahatma Gandhi </B>is the <I> <U> Father of
our Nation.</U> </I> </CENTER>
Every student must learn the inspiring words (quotes)
of Gandhiji. It will inspire everyone. Let us have a
look at it.
</P><BR>
<SMALL> The weak can never forgive </SMALL>.
<BIG> Forgiveness is an attribute of the strong</BIG>
<BR> Live as if you were to die tomorrow.
<STRONG> Learn as if you were to live forever.</STRONG>
</BODY>
</HTML>
such notations in HTML? We can see that the figures are written in subscript form.
The <SUB> tag is used to create subscripts in a web page. We can display the text
H2O with the code H<SUB>2</SUB>O.
Similarly, the superscripts as in algebraic expressions like (a+b)2 = a2 + 2ab+ b2 can
be represented by the tag <SUP>. The above expression can be written as
(a+b)<SUP>2</SUP> = a<SUP>2</SUP> + 2ab + b<SUP>2</SUP>
<BLOCKQUOTE> and <Q> tags - Indenting a quotation
The <BLOCKQUOTE> tag is used to indent the content enclosed in these tags. The
HTML <Q> tag (Quote tag) is used to indicate the text enclosed in double quotation
marks with an indent. This tag is intended for short quotations that do not require
paragraph breaks, whereas <BLOCKQUOTE> is used for long quotations.
The illustration of the tags mentioned above is done in Example 4.9. Let us remember
that World Environment Day is celebrated on June 5. Let us create thoughts for
this day and create a web page using these tags. The corresponding web page is
shown in Figure 4.25.
Example 4.9: To illustrate <SUP>, <BLOCKQUOTE> and <Q> tags
<HTML>
<HEAD>
<TITLE> BlockQuote and Q tags </TITLE>
</HEAD>
<BODY Bgcolor= "#98FB98" Text= "#008000">
Every year we celebrate World Environment Day on 5<SUP>
th</SUP> June. Let us have a message to all on this
occassion.
<BLOCKQUOTE> <B>June 5<SUP>th</SUP> is World Environment
Day. </B>
Mother nature too needs care and protection. Show her
your care by caring for her trees. Love trees and love
nature. And work for a greener environment because
generations have to come... The future depends on us...
</BLOCKQUOTE>
<Q>Keep your world clean and green. Save trees, Save the
environment!!
</Q>
</BODY>
</HTML>
115
Computer Applications (Commerce) - XII
Example 4.10 and Figure 4.26 give us an idea of this tag. Let us create a web page
that contains some slogans on World Environment Day.
Example 4.10: To illustrate <PRE> tag
<HTML>
<HEAD>
<TITLE> Pre Formatting tags </TITLE>
</HEAD>
<BODY Bgcolor = "#eee8aa" Text = "#b22222">
<PRE>
Don't Pollute Water,
Don't Pollute Air,
Don't Pollute Environment,
And Don't Pollute Yourself,
Celebrate World Environment Day ...
</PRE>
</BODY>
</HTML>
The web page in Figure
4.26 shows that anything
written within <PRE> and
< / P R E > tags will be
displayed as it is in the
HTML document.
Fig. 4.26: Illustration of <PRE> tag
4.10.8 <ADDRESS> - Displaying the address
The <ADDRESS> tag defines the contact information for the author/owner of a
document or an article. The content of this tag can include name, phone numbers,
PIN numbers, e-mail addresses, etc. Most of the browsers display the texts in italics.
The code given in Example 4.11 illustrates the <ADDRESS> tag. The appearance of
this page is shown in Figure 4.27.
Example 4.11: To illustrate <ADDRESS> tag
<HTML>
<HEAD>
<TITLE> Address tag </TITLE>
</HEAD>
<BODY Bgcolor= "#DDA0DD">
117
Computer Applications (Commerce) - XII
118
4. Web Technology
• Scrolldelay: This specifies time delay between each jump. This will have
value in seconds like 10, 15, etc.
• Scrollamount: This specifies the speed of the marquee text.
• Loop: This specifies how many times the marquee element should scroll on
the screen. The default value is Infinte, which means that the marquee scrolls
endlessly.
• Bgcolor: This specifies background colour in terms of colour name or colour
hex value.
• Hspace: This specifies horizontal space around the marquee. This can be a
value in pixels or percentage value.
• Vspace: This specifies vertical space around the marquee. This can be a value
in pixels or percentage value.
The code given in Example 4.12 illustrates the use of <MARQUEE> tag and Figure
4.28 shows the corresponding web page.
Example 4.12: To illustrate <MARQUEE> tag
<HTML>
<HEAD>
<TITLE> HTML marquee Tag </TITLE>
</HEAD>
<BODY>
<MARQUEE Width= "50%"> This will take only 50% width of
Browser Window</MARQUEE>
<MARQUEE Height= "100" Hspace= "100" Bgcolor= "#44BB22"
Direction= "up"> Scrolling up </MARQUEE>
<MARQUEE Height= "20" Vspace= "30" Bgcolor= "#FFBB00"
Direction= "right"> This will scroll from left to right
</MARQUEE>
</BODY>
</HTML>
The first marquee starts from
the middle and scrolls
towards the left of the
window since the width is
50%. The second marquee is
in the green coloured portion
and 100 pixels height is
provided for scrolling. The Fig. 4.28 : Marquee tag with different attributes
119
Computer Applications (Commerce) - XII
scroll area is set 100 pixels horizontally away from the left margin. The third marquee
is filled with the background colour "#FFBB00" and placed 30 pixels vertically
below the previous marquee. The scroll window has a height of 40 pixels and it
scrolls from left to right. Instead of words or phrases, we can also use images as the
marquee content.
4.10.10 <DIV> - Formatting a block of text
The <DIV> tag is used for defining a section or a block in the document. With the
<DIV> tag, we can group large sections of HTML documents together and format
them. This section may contain paragraphs, tables, etc. Most browsers place a line
break before and after <DIV> elements. The attributes of <DIV> tag are:
Align : sets the horizontal alignment with values left, right, center, and
justify.
Id : assigns a unique identifier for the tag.
Style : indicates how to render the content in terms of colour, font, etc.
In Example 4.13, we use <DIV> tag to apply Align and Style. Figure 4.29 shows
the resultant web page.
Example 4.13: To illustrate <DIV> tag
<HTML>
<HEAD>
<TITLE> DIV Tag </TITLE>
</HEAD >
<BODY Bgcolor= "#ddffff">
<H2 Align= "center"> Success Story </H2>
<DIV Align= "Center" Style= "Color:#0000FF"> One day a
partially deaf four - year old child came home with a
note in his pocket from his teacher, "Your Tommy is too
stupid to learn, get him out of the school."
<P>His mother read the note and answered, "My Tommy is
not too stupid to learn, I will teach him myself." And
that Tommy grew up to be the great Thomas Alwa Edison.
</P> He had only three months of formal schooling.
</DIV>
All success stories are stories of great failures.
You learn from your failure and move forward.
</BODY>
</HTML>
120
4. Web Technology
121
Computer Applications (Commerce) - XII
122
4. Web Technology
Comments are not displayed in the browser window. HTML comments are placed
within <!-- --> tag. So any content placed within <!-- --> tag will be
treated as a comment and will be completely ignored by the browser. In Geany
editor the comments are displayed in red colour. The code in Example 4.15 illustrates
the use of comments and Figure 4.31 shows the resultant message.
Example 4.15: To illustrate the use of comment tag
<HTML>
<HEAD> <!-- Document Header Starts -->
<TITLE> Comment Tags </TITLE>
</HEAD>
<BODY Bgcolor= "#D8D8D8">
<!-- This is a comment -->
<p>The paragraph starts here. Comment statements are
not displayed in the browser window</p>
<!-- Comments are not displayed in the browser -->
</BODY>
</HTML>
123
Computer Applications (Commerce) - XII
124
4. Web Technology
125
Computer Applications (Commerce) - XII
126
4. Web Technology
127
Computer Applications (Commerce) - XII
Let us conclude
128
4. Web Technology
Let us practice
1. Wrtie an HTML code for a web page of Kerala with the following details and
features:
• A heading followed by a paragraph of 5 sentences about Kerala using
text formatting tags and attributes.
• Background of the page needs an image of a scenary.
2. Wrtie an HTML code for a web page for your school with the following details
and features:
• A heading followed by a paragraph of 3 sentences about the district using
text formatting tags and attributes.
• Provide a colour to the background of the page.
• Include an image of the school.
3. Wrtie an HTML code for a web page for your school with the following details
and features:
• A heading followed by a paragraph of 3 sentences about the district using
text formatting tags and attributes.
• Give the postal address of the school.
• Include a marquee that "Admission for the new accademic year commences
on 10th May"
4. Wrtie an HTML code for a web page to show the lyrics of our National Anthem
with the following details and features:
• A heading with a different font characteristics.
• An image of our national flag
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
Let us assess 123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
1. What is the role of routers in transporting data over the Internet?
2. The social media websites developed their own protocol for communicating
over the Internet. How is this possible when Internet uses TCP/IP protocol?
3. The user name and password of an e-mail account has to be sent securely over
the Internet.
a. Name the technology used to send the data to the server.
b. How does this technology support secure data communication?
4. What is the role of payment gateway in online purchases?
5. ABC Engineering College has about 1000 computers connected to the Internet,
in its campus. What is the advantage of having a local DNS server in the college's
intranet?
129
Computer Applications (Commerce) - XII
6. Write an example of a web server operating system and a web server package.
7. What is the use of software ports in a web server?
8. The port used for HTTP is ________.
9. Suppose you are browsing the website www.prdkerala.org. Explain how the
DNS resolves the IP address.
10. What are scripts? Explain the different scripting languages.
11. Consider the home page of your school website and the web page that displays
the results of class XI examinations.
a. Compare the difference between the two web pages based on their creation.
b. Write the technologies that can be used for developing these web pages.
12. a. The file name extension for a JavaScript file is _________.
b. Write two popular uses of JavaScript in a web page.
13. What is Ajax? What is its use?
14. Your friend Ravi wishes to create a website that displays the marks of the
students in your class in each examination.
a. Suggest a technology to implement this.
b. Justify your suggestion.
15. Consider that Manoj is developing a website using PHP that uses a database in
MySQL. What are the requirements to implement this if he is using Linux web
hosting?
16. "Almost all websites today use CSS for its development." What are the
advantages of using CSS in web sites?
17. Who developed HTML?
18. In HTML, there are mainly two sections. Can you name them?
19. If you analyse web pages you can see different colours for links, visited links,
background etc. Expalin how this can be done in HTML, with examples.
20. Compare container and empty tags in HTML with examples.
21. The default colour of the attribute Alink is __________.
22. The default color of the attribute Vlink is __________.
23. Classify the following HTML related words:
BR, IMG, ALIGN, FONT, FACE
24. Name the tag which has Noshade attribute.
25. Write the main attribute of <IMG> tag to insert an image file in the webpage.
26. Mention the purpose of Alt atribute in <IMG> tag.
27. The default alignment of an image obtained by using <IMG> tag is ________.
28. List the main attributes of <FONT> tag.
130
Web Designing using
5 HTML
I
n the previous chapter, we studied the basic
Significant Learning Outcomes
tags of HTML. We have also learnt to create
After the completion of this chapter, the some simple web pages using those tags and
learner their attributes. But we are familiar with websites
• uses different list tags to present the that provide much more facilities and utilities.
content effectively in web pages.
There are websites that contain different types
• identifies the relevance of hyper
linking and uses <A> tag for different of lists. Linking between web pages is the
types of linking. backbone of World Wide Web. The different
• provides audio and video in web types of linking are discussed in this chapter.
pages with the help of <EMBED> tag. You might have come across certain information
• produces inline sounds and videos
in tabular form. Sometimes you see more web
in web pages.
• lists and explains the tag and pages in the same browser window. We are also
attributes for creating a table. familiar with websites through which we submit
• uses the tags associated with the register number to obtain the mark list of
<TABLE> tag to design tables with examinations, apply for admission and
different characteristics.
scholarships, pay the bills of electricity and
• constructs different tables using the
tags and attributes. water consumption etc. How can we create
• identifies the importance of frames tables in web pages to present information? Can
in the web page. we place more than one web page in a single
• creates frames using appropriate browser window? If yes, how? How are web
tags to display different web pages
in the same browser window.
pages created to accept data from the user to
• identifies the concept of Forms in the provide information? HTML provides all these
web page. facilities for web developers. In this chapter, we
• explains various components in a discuss the HTML tags required to answer all
Form and creates them using proper these questions.
tags and attributes.
• designs web pages with tables,
frames and forms.
Computer Applications (Commerce) - XII
132
5. Web Designing using HTML
133
Computer Applications (Commerce) - XII
items. We can customise the numbering system used in ordered list by using the
Type attribute, which can set with the values as detailed below:
1 Default numbering scheme (1, 2, 3, ...)
A Upper case letters (A, B, C, ...)
a Lower case letters (a, b, c, ...)
I Large roman numerals (I, II, III, ...)
i Small roman numerals (i, ii, iii, ...)
An ordered list, by default, starts with the first number in the series used in the list.
That is, the starting number will be any one from 1, A, a, I and i. If we want to start
with any other number in the series, then the Start attribute of <OL> tag enables
us to change the beginning value. To start numbering a list at 5, for example, we
may write: <OL Start= "5">. Thus, the numbering starts from 5 and then proceeds
with 6, 7, 8, ... and so on.
The Start attribute sets the starting value of the item (it must be an integer) and
the Type attribute sets the numbering style. For example, the following ordered
list starts numbering from V and continues with VI, VII, ... and so on. The output
of this code is shown in Figure 5.4.
<BODY Bgcolor ="#DDA0DD">
<H4 Align="center">Ordered List with Type attribute</H4>
<OL Type= "I" Start= "5">
<LI> Registers </LI>
<LI> Cache </LI>
<LI> RAM </LI>
<LI> Hard Disk </LI>
</OL>
</BODY>
136
5. Web Designing using HTML
137
Computer Applications (Commerce) - XII
138
5. Web Designing using HTML
139
Computer Applications (Commerce) - XII
140
5. Web Designing using HTML
141
Computer Applications (Commerce) - XII
142
5. Web Designing using HTML
144
5. Web Designing using HTML
145
Computer Applications (Commerce) - XII
Value Description
Hsides Display borders on the horizontal sides (top and bottom) only
lhs or rhs Display the border only the left side or the right side
Vsides Display borders on the vertical sides (right and left) only
box or border Display borders on all sides of the table (It is the default value)
Table 5.2: Values of Frame attribute
10. Rules: We can use the Rules attribute to control what rules (borders between
cells) are displayed in a table. Table 5.3 shows the values of Rules attribute.
Value Description
none Display no rules
cols Display rules between columns only
rows Display rules between rows only
groups Display rules between row groups and column groups only
all Rules will appear between all rows and columns
Table 5.3:Values of Rules attribute
Now let us discuss some other tags associated with <TABLE> tag.
5.4.2 <TR> tag
The rows in a table are created using <TR> tag. It is a container tag. The whole row
is enclosed within the tag pair <TR> and </TR>. A <TR> tag always comes inside
the <TABLE> tag. A row itself is a collection of cells. A cell is the smallest component
of a table. There are two types of cells - heading cells and data cells. As seen in
Table 5.1, the values given in red colour are of heading type. The values given in
blue are just data cells.
5.4.3 <TH> tag
<TH> tag is used to define heading cells. It is also a container tag. The heading data
should be enclosed between <TH> and </TH> tags. The heading cells are displayed
in bold face and in centred form. <TH> tag always comes inside the <TR> tag.
5.4.4 <TD> tag
<TD> tag is similar to <TH> tag and is used to display data cells. It is also a container
tag. The data is given in between <TD> and </TD> tags. Similar to <TH> tag,<TD>
tag is also placed within the <TR> tag.
The code given in Example 5.12 creates a simple table and Figure 5.14 shows the
resultant web page.
146
5. Web Designing using HTML
<TR>
<TH> Smokers </TH>
<TD> 412 </TD>
</TR>
<TR>
<TH> Pan users </TH>
<TD> 159 </TD>
</TR>
<TR>
<TH> Alcohol users </TH>
<TD> 219 </TD>
</TR>
<TR>
<TH> Other cases </TH>
<TD> 280 </TD>
</TR>
<TABLE>
<BODY>
<HTML>
In Example 5.13, we used <TH> tags within
all <TR> tag pairs, which make the first
column of the table similar to header column
as shown in Figure 5.15.
Fig. 5.15: Table using Cellspacing and
Attributes of <TR> tag Cellpadding
The characteristics of a row can be changed using the attributes of <TR> tag.
1. Align: This attribute specifies the horizontal alignment of the text in a cell in
that particular row. This can take the values left, right or center. The
default is left for data and center for headings (see Figure 5.15).
2. Valign: We can specify the vertical alignment of the content in a cell of any
row using Valign. The possible values are top, middle, bottom or baseline.
Baseline vertical alignment aligns the baseline of the text across the cells in the
row.
3. Bgcolor: This attribute gives background colour to a particular row. Usually
this helps in highlighting a row.
The following code segment is the modified part of the code given in Example
5.13. It modifies the third row of the table shown in Figure 5.15 with a background
colour, and horizontal and vertical alignments.
148
5. Web Designing using HTML
<BODY>
<TABLE Border= "1" Cellspacing= "3" Cellpadding= "5">
<TR>
<TH Colspan= "3"> No. of Registered Students </TH>
</TR>
<TR>
<TH Rowspan= "2"> Year </TH>
<TD> 2014 </TD> <TD> 75 </TD>
</TR>
<TR>
<TD> 2015 </TD> <TD> 88 </TD>
</TR>
</TABLE>
<BODY>
<HTML>
151
Computer Applications (Commerce) - XII
152
5. Web Designing using HTML
1. Src: As we have already discussed, Src specifies the URL of the document to
be loaded in the frame. For example, <FRAME Src = "school.html">
loads the page school.html in a particular frame.
2. Scrolling: When the content inside a frame exceeds the frame size, a scrollbar
appears depending upon the value of the Scrolling attribute. It can take
values Yes, No or Auto. Auto is the default value and it displays scroll bars if
the frame content exceeds the normal display area.
3. Noresize: It is used to prevent users from resizing the border of a specific
frame by dragging on it. Just giving Noresize prohibits resizing the frame
window. For example, <FRAME Src= "school.html" Noresize>.
4. Marginwidth and Marginheight: We can set horizontal and vertical margins
to the frame by using Marginwidth and Marginheight, respectively. The
values are given in pixels.
5. Name: It gives a name to a frame. This particular frame can be referenced
using this name later in the code.
The following code can create the frameset shown in Figure 5.20. It is assumed that
the three HTML pages sampleframe1.html, sampleframe2.html and sampleframe3.html
are already created as in Figure 5.20.
<HTML>
<HEAD> <TITLE> A simple Frameset </TITLE> </HEAD>
<FRAMESET Rows= "20%, 30%, 50%">
<FRAME Src= "sampleframe1.html">
<FRAME Src= "sampleframe2.html">
<FRAME Src= "sampleframe3.html">
</FRAMESET>
</HTML>
154
5. Web Designing using HTML
Now let us create a web page with two frames - one for showing the links for these
files and the other for opening the respective web pages. When a user clicks on any
one of the three links available in one frame, the associated file will open in the
other frame.
Once you have created the three files mentioned above, the two HTML codes
given in Example 5.16 can satisfy our need.
Example 5.16: To illustrate the concept of targeting frames
Save the following code in a file main.html
<HTML>
<HEAD> <TITLE> Left Frame </TITLE> </HEAD>
<BODY Bgcolor= "#00AFFF" Text= "#282D2F">
<H2> Select the option </H2>
<FONT Size= "5">
<A Href= "bio.html" Target="right_frame">Biography</A><BR>
<A Href= "poem.html" Target="right_frame">Poetry</A><BR>
<A Href= "fiction.html" Target="right_frame">Fiction</A>
</FONT>
</BODY>
</HTML>
Now create a file to store the following code:
<HTML>
<HEAD> <TITLE> Targeting Frames </TITLE> </HEAD>
<FRAMESET Cols= "200, *">
<FRAME Src= "main.html" Name= "left_frame">
<FRAME Name= "right_frame">
</FRAMESET>
</HTML>
When the above document is executed,
a web page with two frames will be
opened. The first column of the
browser window will show the
main.html and the second column will
be blank. Note that Src attribute is not
specified for that frame, but a name
right_frame is assigned. If the first
link (biography) is selected, the file
bio.html will be opened in the second
Fig. 5.21 : Web page with target frame
frame as shown in Figure 5.21. It is
155
5. Web Designing using HTML
2. The second row is left free. Now we will divide it into two frames vertically.
So, instead of a second <FRAME> tag, insert another opening <FRAMESET>
tag as shown below:
<FRAMESET Rows= "85, *">
<FRAME Src= "sampleframe1.html">
<FRAMESET Cols= "220, *">
</FRAMESET>
</FRAMESET>
This code will divide the second row into two columns. Now, we can add two
<FRAME> tags within the inner frameset and complete the HTML code as
given in Example 5.17. The resultant web page is shown in Figure 5.23. It is
assumed that the three HTML pages are already created as in Figure 5.23.
Example 5.17: To implement the concept of nested frameset
<HTML>
<HEAD>
<TITLE> nesting frames </TITLE>
</HEAD>
<FRAMESET Rows= "85, *">
<FRAME Src= "sampleframe1.html">
<FRAMESET Cols= "200, *">
<FRAME Src= "sampleframe2.html">
<FRAME Src= "sampleframe3.html">
</FRAMESET>
</FRAMESET>
</HTML>
5.5.5 <NOFRAMES> tag
Earlier browsers did not support frames. In
such a situation, the browser is expected to
respond to the user in some way or the other.
The tag pair <NOFRAMES> and </NOFRAMES>
is used to display some text content in the
window if the browser is unable to support
frames. The following code illustrates the use
of <NOFRAMES> tag.
Fig. 5.23: Nested framesets
<HTML>
<HEAD> <TITLE> A simple Frameset </TITLE>
</HEAD>
157
Computer Applications (Commerce) - XII
158
5. Web Designing using HTML
A common use for JavaScript (or any client side scripting language) is
to verify that users have filled in all the required fields in a Form and/
or to check whether the input data is valid or not, before the browser
actually submits the Form to the form handler on the web server.
Form controls
There are different types of Form controls that we can use to collect data using
HTML Form. These controls include Text box, Password, Check Box, Radio Button,
159
Computer Applications (Commerce) - XII
Text Area, Select Box, Submit and Reset Button.We can create most of these controls
in any HTML Form using <INPUT> tag.
5.6.2 <INPUT> tag
The visible part of a Form is a set of controls to accept the input from the viewers.
Different types of input can be selected based on the nature of input. The <INPUT>
tag is an empty tag that can be used to make different types of controls such as Text
Box, Radio Button, Submit Button etc. The Type attribute determines the type of
control created by this tag.
Attributes of <INPUT> tag
1. Type: This attribute determines the control type created by the <INPUT> tag.
The main values of Type are given in Table 5.5.
Value Description
text creates a text box
password same as text box. But here characters are represented by coded
symbols such as asterisk.
checkbox creates a checkbox where user can enter Yes or No values (check
or uncheck).
radio similar to checkbox but is used to select a single value from a
group of values. When multiple radio buttons are assigned with
the same value for Name attribute, users can select only one button
at a time. When the user changes the selection, the one that is
already selected becomes deselected.
reset a special button used to clear all the entries made in the form and
to bring it to the initial state.
submit another special button used to submit all the entries made in the
form to the server.
button creates a standard graphical button on the form. We can call
functions on clicking this button.
Table 5.5: Values of Type attribute
2. Name: It is used to give a name to the input control. When the Form is submitted,
the data values are passed to the server along with the corresponding name of
the control.
3. Value: It can be used to provide an initial (default) value inside the control.
4. Size: This attribute sets the width of the input text in terms of characters. It is
applicable only to the input types text and password.
160
5. Web Designing using HTML
5. Maxlength: It limits the number of characters that the user can type into the
field. It is also applicable only to the text and the password.
The HTML code given in Example 5.18 creates an HTML Form to input a name
and password. Figure 5.24 shows the resultant web page.
Example 5.18: To create an HTML Form
<HTML>
<HEAD> <TITLE> Login </TITLE> </HEAD>
<BODY Bgcolor= "Pink">
<FORM Action= "login.php" Method= "post">
<P> Name:
<INPUT Type= "text" Name= "firstname" Size= "30"
Maxlength= "25"> </P>
<P>Password:
<INPUT Type= "password" Name= "Psswd" Size= "30"
Maxlength= "25"> </P> <BR>
<INPUT Type= "reset" Value= "Clear">
<INPUT Type= "submit" Value= "Send">
</FORM>
</BODY>
</HTML>
161
Computer Applications (Commerce) - XII
Let us design an HTML Form to input data with the help of radio button (or
option button) and check boxes. You might have heard that radio buttons are used
to specify only one option from a set of alternatives, and that check boxes are used
to mark one or more items in a given list.
The code given in Example 5.19 creates a Form to specify the gender and hobbies
of a person with the help of radio buttons and check boxes. Figure 5.25 shows the
corresponding web page.
Example 5.19: To create an HTML Form with radio buttons and check boxes
<HTML>
<HEAD> <TITLE>Checkbox Radio Button Control</TITLE> </HEAD>
<BODY Bgcolor= "#E9BEE5">
<FORM> <BR>Sex:
<INPUT Type= "radio" Name= "sex" Value= "male"> Male
<INPUT Type= "radio" Name= "sex" Value= "female"> Female
<BR> <BR>Hobbies:
<INPUT Type= "checkbox" Name= "Hobby" Value= "Games">
Playing Games
<INPUT Type= "checkbox" Name= "Hobby"
Value="WatchingTV"> Watching TV
<INPUT Type= "checkbox" Name= "Hobby" Value= "Reading">
Reading
</FORM>
</BODY>
</HTML>
162
5. Web Designing using HTML
between the tag pair gives space for multi line text depending on the values given to
the attributes. The main attributes of <TEXTAREA> tag are:
1. Name: It is used to give a name to the control.
2. Rows: It specifies the number of rows in a text area control.
3. Cols: It indicates the number of columns in a text area, i.e., number of characters
in a line.
Consider the following code segment and observe the usage of <TEXTAREA> tag:
<FORM Action= "guestbook.php" Method= "post">
<TEXTAREA Rows= "10" Cols= "30" Name= "address">
Enter your address.
</TEXTAREA>
</FORM>
On completing the code and opening it, we can
see a page as shown in Figure 5.26. Any text we
include between tag pair <TEXTAREA> and
</TEXTAREA> appears in a text box. When the
user enters any data in the text box, it overrides
default text.
5.6.4 <SELECT> tag Fig. 5.26: HTML Form with text area
A select box, also called dropdown box, provides a list of various options in the
form of a dropdown list, from where a user can select one or more options. Select
box is helpful when a number of options are to be displayed in a limited space. The
options in the list are specified using <OPTION> tag, which will be contained in the
<SELECT> tag pair.
The container tag pair <SELECT> and </SELECT> encloses a select box. The main
attributes of <SELECT> tag are:
1. Name: It gives a name to the control, which is sent to the server to be recognized
and to get the value.
2. Size: This can be used to present a scrolling list box. Its value will decide
whether the select box should be a drop down list or a list box. If the value is
1, we get a dropdown list (or combo box).
3. Multiple: It allows users to select multiple items from the menu.
Now let us discuss the role of <OPTION> tag in select boxes. It is an empty tag
placed inside the container tag <SELECT> and </SELECT>. It lists out the options
provided in the select box. The main attributes of <OPTION> tag are:
163
Computer Applications (Commerce) - XII
Now let us create a Form with all the elements discussed so far, to submit the
details such as name, age, sex, address, hobbies etc. of a student. The code given in
Example 5.21 can be used for this so that an HTML Form as shown in Figure 5.28
will be obtained.
Example 5.21: To create an HTML Form to submit the details of a student
<HTML>
<HEAD> <TITLE> FormResume </TITLE> </HEAD>
<BODY Bgcolor= "#E9BEE5">
<CENTER ><H3>Enter your details</H3></CENTER>
<FORM Action= "guestbook.php" Method= "get">
Name:
<INPUT Type= "text" Name= "first_name" Size= "20"
Maxlength= "20" Value= "First Name Here"><BR><BR>
Age:
<INPUT Type="text" Name="age" Size="3" Maxlength="3"><BR>
Sex:
<INPUT Type="radio" Name="sex" Value="male"> Male
<INPUT Type="radio" Name="sex" Value="female"> Female
<FIELDSET>
<LEGEND>Nationality</LEGEND>
<SELECT Name= "Nationality" Size= "4">
<OPTION Value= "Indian" Selected> Indian
<OPTION Value= "British"> British
<OPTION Value= "German"> German
<OPTION Value= "Srilankan"> Srilankan
</SELECT><BR><BR>
Nativity:
<INPUT Type= "text" Name="State" Size="15"><BR><BR>
District:
<INPUT Type= "text" Name= "District" Size= "15">
</FIELDSET><BR>
Hobbies:
<INPUT Type= "checkbox" Name= "Hobby" Value= "games">
Playing Games
<INPUT Type= "checkbox" Name= "Hobby"
Value= "WatchingTV"> Watching TV
<INPUT Type= "checkbox" Name= "Hobby" Value= "Reading">
Reading<BR><BR>
165
Computer Applications (Commerce) - XII
The Method attribute of the <FORM> tag specifies the HTTP method (get or
post) to be used when submitting the forms.
Know your progress
1. HTML provides _______ to input data through web pages.
2. Name the two tags used within <FORM> to enter text data.
3. How do radio button control and check box control differ?
4. Which tag is used to group data within the Form?
5. Name the tag used within <FORM> to input data.
167
Computer Applications (Commerce) - XII
Let us conclude
In this chapter, we have gone through some of the advanced features of HTML.
Different kinds of lists are discussed to make the text more presentable. The beauty
of the web pages can be enhanced by including marquees, images, audio and video.
We have also discussed the importance of hyper linking and familiarised with various
kinds of hyperlinks. Creating a table with the tags <TABLE>, <TR>, <TH>, and
<TD>, and their attributes were discussed. The importance of Rowspan and
Colspan attributes are identified. We can divide the browser window into different
frames using framesets so that different pages can be opened and viewed at the
same time. We have also seen that division of browser window can be done in
different ways with the concept of nested framesets. We have discussed how Target
attribute is used to create link between different frames of the browser window. We
have also identified the utility of Form in the web page to submit data to the server
using online facility. We have seen various elements such as text box, password,
radio button, text area, select box, etc. that facilitate the input of data in different
ways. We have just mentioned the concept of client side programs and server side
programs. So, this chapter is a stepping stone to the next chapters in which we will
discuss how the input data in the Form is verified and how the data is stored or
processed in the server.
168
5. Web Designing using HTML
Let us practice
1. Wrtie an HTML code for a web page of a district in Kerala with the following
details and features:
• A heading followed by a paragraph of 3 sentences about the district using
text formatting tags and attributes.
• A list of the tourist places in the district.
2. Wrtie an HTML code for a web page for your school with the following details
and features:
• A heading followed by a paragraph of 3 sentences about the district using
text formatting tags and attributes.
• Include a list of five co-curricular activites like NCC, NSS, Clubs, etc.
3. Wrtie an HTML code for a web page to show the following details:
Components of a Computer
• Hardware
1. I/O Devices
2. RAM
3. Hard Disk & DVD Drive
• Software
1. Operating System
2. Application Programs
4. Write an HTML code to present some details about Onam - the festival of
Kerala, in a web page with the following features:
• A heading with attractive font characteristics.
• An image of "Vallam Kali" (boat race) in the background of the page.
• Internal links to any two of the traditional events like "Pookkalam",
"Thumpi Thullal", "Thiruvathira", "Onavillu", "Vallam kali", "Kummatti",
"Pulikali", etc.
5. Write HTML codes to create two web pages to show some information about
the higher secondary and high school sections of your school. Create another
web page to divide the browser window horizontally into two. In the first
frame, a brief introduction of the school and two links are to be provided -
one for HSS and the other for HS. On clicking these links the respective web
page is to be opened in the second frame.
169
Computer Applications (Commerce) - XII
6. Write an HTML code to show the following table in a web page and also
provide an external link to the website of Kerala Police given below the table:
Road Accidents in Kerala during 2012 - 2014
Total Number of
Year
Cases Persons Killed Persons Injured
2012 36174 4286 41915
2013 35215 4258 40346
2014 36282 4049 41096
Data Source: www.keralapolice.org
7. Write an HTML code to display an application form as shown below:
APPLICATION FOR THE BEST STUDENT AWARD
Name: Sex: Male Female
Class & Division: Select
Total Grade Point in Class XI:
Average Grade Point in Termly Exams in Class XII:
Cocurricular Activities:
NCC NSS Sports Arts Literary
Other Achievements:
12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
Let us assess 12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
170
5. Web Designing using HTML
2. Rohit created a table in HTML but a border was not visible. What could be
the reason?
3. ________ attribute is used with <A> tag to display the linked page in a specified
frame.
4. Your computer teacher asked you to prepare a list of your best friends in a
webpage. Which tag will you prefer? Write HTML code segment for this list.
5. Name the possible values of type attribute of <OL> tag.
6. Write the attributes of <UL> tag.
7. How do you create a list using upper case letters for numbering?
8. Suppose you want to create a list using lower case letters for numbering. How
can this be made possible?
9. How can we create a list starting from 6 onwards?
10. Write the HTML code for creating the following webpage:
ABC Pvt. Ltd.
Kerala
1. Health Care
2. Baby Products
• Toys
• Dress
3. Ladies Wear
• Kurthas
• Jeans
11. Varun is creating a web page. He wants to create a link on the word 'sample' to
a file named sample.html that is stored in a subdirectory Exam in D drive. Write
the HTML command for this purpose.
12. Name the tag which has Noshade attribute.
13. Sunil developed a personal website, in which he has to create an e-mail link.
Can you suggest the protocol used to achieve this link.
14. Shahir wants to connect his webpage to www.gmail.com. Write the tag and
attribute required for this.
15. Mention the characteristics of two types of hyperlinks available in HTML.
16. Differentiate between Cellspacing and Cellpadding.
17. Differentiate between Text control and Textarea control used in Form.
18. Action and ________ are the main attributes of the <FORM> tag.
171
Computer Applications (Commerce) - XII
I
Significant Learning Outcomes n the previous chapters we learned to
create different types of web pages
After the completion of this chapter, the containing texts and graphics. Since this is
learner the world of the Internet, most of us might
• distinguishes the use of client side have visited various websites in the Internet
and server side scripting language. for different purposes. These web pages
• explains the need of client side contain features that we have not learned.
scripting language. Creating such types of web pages requires the
• identifies the importance of knowledge of scripting languages. Different
JavaScript as the client side scripting scripting languages are used at the client side
language. and server side. Even though JavaScript and
• uses JavaScript functions in a web VB Script are the two client side scripting
page.
languages, JavaScript is the most commonly
• explains different data types in
used scripting language at the client side. The
JavaScript.
main reason for this is that the JavaScript is
• uses correct variables in JavaScript.
• uses appropriate control structures
supported by all browsers, but VB Script is
in program codes. not. Since web pages are to be viewed by a
• uses appropriate built-in functions large number of people over the Internet, we
in JavaScript. cannot expect that the user will use a specific
• explains the method to access browser itself. Hence, a web page should be
Document Elements using made browser independent as much as
javaScript. possible. In this chapter, we will learn how
• creates JavaScript functions that JavaScript is used in a web page. Since all of
handle values in text boxes and us are familiar with C++, it is easy to
combo boxes. understand JavaScript because the JavaScript
follows the same syntax of C++.
Computer Applications (Commerce) - XII
178
6. Client Side Scripting Using JavaScript
Now let us consider the following HTML code given in Example 6.1.
Example 6.1: To create a web page using JavaScript
<HTML>
<HEAD> <TITLE>Javascript - Welcome</TITLE> </HEAD>
<BODY>
<SCRIPT Language= "JavaScript">
document.write("Welcome to JavaScript.");
</SCRIPT>
</BODY>
</HTML>
The above code can be typed in any
text editor. We use Geany editor
Fig. 6.1: A web page using JavaScript
that we used for creating HTML
pages in the previous chapters. Save the file as ‘Code 6.1.html’. Note that even if we
use JavaScript in an HTML page, it is saved with .html extension. Then, open the
file in any browser. We will get the web page as shown in Figure 6.1. Note that the
statement document.write is written in lowercase letters. This is because JavaScript
is a case sensitive scripting language. The keywords in JavaScript are all in the
lowercase.
In the above HTML file, document.write() is a JavaScript command that includes
a text in the body section of the HTML page. That is, the above HTML file has the
same effect of the following HTML code.
Example 6.2: To create a web page using HTML
<HTML>
<HEAD> <TITLE>Javascript - Welcome</TITLE> </HEAD>
<BODY>
Welcome to JavaScript.
</BODY>
</HTML>
Compare the above two examples (Example 6.1 and Example 6.2). In the second
HTML code, the text Welcome to JavaScript is directly placed inside the
body section, whereas in the first one, “Welcome to JavaScript” is included
in the body section using the JavaScript method document.write(). Actually,
d o c u m e n t represents the body section of the web page. Therefore,
document.write() is a JavaScript function that will include a text in the body
179
Computer Applications (Commerce) - XII
section of the web page. It is very important to note that like C++, every statement
in JavaScript also ends in a semicolon.
<SCRIPT Language= "JavaScript"> tells the browser that the code that
follows is a JavaScript code. Now let us see how a browser handles the JavaScript
code. The script code is interpreted at runtime by the JavaScript engine. Every
browser has a JavaScript engine. JavaScript engine is a virtual machine for executing
JavaScript code. When the browser sees a JavaScript code, it is passed to the script
engine for processing. The script engine executes the code. If an HTML page does
not contain any JavaScript code, the browser alone is able to render the HTML
page. But if there is a JavaScript code, the browser takes the help of script engine
also to render the HTML page. Hence, an HTML file without JavaScript is always
rendered faster than that with JavaScript code.
Let us consider the code given in Example 6.3, that mixes JavaScript codes with
HTML tags. The output of the HTML page is given in Figure 6.2.
Example 6.3: To create a web page containing heading tags
<HTML>
<HEAD> <TITLE>Javascript - Welcome</TITLE> </HEAD>
<BODY>
<H1>
<SCRIPT Language= "JavaScript">
document.write("This is in H1 Head");
</SCRIPT>
</H1>
<BR>
<H2>
<SCRIPT Language= "JavaScript">
document.write("This is in H2 Head");
</SCRIPT>
</H2>
</BODY>
</HTML>
In the above code, we used scripting codes
in between the HTML tags more than once.
Fig. 6.2: Web page containing heading tags
Thus you can use the script codes any number
of times in between the HTML tags. Wherever we use script codes, do remember
to place them in between <SCRIPT> and </SCRIPT> tags.
180
6. Client Side Scripting Using JavaScript
181
Computer Applications (Commerce) - XII
182
6. Client Side Scripting Using JavaScript
Note the semicolon after the function name. Now let us make use of the above
print()function in an HTML page.
183
Computer Applications (Commerce) - XII
Here the line function function_name()is called the function header and
the code within the braces { and } is called function body. The main difference
from C++ is that, in JavaScript there is no return type, whereas in C++ the function
has a return type. In JavaScript also, we can return some value from a function as in
C++. Since this chapter is meant to give only a basic idea about the use of JavaScript,
we do not discuss them for the time being. Another difference is that, C++ does
not use the keyword function to define a function, but JavaScript does.
We might have noted that the function is defined within the head section of the
HTML page. It is not necessary to define the function within the head section itself.
We can define a function in the body section also as given below:
<BODY>
<SCRIPT Language= "JavaScript">
function print()
{
document.write(“Welcome to JavaScript.”);
}
print();
</SCRIPT>
</BODY>
The above code also produces the same output as in Figure 6.3. Note that even if
the function is defined within the body section, it must be called for its execution.
For example, the following code does not display anything on the screen:
<BODY>
<SCRIPT Language= "JavaScript">
function print()
{
document.write(“Welcome to JavaScript.”);
}
</SCRIPT>
</BODY>
Even though a function can be defined
anywhere in an HTML page, it is always
better to include the function definition
within the head section. Now consider the
following code in which the print()
function is called twice. It will give the Fig. 6.4: Web page using two print functions
output as shown in Figure 6.4. without break
184
6. Client Side Scripting Using JavaScript
<BODY>
<SCRIPT Language= "JavaScript">
print();
print();
</SCRIPT>
</BODY>
When we call the function twice, it just places the content ‘Welcome to
JavaScript’ twice in the body section, where the function is called. Hence, the
body section in the above code has the same effect as the following code.
<BODY>
Welcome to JavaScript.Welcome to JavaScript.
</BODY>
If the message should be displayed in the two different lines, we must use <BR> tag.
<BODY>
Welcome to JavaScript.<BR>Welcome to JavaScript.
</BODY>
In order to create the same effect using JavaScript, the function can be modified as
shown below.
<SCRIPT Language= "JavaScript">
function print()
{
document.write("Welcome to JavaScript.<BR>");
}
</SCRIPT>
This HTML code will give the output as
shown in Figure 6.5.
Know your progress
1. Say whether the following Fig. 6.5: Web page using two print functions
statements are true or
false:
a. A function is automatically executed when the browser opens
the web page.
b. A function is usually placed in the head section of a web page.
d. A function can be called any number of times.
e. Even though a function is defined within the body section, it
will not be executed, if it is not called.
2. List the advantages of using functions in JavaScript.
185
Computer Applications (Commerce) - XII
186
6. Client Side Scripting Using JavaScript
2. Given below is an HTML code to get the output as shown in the figure
below. The code contains four functions namely startGreen() ,
stopGreen(), startRed() and stopRed(). These functions are called
from different places from the body section of the HTML page. You can
see that the body part in each function definition is blank except for the
function stopGreen(). You have to complete the definition of all other
functions so as to get the output as shown in figure.
<HTML>
<HEAD>
<SCRIPT Language= “JavaScript”>
function startGreen()
{
.............
.............
}
function stopGreen()
{
document.write(“</FONT>”);
}
function startRed()
{
.............
.............
}
function stopRed()
{
.............
.............
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT Language= “JavaScript”>
startGreen();
</SCRIPT>
This is in Green colour with size 5
<SCRIPT Language= “JavaScript”>
stopGreen();
</SCRIPT>
187
Computer Applications (Commerce) - XII
189
Computer Applications (Commerce) - XII
190
6. Client Side Scripting Using JavaScript
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT Language= "JavaScript">
add();
</SCRIPT>
</BODY>
</HTML>
In the above example, the
body section contains only
one JavaScript statement - a
call to the add() function.
After executing the
function, it will display the Fig. 6.7: Web page to find the sum of two numbers
output as shown in Figure
6.7.
6.5 Operators in JavaScript
Almost all operators in JavaScript are exactly similar to those in C++. Let us have
a quick look at all of these operators.
6.5.1 Arithmetic operators
Table 6.1 shows the arithmetic operators used in JavaScript along with examples.
Operator Description Example Value of y Result (x)
+ Addition x = y + 10 15 25
- Subtraction x = y - 10 15 5
* Multiplication x = y * 3 15 45
/ Division x = y / 2 15 7.5
% Modulus x = y % 2 15 1
(division remainder)
x = ++y 15 16
++ Increment
x = y++ 15 15
x = --y 15 14
-- Decrement
x = y-- 15 15
Table 6.1: Arithmetic operators
191
Computer Applications (Commerce) - XII
From the above table, we can see that all arithmetic operators work exactly as in
C++.
6.5.2 Assignment operators
Table 6.2 displays the usage of various assignment operators in JavaScript.
Operator Description Example Value of a Value of b Result (a)
= Assignment a = b 10 3 3
+= Add and assignment a+=b 10 3 13
-= Minus and assignment a-=b 10 3 7
*= Multiply and assignment a*=b 10 3 30
/= Divide and assignment a/=b 10 3 3.33
%= Modulus and assignment a%=b 10 3 1
Table 6.2: Assignment operators
It is very easy to understand the working of each operator from the above table.
The ‘Result’ column gives the result after executing the statement in the ‘Example’
column with the given values of a and b.
6.5.3 Relational operators (Comparison operators)
Table 6.3 shows the various relational operators used in JavaScript, along with examples.
From the table, it is clear that the result of a relational operation is either true or
false. These operators compare the values on the two sides of the operator and
give the result accordingly.
192
6. Client Side Scripting Using JavaScript
From the above tables, it is clear that all these operators are exactly similar to C++.
JavaScript provides a number of other operators also for different purposes. Since
our discussion of JavaScript is limited only to this chapter, the discussion of those
operators are beyond the scope of this book. Besides, the operators discussed
above are enough to perform almost all the operations for a beginner. However,
the following string operator will be of use to us in various situations. This operator
is not available in C++.
6.5.5 String addition operator (+)
We have already seen that the operator + is used to add two numbers. The same
operator + is used to add two strings also. Adding two strings means concatenating
two strings.
Look at the following example code.
var x, y;
x = “A good beginning ”;
y = “makes a good ending.”;
z = x + y;
The + operator will add the two strings. Therefore the variable z will have the value
A good beginning makes a good ending. The same + operator behaves
differently based on the type of operands. If the operands are numbers, it will add
the numbers. If the operands are strings it will concatenate the strings. Now, predict
the value of z in the following code:
var x, y;
x = “23”;
y = 5;
z = x + y;
The answer is 235. If + operator sees any one operand as string, it will treat both the
operands as string type and concatenate the strings to get the result 235. Suppose,
193
Computer Applications (Commerce) - XII
we want to add x and y in the form of numbers, we can rewrite the last statement as
follows:
z = Number(x) + y;
After executing the above statement, the variable z will have the value 28. Number()
is a function in JavaScript, that converts a string type data containing numbers to
number type. We will make use of this function in some examples later in this chapter.
The syntax in the left column of Table 6.5 is simple if statement and that in the
right column is of if - else statement. Now, let us consider an example that
makes use of the if statement.
Example 6.7: To create a web page that checks whether a student has passed
or not
<HTML>
<HEAD> <TITLE>Javascript - if</TITLE> </HEAD>
<BODY>
<SCRIPT Language= "JavaScript">
var score;
score = 35;
if (score < 30)
{
document.write("The student is failed.");
}
else
{
document.write("The student is passed.");
}
</SCRIPT>
</BODY>
</HTML>
The above program code
makes use of the if statement
Fig. 6.8: Web page to illustrate if withe else statement
with else part. The output of
the program is given in Figure 6.8. We can change the value of the score as a number
below 30 and view the output to see the changes.
6.6.2 switch
switch is a multi-branching statement. Using this, different program codes can be
selected for execution based on the value of an expression. Its syntax is:
switch (expression)
{
case value1:
statements;
break;
case value2:
statements;
break;
.................
195
Computer Applications (Commerce) - XII
.................
default:
statements;
}
The appropriate case is executed based on the value of the expression. Here the
expression can be the name of a variable also. The following is a web page that
prints the day corresponding to a given number.
Example 6.8: To create a web page to print the day of a week
<HTML>
<HEAD> <TITLE>Javascript - switch</TITLE> </HEAD>
<BODY>
<SCRIPT Language= "JavaScript">
var d;
d = 3;
switch(d)
{
case 1:
document.write("Sunday");
break;
case 2:
document.write("Monday");
break;
case 3:
document.write("Tuesday");
break;
case 4:
document.write("Wednesday");
break;
case 5:
document.write("Thursday");
break;
case 6:
document.write("Friday");
break;
case 7:
document.write("Saturday");
break;
default:
document.write("Invalid Day");
}
</SCRIPT>
</BODY>
</HTML>
196
6. Client Side Scripting Using JavaScript
198
6. Client Side Scripting Using JavaScript
b. isNaN() function
This function is used to check whether a value is a number or not. In this function,
NaN stands for Not a Number. The function returns true if the given value is not
a number. For example, the following statements return the value true.
199
Computer Applications (Commerce) - XII
1. isNaN(“welcome”);
2. isNaN(“A123”);
3. isNaN(“Score50”);
4. isNaN(“A”);
c. toUpperCase() function
This function returns the upper case form of the given string. Look at the following
example code:
var x, y;
x = “JavaScript”;
y = x.toUpperCase();
alert(y);
The output of the above code segment is
shown in Figure 6.15. Here you can see how
the toUpperCase() function is called. It
is called along with the name of the string
variable x . That is, x.toUpperCase()
returns the upper case form of the string in
the variable x. JavaScript is a case sensitive Fig. 6.15 : Result of toUpperCase()
200
6. Client Side Scripting Using JavaScript
language. Hence you have to use the function exactly in the same case form as given
in the code.
d. toLowerCase() function
It returns the lower case form of the given string.
Look at the following example code.
var x, y;
x = “JavaScript”;
y = x.toLowerCase();
alert(y);
The output of the above code segment is
shown in Figure 6.16. If all the characters
in the string are already in the lower case,
the toLowerCase() returns the same string. Fig. 6.16: Result of toLowerCase()
e. charAt() function
It returns the character at a particular position. charAt(0) returns the first character
in the string. charAt(1) returns the second character in the string and so on. Look
at the following example code.
var x;
x = “JavaScript”;
y = x.charAt(4);
alert(y);
The output is given in Figure 6.17. Since
the fifth character in the variable x is ‘S’,
the letter is displayed in the browser
window. Fig. 6.17: Result of charAt()
f. length property
Besides functions, a string variable also provides some properties which are of use
to programmers. length property returns the length of the string. length means,
the number of characters in the string. For example,
var x, n;
x = “JavaScript”;
n = x.length;
alert(n);
Here, we can see how the length property is called. The property is called along
with the variable as x.length. Figure 6.18 shows the output of the above code.
201
Computer Applications (Commerce) - XII
202
6. Client Side Scripting Using JavaScript
<CENTER>
Enter a Number
<INPUT Type= “text" Name= "txtNum">
<BR><BR>
Square is
<INPUT Type= "text" Name= "txtSqr">
<BR><BR>
<INPUT Type= "button" Value= "Show">
</CENTER>
</FORM>
</BODY>
</HTML>
The output is given in Figure 6.19. Note that we have given the name frmSquare
for the Form, txtNum and txtSquare for the two textboxes. Giving names to
them is very much important to access
them using JavaScript. If we do not give
any name to a web page element, the
JavaScript cannot access these elements.
We can also note that we have not given a
name to the submit button. This is
because, this button need not be referred
from the JavaScript. Fig. 6.19 : A form web page
Now let us make a slight modification in the above program code as given in
Example 6.12.
Example 6.12: To create a web page that displays the square of a number
<HTML>
<HEAD> <TITLE>Javascript - Text box</TITLE>
<SCRIPT Language= "JavaScript">
function showSquare()
{
var num, ans;
num = document.frmSquare.txtNum.value;
ans = num * num;
document.frmSquare.txtSqr.value = ans;
}
</SCRIPT>
</HEAD>
203
Computer Applications (Commerce) - XII
<BODY>
<FORM Name= "frmSquare">
<CENTER>
Enter a Number
<INPUT Type= "text" Name= "txtNum">
<BR><BR>
Square is
<INPUT Type= "text" Name= "txtSqr">
<BR><BR>
<INPUT Type= "button" Value= "Show"
onClick= "showSquare()">
</CENTER>
</FORM>
</BODY>
</HTML>
Go through the above code carefully. Note
the additions made to the code in Example
6.11. A function with the name showSquare() Fig. 6.20: Web page to find the square of a
number
is defined in the head section of the web page.
This function is called using the following line of code:
<INPUT Type= "button" Value= "Show" onClick= "showSquare()">
onclick= "showSquare()" written within the button means that when the user
clicks this button, the function with the name showSquare()is called.
Now go through the function definition. Look at the following line:
num = document.frmSquare.txtNum.value;
Here document refers the body section of the web page. frmSquare is the name
of the Form we have given inside the body section. txtNum is the name of the text
box within the frmSquare and value refers to the content inside that text box.
That is document.frmSquare.txtNum.value means the document ’s
frmSquare’s txtNum’s value. Therefore the above line assigns the value of the
first text box in a variable num.
Now, you may be able to understand the meaning of the following line.
document.frmSquare.txtSqr.value = ans;
The above line assigns the value of the variable ans in the second text box. Thus
the above web page displays the square of the given number in the second text box
when the button is clicked. User can type any number in the first text box and click
the submit button to see its square. The screen shot of the web page while execution
is given in Figure 6.20.
204
6. Client Side Scripting Using JavaScript
</HEAD>
<BODY>
<FORM Name= "frmSum">
<CENTER>
Enter a Number 1
<INPUT Type= "text" Name= "txtNum1">
<BR><BR>
Enter a Number 2
<INPUT Type= "text" Name= "txtNum2">
<BR><BR>
The sum is
<INPUT Type= "text" Name= "txtSum">
<BR><BR>
<INPUT Type= "button" Value= "Show" onClick= "showSum()">
</CENTER>
</FORM>
</BODY>
</HTML>
This program displays 1020 as the result as shown in Figure 6.21. This is because
the + operator is used to add strings also. By default, the content of the text box is
always treated as of string type. Therefore, even
though the content in the text box is a number,
when we assign this to a variable, it will be
treated as string type only. When we add the
two strings “10”+“20” the answer is “1020”.
The function showSum() can be modified as
follows to get the sum of two numbers.
Fig. 6.21: Web page to illustrate the use
function showSum() of + operator
{
var num1, num2, ans;
num1 = Number(document.frmSum.txtNum1.value);
num2 = Number(document.frmSum.txtNum2.value);
ans = num1 + num2;
document.frmSum.txtSum.value = ans;
}
We discussed the Number() function in the previous section of this chapter. The
Number()function converts the data into number type and assigns that number
into the variable num1. In the above function, num1 and num2 are treated as number
206
6. Client Side Scripting Using JavaScript
208
6. Client Side Scripting Using JavaScript
if (document.frmSum.txtLimit.value == “”)
{
alert(“Please enter the limit!”);
return;
}
if (isNaN(document.frmSum.txtLimit.value))
{
alert("Please enter a number as the limit!");
return;
}
limit = Number(document.frmSum.txtLimit.value);
for(i = 1; i <= limit; i++)
sum += i;
document.frmSum.txtSum.value = sum;
}
Java Script is mostly used for client side validation. When the user clicks the submit
button after entering the data, JavaScript can be used to check whether the user has
given all the necessary data, check whether the data is in the correct format or not,
etc. If they are not in the correct format, a message can be shown reminding the
user to enter the correct data.
The following example makes use of a drop-down list in JavaScript. This web page
allows the user to select a state from a drop-down list. On clicking the show button,
capital of the selected State is displayed in a text box. The output is given in Figure 6.24.
Example 6.15: To create a web page that displays the capital of a State
<HTML>
<HEAD> <TITLE>Javascript - switch</TITLE>
<SCRIPT Language= "JavaScript">
function capital()
{
var n, answer;
n = document.frmCapital.cboState.selectedIndex;
switch (n)
{
case 0:
answer = "Thiruvananthapuram";
break;
case 1:
answer = "Bengaluru";
break;
209
Computer Applications (Commerce) - XII
case 2:
answer = "Chennai";
break;
case 3:
answer = "Mumbai";
break;
}
document.frmCapital.txtCapital.value = answer;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM Name= "frmCapital">
<CENTER> State
<SELECT Size= 1 Name= "cboState">
<OPTION>Kerala</OPTION>
<OPTION>Karnataka</OPTION>
<OPTION>Tamilnadu</OPTION>
<OPTION>Maharashtra</OPTION>
</SELECT>
<BR><BR>
Capital
<INPUT Type= "text" Name= "txtCapital">
<BR><BR>
<INPUT Type= "button" Value= "Show" onClick= "capital()">
</CENTER>
</FORM>
</BODY>
</HTML>
210
6. Client Side Scripting Using JavaScript
The following is a web page that allows the user to enter the name and age of a
student. The name must contain at least 5 characters. The age should be a number in
the range 15 to 20.
Example 6.16: To create a web page that validates name and age
<HTML>
<HEAD> <TITLE>Javascript - Validation</TITLE>
<SCRIPT Language= "JavaScript">
function checkData()
{
var T_name, T_age, N_age;
T_name = document.frmValid.txtName.value;
if (T_name == "")
{
alert("Please enter name!");
return;
}
if (T_name.length < 5)
{
alert("Name must contain at least 5 characters!");
return;
}
T_age = document.frmValid.txtAge.value;
if (T_age == "")
{
alert("Please enter age!");
return;
}
if (isNaN(T_age))
{
alert("Please enter a number as the age!");
return;
}
N_age = Number(T_age);
if (N_age < 15 || N_age > 20)
{
alert("The age must be between 15 and 20!");
return;
}
}
</SCRIPT>
</HEAD>
211
Computer Applications (Commerce) - XII
<BODY>
<FORM Name= "frmValid">
<CENTER>Name
<INPUT Type= "text" Name= "txtName">
<BR><BR>
Age
<INPUT Type= "text" Name= "txtAge">
<BR><BR>
<INPUT Type= "button" Value= "Save"
onClick= "checkData()">
</CENTER>
</FORM>
</BODY>
</HTML>
The output of the above code is given in
Figure 6.25. It checks all necessary
validations for the data. At first, it tests Fig. 6.25: Web page to validate name and age
whether there is an entry in the Name field or not. Then it tests whether the length
of the name entry has minimum 5 characters or not. Then, it tests whether there is
an entry in the age box. Then it checks whether the age entry is a number or not.
Finally, it tests whether the age entry is in the range 15 to 20 or not.
6.9 Ways to add scripts to a web page
Scripts can be placed inside HTML code in different ways. In the previous examples
we have placed the JavaScript code in the head section of the web page. Apart from
head section, scripts can be placed inside the <BODY> tag or as an external file.
Here we discuss the different ways of embedding scripts in web pages.
6.9.1 Inside <BODY>
Placing scripts inside the <BODY> tag has been discussed in the beginning of this
chapter. Here, the scripts will be executed while the contents of the web page is
being loaded. The web page starts displaying from the beginning of the document.
When the browser sees a script code in between, it renders the script and then the
rest of the web page is displayed in the browser window.
Let us discuss this method with an example. The following is a web page to get the
result of a candidate. The user can enter a register number in the text box. On
clicking the Get Result button, a JavaScript function should check whether there is
any entry in the register number box. If there is, it must be a number and it should
have seven digits. The output of the web page is given in Figure 6.26.
212
6. Client Side Scripting Using JavaScript
Example 6.17: To create a web page that accepts a register number after
validation
<HTML>
<HEAD> <TITLE>Javascript - Validation</TITLE> </HEAD>
<BODY>
<FORM Name= "frmValid">
<SCRIPT Language= "JavaScript">
function checkData()
{
var rno;
rno = document.frmValid.txtRegno.value;
if (rno == "")
{
alert("Please enter Register No.");
return;
}
if (isNaN(rno))
{
alert("Invalid Register No.");
return;
}
if (rno.length < 7)
{
alert("The Register No. must have 7 digits");
return;
}
}
</SCRIPT>
<CENTER>
<BR>Enter Register Number
<INPUT Type= "text" Name= "txtRegno">
<BR><BR>
<INPUT Type= "button" Value= "Get Result"
onClick= "checkData()">
</CENTER>
</FORM>
</BODY>
</HTML>
A script can also be at the bottom of <BODY> tag. If the scripts are loaded inside
the <BODY> tag or in the <HEAD> tag, they will be loaded along with the HTML
213
Computer Applications (Commerce) - XII
if (isNaN(rno))
{
alert("Invalid Register No.");
return;
}
if (rno.length < 7)
{
alert("The Register No. must have 7 digits");
return;
}
}
Note that this file contains only JavaScript code and does not contain <SCRIPT>
tag. <SCRIPT> tag is used inside the HTML file only. The file can be linked to
HTML file using the <SCRIPT> tag. The Type attribute specifies that the linked
file is a JavaScript file and the Src attribute specifies the location and file name of
the external JavaScript file. The modified HTML code is given below.
<HTML>
<HEAD><TITLE>Javascript - Validation</TITLE>
<SCRIPT Type= "text/JavaScript" Src= "checkdata.js">
</SCRIPT>
</HEAD>
<BODY>
<FORM Name= "frmValid">
<CENTER>
<BR>Enter Register Number
<INPUT Type= "text" Name= "txtRegno">
<BR><BR>
<INPUT Type= "button" Value= "Get Result"
onClick= "checkData()">
</CENTER>
</FORM>
</BODY>
</HTML>
If Src attribute is present, then contents of <SCRIPT> tag is ignored. That is, you
cannot attach an external file and execute code in single <SCRIPT> tag. Two separate
<SCRIPT> tags are needed for this. One with Src for external file and another with
the code.
215
Computer Applications (Commerce) - XII
Let us conclude
This chapter introduces JavaScript as a client side scripting language that is used
mainly for validations. The tag used in HTML to include JavaScript code and the
popular functions used are explained here. The datatypes in JavaScript and the use
of variables are also discussed in detail. The use of operators and control structures
is similar to that of C++. The different built-in functions and the events in JavaScript
are explained through examples. The different ways of including JavaScript code in
HTML page are presented in detail.
Let us practice
216
6. Client Side Scripting Using JavaScript
d. var x, y, z;
x = 1;
y = 4;
z = !(x < y);
e. var x, y, z;
x = 5;
y = 6 ;
z = (x > y) || (y % 2 == 0);
2. Predict the output of the following
a. <HTML>
<BODY>
<SCRIPT Language= "JavaScript">
var i;
for (i = 10; i >= 1; i--)
document.write(i + "<BR>");
</SCRIPT>
</BODY>
</HTML>
b. <HTML>
<BODY>
<SCRIPT Language= "JavaScript">
var i, s = 0;
for (i = 1; i <= 100; i += 2)
s += i;
document.write("Sum = " + s);
</SCRIPT>
</BODY>
</HTML>
c. <HTML>
<BODY>
<SCRIPT Language= "JavaScript">
var n, s = 0;
n = 0;
while (n <= 50)
{
s = s + n;
n = n + 5;
}
218
6. Client Side Scripting Using JavaScript
219
Computer Applications (Commerce) - XII
220
7 Web Hosting
W
e familiarised ourselves with creating
Significant Learning Outcomes
web pages in the earlier chapters. A
website consisting of several web
After the completion of this chapter, the pages are designed to give information about
learner: an organisation, product, service, etc. Suppose
we have developed a website for our school
• describes the use of a web server
using HTML. How can we make this website
and the concept of web hosting.
available on the Internet? These web pages are
• classifies different types of hosting. to be stored in the web servers connected to
• explains the way to buy hosting the Internet, to be made available to others.
space. This chapter presents an overview of web
• registers a domain and hosts a hosting, its different types and general features.
website using FTP client software. For accessing a website we need a domain
name. How domain names are chosen and
• explains the features of free
registered are also presented here. The various
hosting.
FTP client softwares available to transfer the
• identifies the use of Content files of the website (web pages, images, etc.)
Management Systems. from our computer to the server are also
• describes the need for responsive discussed. After learning this chapter, one will
web design. be able to register a domain name and host a
website.
7.1 Web hosting
To develop a website for our school we need
to design web pages. In the previous chapters,
we discussed how to design web pages. Any
text editor or a web designing tool can be used
to develop a home page, a page for the courses
Computer Applications (Commerce) - XII
in the school, facilities available, contact address, etc. and link them using a menu to
form an attractive website.
After developing the school website in our computer, it has to be made available in
the Internet. The designed website has to be uploaded to a web server to make it
available to Internet users all over the world. For this, either storage space is rented
on a web server to store the web pages that we have created or our own web server
is set up. Setting up a web server is very expensive compared to hosting a website in
a rented storage space.
Web hosting is the service of providing storage space in a web server to serve files
for a website to be made available on the Internet. The companies that provide web
hosting services are called web hosts. Web hosts own and manage web servers.
These web servers offer uninterrupted Internet connectivity, software packages for
offering additional services such as databases and support for programming
languages such as PHP, Java, ASP.NET, etc.
7.1.1 Types of web hosting
Suppose the entire content of our school website including html files, images, etc.,
require 4 MB of hard disk space on the web server. Web hosts provide only standard
packages of 10 MB, 20 MB, etc. of space on the web server. We may need to
choose the web host considering the packages offered by them that suit our purpose.
The number of visitors expected to visit our website is also a factor. If our website
requires a database, contains scripts, etc. then the support of such features are also
to be considered while choosing a web host.
The type of web hosting has to be decided based on requirements like the amount
of space needed for hosting, the number of visitors expected to visit the website,
the use of resources like databases, programming support, etc. Web hosts provide
different types of hosting packages. They can be shared hosting, virtual hosting and
dedicated hosting.
a. Shared hosting: Shared web hosting is the most common type of web hosting.
It is referred to as shared because many different websites are stored on one single
web server and they share resources like RAM and CPU. The features available on
shared web servers are generally basic and are not flexible to suit a website that
require specific features like high bandwidth, large storage space, etc. Shared hosting
is most suitable for small websites that have less traffic. Shared servers are cheaper
and easy to use, since they are configured with the most popular options. The updates
and the security issues of the software installed in the web server are taken care of
by the hosting company itself. A drawback is that since the bandwidth is shared by
several websites, if any of these has a large volume of traffic, it will slow down all
other websites hosted in the shared server.
218
7. Web Hosting
b. Dedicated hosting: Dedicated web hosting is the hosting where the client leases
the entire web server and all its resources. The web server is not shared with any
other website. Websites of large organisations, government departments, etc. where
there are large numbers of visitors, opt for dedicated web hosting. Here, the client
has the freedom to choose the hardware and software for the server and has full
control over the web server. Dedicated servers provide guaranteed performance,
but they are very expensive. The advantage of dedicated servers is that such servers
are usually hosted in data centers where the service provider facilitates Internet
connectivity, round-the-clock power supply, etc. and the technical expertise for
managing web servers. The cost of setting up and managing these facilities is thus
reduced for the client. Since the bandwidth is not shared with other websites, it
speeds up the access of the website. If the client is allowed to place their own
purchased web server in the service providers facility, then it is called co-location.
c. Virtual Private Server: A Virtual Private Server (VPS) is a physical server that
is virtually partitioned into several servers using the virtualization technology. Each
VPS works similar to a dedicated server and has its own separate server operating
system, web server software and packages like e-mail, databases, etc. installed in it.
Unlike shared hosting, VPS provides dedicated amount of RAM for each virtual
web server. Each of these VPS works as a fully independent web server, as if each
were running on a separate physical server. The users of VPS are provided with the
rights to install and configure any software on their VPS. They are also given the
right to restart their VPS without affecting other virtual servers running on the
same physical server.
VPS hosting provides dedicated bandwidth to each website on the server. This
provides the advantages of a dedicated hosting, even though the actual server is
shared. This type of hosting is suitable for websites that require more features than
that provided by shared hosting, but does not require all the features of dedicated
hosting. VPS provides almost the same
services at a lesser cost than that of
dedicated hosting. Some popular
server virtualization softwares are
VMware, Virtualbox, FreeVPS, User-
mode Linux, Microsoft Hyper-V, etc.
Figure 7.1 gives a symbolic
representation of the different types of
web hosting packages. Fig. 7.1 : Types of web hosting
219
Computer Applications (Commerce) - XII
220
7. Web Hosting
Most of the web hosting companies offer domain name registration services. After
finalising a suitable domain name for our website, we have to check whether this
domain name is available for registration or it is already in use by somebody else.
The websites of the web hosting companies or web sites like www.whois.net provide
an availability checker facility where we can check this. These websites check the
database of ICANN that contains the list of all the registered domain names and
gives a response as shown
in Figure 7.4. If the
domain name entered is
available, we can proceed
with the registration. The
registration requires filling Fig. 7.4Fig. 7.4 : Domainname
: Domain name registration
registrationsearchsearch
result result
infor mation for WHOIS
database of domain names for
ICANN. WHOIS information
requires the name, address,
telephone number and e-mail
address of the registrant, as
shown in Figure 7.5. This
information can be made public
or can be kept private according
to the registrant's wish. After
paying the annual registration fees
online, the domain is purchased
and is registered in our name. The Fig. 7.5 : Providing WHOIS information
shopping cart of the purchase is shown in Figure 7.6.
Thus, we have
purchased a web
server space for our
school website and
have registered a
domain name for it.
Now, when the user
types our domain name, Fig. 7.6 : Buying a domain name
www.stjosephsbhss.org,
in the browser window, it should display the webpage stored in the web server we
have purchased. This will happen only if the DNS for server returns the IP address
of our web server when the browser requests for it with www.stjosephsbhss.org.
221
Computer Applications (Commerce) - XII
Therefore, our domain name has to be connected to the IP address of the web
server where the web pages are stored. This is done using 'A record' (Address
record) of the domain. An 'A record' is used to store the IP address of a web
server connected to a domain name. The 'A record' can be modified by logging
into the control panel of the domain. Here, you can set the 'A record' of the domain
name to point to the IP address of web server as shown in Figure 7.7. After this,
the DNS
servers will be
able to resolve
our domain
name to
connect to our
web server. Fig. 7.7 : Changing 'A record' of the domain
222
7. Web Hosting
Once the FTP client is authenticated the IDE of FTP software appears as given in
Figure 7.9. In this figure, the portion on the left side displays the folders and files in
our computer and the right side displays the files in the web server computer. We
223
Computer Applications (Commerce) - XII
can use either the menu or ‘drag and drop’ files from the left side window to the
right side window to upload the files to the web server. The files will then be
transferred (copied) from our computer to the web server. The popular FTP client
software are FileZilla, CuteFTP, SmartFTP, etc.
224
7. Web Hosting
Most CMS is available for free download at their websites. Copy the files of the
CMS to the hosting space on our web server and configure the website as shown in
Figure 7.12. Templates that provide a list of preset designs for websites are also
popular CMS websites. There are also third party vendors who customise the CMS
for a fee. If you are hosting on a shared web server, verify whether the web server
supports the CMS you have downloaded.
CMS is economical and now many organisations, bloggers, etc. use it for their
websites. Some of the popular CMS software are WordPress, Drupal and Joomla!
Figure 7.14 shows the website of Motor Vehicles department of Government of
Kerala, developed using Joomla!
7.4 Responsive web design
Today we browse web pages using various devices like desktops, laptops, tablets
and mobile phones. All these devices have different screen sizes. Traditional web
pages are designed to be displayed on the screens of devices like desktops and
laptops. These web pages are difficult to view when it is accessed using tablets and
mobile phones. The user may have to use the scroll bar to move from one part of
the web page to another. In earlier days, a separate website was created for the
purpose of viewing in mobile devices. These websites contained web pages whose
size matched the screen size of these devices. But maintaining two websites for a
single organisation created issues. It would be better if the web page was able to
adjust itself to the screen size of the device. This type of web page designing is
called responsive web design. Figure 7.15 shows the appearance of a responsive
website in different devices.
Responsive web design is the custom of
building a website suitable to work on
every device and every screen size, no
matter how large or small, mobile phone
or desktop or television. The term
'responsive web designing' was coined by
Fig. 7.15 : Responsive web design
Ethan Marcotte, an independent designer
and author, to describe a new way of designing for the ever-changing Web. Responsive
web design can be implemented using flexible grid layout, flexible images and media
queries. Flexible grid layouts set the size of the entire web page to fit the display
size of the device. Flexible images and videos set the image/video dimensions to
the percentage of display size of the device. Media queries provide the ability to
specify different styles for individual devices. A horizontal menu in a web page for
larger displays might have to be converted to a drop down menu for a mobile
phone. These settings can be done using media queries inside the CSS file.
Screen sizes always vary - from a wearable device, mobile phones, tablets to laptops,
desktops and televisions. Therefore, it is important that websites are designed to
adapt to the screen size of the device.
227
Computer Applications (Commerce) - XII
Design a website containing the name, age, total runs scored, no. of
wickets taken, etc. of the members of the Indian cricket team and
host the web site using any free hosting services.
Prepare a list of popular CMS providers and write their features.
Let us do In the web hosting space provided, upload the files of the school
website you have prepared using any FTP software.
Let us conclude
After designing a website, it has to be hosted over the Internet using a suitable type
of hosting. Websites of small organisations can be hosted using shared hosting,
websites that have more traffic and need more security can opt for VPS hosting,
whereas websites of large organisations or those with very high traffic require
dedicated hosting. After buying a suitable web hosting space, FTP software can be
used to connect to the web server and can securely transfer the files of the website
to it. Domain name can be registered through a service provider and the 'A record'
can be set to point the domain to the web server. There are free hosting websites
that provide hosting free of cost. Content Management Systems (CMS) offer tools
and standard security features in its design that helps even people with less technical
knowledge to design and develop secure websites. Today, since we browse websites
using devices like mobile phones, tablets, laptops, etc. that have different screen
sizes, it is important to design websites that display themselves according to the
size of the screen they are viewed from.
12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
Let us assess 12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
12345678901234567890123456789012123456789012345678901234567890121234567
1. What do you mean by web hosting? Explain the different types of web hosting.
2. A supermarket in a city wishes to take its business online. It plans to accept
orders for its products through a website and receive payments online.
a. Which type of hosting is suitable for this website?
b. Explain the reason for your choice.
3. Emil wishes to purchase the web hosting space required to host a website for
his medical shop. List the features to be taken into consideration while buying
hosting space on a web server.
4. How can we connect a website hosted in a webserver to a domain name?
5. What is the advantage of using SFTP protocol in FTP software?
6. Raju wishes to host a website for his family. What are the advantages that free
web hosting companies provide?
7. What is CMS? What are the features of CMS? Give Examples.
8. Explain the need for applying responsive web design while developing websites
today.
9. How is responsive web design implemented?
228
Database Management
8 System
T
his is an era of information. The
Significant Learning Outcomes
survival of organisations in this
competitive world largely depends on
After the completion of this chapter, the the need for information obtained with high
learner accuracy and speed. We know that
• recognises the need for files. infor mation is obtained through the
• identifies the major limitations of
processing of data. For this, a huge amount
the conventional file manage-
of data is to be collected, stored and
ment system.
processed to generate information. Every
organisation that we can think of like schools,
• lists and explains the different
banks, business organisations, etc. are in need
advantages of the Database
of information. Can you imagine how this
Management System.
huge quantity of data was handled
• lists the various components of traditionally? In earlier days, this was handled
DBMS and explains their purpose. manually with data recorded in books termed
• recognises the types of users and as 'book keeping'. It is obvious that large
their roles in the DBMS environ- storage space is a hazard and processing of
ment. data is laborious. With the advent of
• explains the levels of data computers the data could be stored effectively,
abstraction and data indepen- but the possibility of duplication,
dence in DBMS. inconsistency, invalidity, etc. remained. This
• explains relational data model by chapter provides an effective mechanism to
citing examples. overcome these limitations. The concept of
Database Management System (DBMS) is
• uses different terminologies in
introduced in this chapter as an effective
RDBMS, appropriately.
record keeping system (earlier called book
• applies and evaluates various keeping). Various operations are also
operations in Relational algebra. discussed to retrieve the required and relevant
information from the database.
Computer Applications (Commerce) - XII
mechanisms for the manipulation of data. In addition, the database system must
ensure the safety of the data stored, against unauthorized access or system failure.
If data is to be shared among several users, the system must avoid possible
anomalous results. The database management system has a number of advantages
over the traditional file management system. They are listed below.
• Controlling data redundancy: In file management systems, data may be placed
in many files. The storing of the same data in multiple locations (may be in the
same file or different files) or duplication of data is known as data redundancy.
Redundancy leads to higher cost in storage and data access. Database systems
do not maintain redundant data, instead all the data is kept at one place in a
centralized manner. All the applications or users that require data refer to the
centrally maintained database. Sometimes there can be technical or business
reasons for maintaining several copies of the same data. However, redundancy
should be carefully controlled in any case.
• Data consistency: Data redundancy may lead to data inconsistency; that is,
the various copies of the same data show different values in different files.
Assume that your class teacher and Principal maintain separate copies of the
address list of all students admitted in your class. During periodic address
change a few students report to the Principal and a few students report to the
changes to the class teacher. After a certain period of time both the address
lists become irrelevant and inconsistent since total corrections are not updated
in both. By controlling data redundancy, data consistency is obtained. If a data
item appears only once, any update to its value has to be performed only once
and the updated value is immediately available to all users.
• Efficient data access: A DBMS utilises a variety of techniques to store and
retrieve data efficiently.
• Data integrity: Data integrity refers to the overall completeness, accuracy
and consistency of data in the database. This can be indicated by an absence
of any alteration in data between two updates of a data record. Data integrity
is imposed within a database at its design stage through the use of standard
rules and procedures. Data integrity can be maintained through the use of
error checking and validation routines.
• Data security: The information inside a database is valuable to any company
or organization. Therefore it must be kept secure and private. Data security
refers to the protection of data against accidental or intentional disclosure or
unauthorized destruction or modification by unauthorized persons. The various
programs and users may share data in common. But access to specific
information can be limited to selected users by setting the access rights. Through
231
Computer Applications (Commerce) - XII
232
8. Database Management System
Hardware: The hardware is the actual computer system used for storage and
retrieval of the database. This includes computers (PCs, workstations, servers and
supercomputers), storage devices (hard disks, magnetic tapes), network devices
(hubs, switches, routers) and other supporting devices for keeping and retrieval of
data.
Software: The software
part consists of the actual
DBMS, application
programs and utilities.
DBMS acts as a bridge
between the user and the
database. In other words,
DBMS is the software that
interacts with the users,
application programs, and
databases. All requests from Fig. 8.1: Database system environment
users for access to the
database are handled by the DBMS. Database management system software consists
of several software components that handle various tasks such as data definition,
data manipulation, data security, data integrity, data recovery and performance
optimization. One general function provided by the DBMS is thus the shielding of
database from complex hardware-level detail. The DBMS controls the access and
helps to maintain the consistency of the data.
Application programs are most commonly used to access data found within the
database to generate reports, tabulations, and other information to facilitate decision
making. Utilities are the software tools used to help manage the database system.
For example, all major DBMS provide graphical user interfaces (GUIs) to help
create database structures, control database access, and monitor database operations.
Data: It is the most important component of DBMS environment from the end
users point of view. The database contains operational data and the meta-data (data
about data). The database should contain all the data needed by the organization.
The major feature of databases is that the actual data and the programs that uses
the data are separated from each other. For effective storage and retrieval of
information, data is organized as fields, records and files.
Assume a box containing a collection of cards which stores the Admission Number,
Name, Batch, Result, Marks of students in a class. Each card will have the same
format but the data written on them is different as in Figure 8.2.
233
Computer Applications (Commerce) - XII
234
8. Database Management System
235
Computer Applications (Commerce) - XII
implementation of the simple structures at the logical level may involve complex
physical-level structures, the user of the logical level does not need to be aware of
this complexity. Database administrators, who must decide what information to
keep in the database, use the logical level of abstraction. Logical level is also referred
as conceptual level.
c. View level
View level is the highest level of database abstraction and is the closest to the users.
It is concerned with the way in which individual users view the data. It describes
only a part of the entire database. Most of the users of the database are not concerned
with all the information that is contained in the database. Instead they need only a
part of the database that is relevant to them. This simplifies their interaction with
the system. The system may provide many views for the same database. Figure 8.4
shows the three levels of data abstraction for a STUDENT file with fields AdmNo,
Name, Batch, Result, Marks.
236
8. Database Management System
higher level is called data independence. There are two levels of data independence,
physical data independence and logical data independence.
a. Physical data independence
Physical data independence refers to the ability to modify the schema followed at
the physical level without affecting the schema followed at the conceptual level.
That is, the application programs remain the same even though the schema at physical
level gets modified.
b. Logical data independence
Logical data independence refers to the ability to modify a conceptual schema
without causing any changes in the schema followed at view (external) level. The
logical data independence ensures that the application programs remain the same.
It is more difficult to achieve logical data independence than physical data
independence because the application programs are heavily dependent on the logical
structure of the database.
8.4 Users of database
Depending on the degrees of expertise or the mode of the interactions with DBMS
the users of a database system can be classified into the following groups:
• Database Administrator (DBA)
• Application Programmers
• Sophisticated Users
• Naive Users
8.4.1 Database Administrator
The person who is responsible for the control of the centralized and shared database
is the Database Administrator (DBA). The DBA is responsible for many critical
tasks such as,
Design of the conceptual and physical schemas: The DBA is responsible for
interacting with the users of the system to understand what data is to be stored in
the DBMS and how it is likely to be used. Based on this knowledge, the DBA must
design the conceptual schema and the physical schema.
Security and authorization: The DBA is responsible for ensuring authorized access
of data. For example, in a school, teachers allow students to find out course details,
results of the student and the details as to who teaches a particular subject. At the
same time students shall not be permitted to see teachers' salaries or grades of
237
Computer Applications (Commerce) - XII
other students. The DBA can enforce this policy by giving permission to students
to read only the course view.
Data availability and recovery from failures: The DBA must take steps to restore
the data to a consistent state when the system fails to complete a transaction or in
case of a system crash. The DBMS provides software support for these functions,
but the DBA is responsible for implementing procedures to back up the data
periodically and maintain logs (special files for storing all activities in a database
such as insertion, deletion, updation etc.) of system activity (to facilitate recovery
from a crash).
8.4.2 Application programmers
Application programmers are computer professionals who interact with the DBMS
through application programs. Application programs are programs written in any
host language (for example Visual Basic, C, C ++, Java, etc.) and interact with the
DBMS through Data Manipulation Language (DML). Application programs should
ideally access data through the external schema.
8.4.3 Sophisticated users
Sophisticated users include engineers, scientists, business analysts, and others who
are thoroughly familiar with the facilities of the DBMS. They interact with the systems
through their own queries (a request to a database) to meet their complex
requirements.
8.4.4 Naive users
Naive users interact with the system by invoking one of the application programs
that were written previously. They are not concerned with or even aware of the
details of the DBMS. Naive users deal only with the higher level of abstraction.
People accessing data over the web, clerical staff in an office, billing clerk in a
supermarket or hotels, bank clerk, etc. are examples of some naive users.
Know your progress
1. The person who interacts with the database through query
language is called ________
2. The billing clerk in a Supermarket is a ________ user.
3. Who provides data security in a database?
4. Who changes the structure of a database?
5. ________ interacts with the database through the prewritten
application program.
238
8. Database Management System
Today, a vast majority of database products are based on the relational model and
they are known as Relational DataBase Management System (RDBMS). The major
advantages of the relational model over the other data models are its simple data
representation and the ease with which even complex queries can be expressed. The
popular RDBMS are Oracle, Microsoft SQL Server, MySQL, DB2, Informix and
Ingress. Most commercial relational database systems offer a query language that
includes Structured Query Language (SQL), Query-by-Example (QBE) or Datalog.
We shall study the widely used query language SQL in the Chapter 9.
8.6 Terminologies in RDBMS
Before discussing the operations on relational databases, let us be familiar with
some terminologies associated with RDBMS.
a. Entity
An entity is a person or a thing in the real world that is distinguishable from others.
For example, each student is an entity, and each school can be considered as another
entity.
b. Relation
Relation is a collection of data elements organized in terms of rows and columns.
A relation is also called Table. A sample relation named STUDENT is shown in
Table 8.1.
239
Computer Applications (Commerce) - XII
STUDENT relation
240
8. Database Management System
any one of the values from this set only can appear in the column Batch. Similarly,
the set {EHS, NHS} is the domain of the column Results.
h. Schema
The description or structure of a database is called the database schema, which is
specified during database design. In the relational model, the schema for a relation
specifies its name, the name of each column, and the type of each column. As an
example, student information in a School database may be stored in a relation with
the following structure:
STUDENT (Admno : integer,
Roll : integer,
Name : character(50),
Batch : character(20),
Marks : decimal,
Result : character(4))
i. Instance
An instance of a relation is a set of tuples in which each tuple has the same number
of fields as the relational schema. The preceding schema says that each row in the
STUDENT relation has six columns, with column names and types as indicated.
An example for instance of the STUDENT relation is shown in Table 8.1.
Know your progress
1. Organization of data in terms of rows and columns is called
________.
2. ________ in a table gives the complete data of a particular
entity.
3. Number of rows in a relation is called ________.
4. Number of ________ in a relation is called degree of the
relation.
5. In the relational model, data is organised as ________.
8.6.1 Keys
A relation is defined as a set of tuples. All the tuples in a relation must be distinct.
That is, no two tuples can have the same combination of values for all their attributes.
Therefore there should be a way to identify a tuple in a relation. The concept of a
key allows us to make such distinctions. A key is an attribute or a collection of
attributes in a relation that uniquely distinguishes each tuples from other tuples in a
241
Computer Applications (Commerce) - XII
given relation. If a key consists of more than one attribute then it is called a composite
key. In the extreme, the entire tuple is the key since each tuple in the relation is
guaranteed to be unique. However, we are interested in smaller keys, if they exist,
for a number of practical reasons.
a. Candidate key
A candidate key is the minimal set of attributes that uniquely identifies a row in a
relation. In the STUDENT relation of Table 8.1, AdmNo can uniquely identify a
row. Therefore it can be considered as a candidate key. There may be more than
one candidate key in a relation. Also, a candidate key need not be just one single
attribute. It can be a composite key. For example, a combination of Roll, Batch
and Marks can also be used to identify a particular student. Therefore, Roll + Batch
+ Year can be considered as another candidate key of STUDENT relation.
b. Primary key
A primary key is one of the candidate keys chosen to be the unique identifier for
that table by the database designer. A primary key is a set of one or more attributes
that can uniquely identify tuples within the relation. As it uniquely identifies each
entity, it cannot contain null value and duplicate value.
Candidate keys are considered as candidates for primary key position. From the
candidate keys the one with the least number of attributes may be selected as primary
key. In our example (STUDENT relation), the attribute AdmNo can be used as the
primary key. That is, no two students in the STUDENT relation can have the same
AdmNo. In Table 8.1, we can see unique values in the column Name, but in real
case scenario, more than one student can have the same name.
c. Alternate key
A candidate key that is not the primary key is called an alternate key. In the case of
two or more candidate keys, only one of them can serve as the primary key. The
rest of them are alternate keys. In our example the combination of Roll + Batch +
Year is the alternate key since AdmNo is taken as the primary key.
d. Foreign key
A key in a table can be called foreign key if it is a primary key in another table. Since
a foreign key can be used to link two or more tables it is also called a reference key.
Suppose we have used Batch code instead of Batch name as shown in Table 8.2 and
we have a relation BATCH as shown in Table 8.3. It is clear that BatchCode is the
primary key in relation Batch, but it is used in STUDENT table as a non-key attribute.
So, BatchCode is referred to as a foreign key with respect to STUDENT relation.
242
8. Database Management System
STUDENT relation
243
Computer Applications (Commerce) - XII
help of a special language associated with the relational model, called query language.
We will learn this language in the next chapter to perform these operations. The
operations involved in relational algebra take one or two relations as input and
produces a new relation as the result. The fundamental operations in relational algebra
are SELECT, PROJECT, UNION, INTERSECTION , SET DIFFERENCE,
CARTESIAN PRODUCT, etc. The SELECT and PROJECT operations are unary
operations because they operate on one relation. The remaining operations are
binary operations as they operate on pairs of relations.
8.7.1 SELECT operation
SELECT operation is used to select rows from a relation that satisfies a given
predicate. The predicate is a user defined condition to select rows of user's choice.
This operation is denoted using lower case letter sigma ( σ ). The general format of
select is as follows:
σ condition
(Relation)
The result of SELECT operation is another relation containing all the rows satisfying
the given predicate (or conditions). The relational algebra uses various comparison
operators < (less than), <= (less than or equal to), > (greater than), >= (greater
than or equal to), = (equal to) and < > (not equal to) to set up simple conditions,
and logical operators ∨ (OR), ∧ (AND) and ! (NOT) to construct composite
conditions.
To illustrate the SELECT operation, consider the relation STUDENT given in Table
8.1. The following examples show how SELECT operations are expressed in
relational algebra and what output they produce.
Example 8.1: To select all the students who are eligible for higher studies.
σ Result="EHS"
(STUDENT)
244
8. Database Management System
σ Result="NHS" ∧ Batch="Commerce"
(STUDENT)
The result of this
operation is a relation AdmNo Roll Name Batch Marks Result
as shown in Table 8.5 104 12 Mahesh Commerce 180 NHS
Table 8.5: Output of Example 8.2
Example 8.3: To select all the students in the batch Science or Commerce.
σ Batch="Science" ∨ Batch="Commerce"
(STUDENT)
Table 8.6 shows the AdmNo Roll Name Batch Marks Result
output this operation. 101 24 Sachin Science 480 EHS
102 14 Rahul Commerce 410 EHS
104 12 Mahesh Commerce 180 NHS
106 8 Joseph Commerce 350 EHS
108 2 Bincy Science 300 EHS
Table 8.6: Output of Example 8.3
8.7.2 PROJECT operation
The PROJECT operation selects certain attributes from the table and forms a new
relation. If the user is interested in selecting the values of a few attributes, rather
than all the attributes of the relation, then use PROJECT operation. It is denoted by
lower case letter π . The general format of project operation is as follows:
π A1, A2,…., An
(Relation)
Here A1, A2, . . . ., An refer to the various attributes that would make up the
relation specified.
Example 8.4: Select Name, Result and Name Marks Result
Marks attributes in STUDENT relation. Sachin 480 EHS
π (STUDENT) Rahul 410 EHS
Name, Marks, Result
245
Computer Applications (Commerce) - XII
UNION operation is a binary operation and it returns a relation containing all tuples
appearing in either or both of the two specified relations. It is denoted by ∪ . The
two relations must be union-compatible, and the schema of the result is defined to
be identical to the schema of the first relation. If two relations are union-compatible,
then they have the same number of attributes, and corresponding attributes, taken
in order from left to right, have the same domain. Note that attribute names are not
used in defining union-compatibility.
Consider two relations ARTS and SPORTS given in Tables 8.10 and 8.11 containing
the details of students who participate in the arts festival and the sports meet of a
school, respectively. Both the relations ARTS and SPORTS consist of AdmNo,
Name and BatchCode as fields. It is clear that that these two relations are union
SPORTS relation
ARTS relation
AdmNo Name BatchCode
AdmNo Name BatchCode
102 Rahul C2
101 Sachin S2
103 Fathima H2
103 Fathima H2
105 Nelson H2
106 Joseph C2
106 Joseph C2
110 Nikitha S1
108 Bincy S2
132 Vivek C1
132 Vivek C1
154 Nevin C1
164 Rachana S1
Table 8.10: Instance of ARTS relation
Table 8.11: Instance of SPORTS relation
246
8. Database Management System
compatible. That is, the two relations have the same number of attributes and the
type of the corresponding attributes are also the same.
Relation ARTS ∪ SPORTS returns the AdmNo Name BatchCode
details of the students participated in arts 101 Sachin S2
or sports or both. That is, the expression
103 Fathima H2
ARTS ∪ SPORTS returns a table as shown
106 Joseph C2
in Table 8.12. This table consists of the
110 Nikitha S1
records belonging to the tables ARTS or
SPORTS or both, eliminating the 132 Vivek C1
duplication. In Table 8.12, we can see that 154 Nevin C1
records of students with admission 102 Rahul C2
numbers 103, 106, and 132 appear only 105 Nelson H2
once in the relation. 108 Bincy S2
164 Rachana S1
8.7.4 INTERSECTION operation Table. 8.12: Relation of ARTS U SPORTS
INTERSECTION operation is also a binary operation and it returns a relation
containing the tuples appearing in both of the two specified relations. It is denoted
by ∩ . The two relations must be union-compatible, and the schema of the result is
defined to be identical to the schema of the first relation.
If we apply INTERSECT operation on the relations in Tables 8.10 and 8.11, the
expression ARTS ∩ SPORTS returns the AdmNo Name BatchCode
details of the students participated in both
103 Fathima H2
arts and sports. That is ARTS ∩ SPORTS
returns a table consisting of rows 106 Joseph C2
common to ARTS and SPORTS as shown 132 Vivek C1
in Table 8.13. Table. 8.13: Relation of ARTS SPORTS
248
8. Database Management System
A Database model defines the logical design of data. The model describes
the relationships between different parts of the data. The different
models used in database design are Hierarchical Model, Network Model,
Relational Model and Object-Oriented Model. Hierarchical structures
were widely used in the early mainframe database management systems, such as the
Information Management System (IMS) by IBM. Popular DBMS product in Network
model were Cincom Systems' Total and Cullinet's IDMS.
Let us conclude
We have discussed the basic concepts of DBMS and its components. The advantages
of database over traditional file system have been detailed. A brief idea about
various terminologies associated with database is presented in the context of
relational data model. Once the data is organised systematically in database, the
operations provided by relational algebra to generate required information are
249
Computer Applications (Commerce) - XII
experienced with the help of sample relations. A good understanding about the
concepts introduced by this chapter is essential to learn the next chapter effectively.
In that chapter we will discuss how database is created and information is retrieved
using a query language.
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
Let us assess 123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
1. Who is responsible for managing and controlling the activities associated with
the database?
a. Database administrator b. Programmer
c. Naive user d. End user
2. In the relational model, cardinality is the
a. number of tuples b. number of attributes
c. number of tables d. number of constraints
3. Cartesian product in relational algebra is
a. a Unary operator b. a Binary operator
c. a Ternary operator d. not defined
4. Abstraction of the database can be viewed as
a. two levels b. four levels
c. three levels d. one level
5. In a relational model, relations are termed as
a. tuples b. attributes
c. tables d. rows
6. In the abstraction of a database system the external level is the
a. physical level b. logical level
c. conceptual level d. view level
7. Related fields in a database are grouped to form a
a. data file b. data record
c. menu d.bank
8. A relational database developer refers to a record as
a. criteria b. relation
c. tuple d. attribute
9. An advantage of the database management approach is
a. data is dependent on programs
b. data redundancy increases
c. data is integrated and can be accessed by multiple programs
d. none of the above
250
8. Database Management System
251
Computer Applications (Commerce) - XII
18. How many distinct tuples are there in a relation instance with cardinality 22?
a. 22 b. 11
c. 1 d. None
19. A set of possible data values is called
a. Attribute b. Degree
c. Tuple d. Domain
20. Why should you choose a database system instead of simply storing data in
conventional files?
21. Explain the different levels of data abstraction in DBMS?
22. How are schema layers related to the concepts of logical and physical data
independence?
23. Consider the instance of the EMPLOYEE relation shown in the following
table. Identify the attributes, degree, cardinality and domain of Name and
Emp_code.
Emp_Code Name Department Designation Salary
1000 Sudheesh Purchase Manager 25000
1001 Dhanya Sales Manager 25000
1002 Fathima Marketing Clerk 12000
1003 Shajan Sales Clerk 13000
24. Identify primary key, candidate keys and alternate keys in the instance of
EMPLOYEE relation in Question 23.
25. Consider the instance of the STUDENT relation shown in the following table.
Assume Reg_no as the primary key.
a. Identify the candidate keys and alternate keys in the STUDENT relation.
b. How are the primary key and the candidate key related?
252
8. Database Management System
26. What is a database? Describe the advantages and disadvantages of using DBMS.
27. What is data independence? Explain the difference between physical and logical
data independence.
28. Enforcement of standard is an essential feature of DBMS. How are these
standards applicable in a database?
29. Cardinality of a table T1 is 10 and of table T2 is 8 and the two relations are
union compatible. If the cardinality of result T1 ∪ T2 is 13, then what is the
cardinality of T1 ∩ T2? Justify your answer.
30. Cardinality of a table T1 is 10 and of table T2 is 8 and the two relations are
union compatible
a. What will be the maximum possible cardinality of T1 ∪ T2?
b. What will be the minimum possible cardinality of T1 ∩ T2?
31. Consider the relations, City (city_name, state) and Hotel (name, address,
city_name). Answer the following queries in relational algebra
a. Find the names and address of hotels in Kochi.
b. List the details of cities in Kerala state.
c. List the names of the hotels in Thrissur.
d. Find the names of different hotels.
e. Find the names of hotels in Kozhikode or Munnar .
32. Using the instance of the EMPLOYEE relation shown in question 23, write
the result of the following relational algebra expressions.
a. σ Department="Sales" (EMPLOYEE).
b. σ salary>20000 ∧ Department="Sales" (EMPLOYEE).
c. σ salary>20000 ∨ Department="Sales" (EMPLOYEE).
d. π name, salary (EMPLOYEE).
e. π name, salary ( σ Designation="Manager" (EMPLOYEE)).
f. π name, Department ( σ Designation="Clerk" ^ salary > 20000 (EMPLOYEE)).
33. Consider the instance of the BORROWER and DEPOSITOR relations shown
in following figure which stores the details of customers in a Bank. Answer the
following queries in relational algebra.
a. Display the details of the customers who are either a depositor or a
borrower.
b. Display the name of customers who are both a depositor and a borrower.
253
Computer Applications (Commerce) - XII
c. Display the details of the customers who are depositors but not borrowers.
d. Display the name and amount of customer who is a borrower but not
depositor.
BORROWER DEPOSITOR
Acc_No Name Amount Acc_No Name Amount
AC123 Albin 50000 AC123 Albin 500
AC103 Rasheeda 25000 AC105 Shabana 25000
AC106 Vishnu 25000 AC116 Vishnu 125000
AC108 Aiswarya 30000 AC108 Aiswarya 3000
34. Consider the instance of the CUSTOMER and BRANCH relations shown in
the following table. Write the Cartesian Product of the two relations.
CUSTOMER BRANCH
Acc_No Name Branch_ID Amount Branch_ID Name
AC123 Albin B1001 50000 B1001 Kochi
AC103 Rasheeda B1001 25000
B1002 Guruvayur
AC106 Vishnu B1001 25000
AC108 Aiswarya B1077 30000 B1077 Idukki
254
9. Structured Query Language
Structured Query
9 Language
I
n the last chapter, we discussed the
Significant Learning Outcomes
Relational Database Management System
(RDBMS). We know that relational
After the completion of this chapter, the database is a set of related data stored in tables
learner
called relations. We also have a basic idea about
• recognises the importance and
relational algebra, which deals with various
features of Structured Query
operations performed on relations. Now, we
Language.
• explains the components of SQL.
need more clarity on these operations which
• distinguishes the features of DDL, include creating a table, inserting data into a
DML and DCL commands. table, manipulating the data stored in a table
• identifies the characteristics of and deleting data from a table, modifying the
MySQL. structure of a table, removing a table, etc. on
• lists different data types and their a relational database. This chapter introduces
features. a language called Structured Query Language
• explains the effect of different (SQL) for these operations. Most of the
constraints in SQL. relational database management systems like
• performs operations using DDL MySQL, Oracle, Sybase, Informix, Postgres,
commands like CREATE, ALTER, SQL Server and MS Access use SQL as
DROP. standard database language. We use one of the
• uses DML commands like SELECT, most popular open source RDBMS, like
INSERT, UPDATE, DELETE for data
MySQL, to implement Structured Query
manipulation.
Language.
• identifies various clauses
associated with SQL commands and 9.1 Structured Query Language
their purpose.
• uses operators for setting different Structured Query Language (SQL) is a
conditions. language designed for managing data in
• lists different aggregate functions relational database management system
and explains their usage. (RDBMS). SQL provides an easy and efficient
• constructs nested queries for
information retrieval. 255
Computer Applications (Commerce) - XII
way to interact with relational databases. There are numerous versions of SQL. The
original version was developed in the 1970’s by Donald D. Chamberlin and Raymond
F. Boyce at IBM's San Jose Research Laboratory (now the Almanden Research
Centre). This language was originally called Structured English Query Language
(Sequel) and later its name was changed to SQL. In 1986, American National
Standard Institute (ANSI) published an SQL standard.
As we know a relational database system is a structured collection of tables
(relations) and the data is stored in these tables. Tables are uniquely identified by
their names and are comprised of columns and rows. A column (field) in a table
represents a particular type of information. In a table, each row represents a
collection of related data. We know that rows in a table are known as tuples (or
records) and columns are known as attributes.
257
Computer Applications (Commerce) - XII
the table? The Data Manipulation Language (DML) provides commands for these
types of manipulations.
DML is a component of SQL that enhances efficient user interaction with the database
system by providing a set of commands. DML permits users to insert data into
tables, retrieve existing data, delete data from tables and modify the stored data.
The common DML commands are SELECT, INSERT, UPDATE and DELETE.
Data Control Language
Data Control Language (DCL) is used to control access to the database, which is
very essential to a database system with respect to security concerns. DCL includes
commands that control a database, including administering privileges and committing
data. The commands GRANT and REVOKE are used as a part of DCL.
GRANT : Allows access privileges to the users to the database.
REVOKE : Withdraws user's access privileges given by using GRANT command.
ANSI SQL. Therefore, most SQL codes are not completely portable among different
database software without adjustments. In this chapter, SQL will be discussed using
open source database software MySQL.
MySQL is a free, fast, easy-to-use RDBMS, used for many applications. It is
developed, marketed, and supported by MySQL AB, which is a Swedish company.
MySQL is becoming very popular for many reasons:
• MySQL is released under an open-source license. So it is customizable.
• It provides high security to the database.
• It is portable as it works on many operating systems and with many languages
including PHP, PERL, C, C++, JAVA, etc.
• MySQL works rapidly and effectively even with large volume of data.
• It is highly compatible with PHP, one of the popular languages for web
development.
MySQL was developed by Michael "Monty" Widenius and David Axmark
in 1995. It was originally owned by a Swedish company called MySQL
AB, and was bought over by Sun Microsystems in 2008. Sun Microsystems
was acquired by Oracle in 2010.
MySQL is often deployed in a Linux-Apache-MySQL-PHP (LAMP), Windows-Apache-
MySQL-PHP (WAMP), or Mac-Apache-MySQL-PHP (MAMP) environment. All components
in LAMP are free and open-source, inclusive of the Operating System. The official site
for MySQL is www.mysql.com. The reference for MySQL is the "MySQL Reference
Manual", available at http://dev.mysql.com/doc
259
Computer Applications (Commerce) - XII
The prompt gives us the message that MySQL is ready to accept any query from the
user. Now we can input our queries at this prompt.
To exit from MySQL, give the command QUIT or EXIT at the prompt as:
mysql> EXIT;
9.2.2 Creating a database
We need to create a database before we work on the data. The database is the
container in which we store the tables. To create a database in MySQL, we use the
CREATE DATABASE command. The syntax is as follows:
CREATE DATABASE <database_name>;
While creating a database, the following points are to be remembered:
• The <database_name> in the syntax indicates the name of the database that
we want to create. It is recommended that the database name should be as
meaningful and descriptive as possible.
260
9. Structured Query Language
261
Computer Applications (Commerce) - XII
the correctness of the data, if we use them in a meaningful way. Care should be
taken to assign correct data types for columns during the designing of the database.
For example, if the numeric value 2 is designated as a text data type, such as a
string, then it cannot be used in a mathematical operation; whereas the same number
stored in an integer column can be used mathematically. So, let us understand the
concept of SQL data types like, the type of data they represent, range of values
supported by each of them, etc. Data types differ in different versions of SQL.
Here, we look at the different data types available in MySQL.
MySQL data types are classified into three. They are numeric data type, string (text)
data type, and date and time data type. All numerical values like 7, 100.234, -456, 0,
etc. can be represented by any of the numeric data types. The data "Aleena" (name
of a student), "Kerala" (name of a state), 'F' (specification of a gender), etc. are
string type by nature. Data like '01-01-2020', '23:34:3' can be represented by Date
and Time data types.
a. Numeric Data types
Numeric data type values can be used like any normal number. They can be added,
subtracted, multiplied and divided. The most commonly used numeric data types
in MySQL are INT or INTEGER and DEC or DECIMAL.
(i) INT or INTEGER
As we know, integers are whole numbers without a fractional part. They can be
positive, zero or negative. An integer value can be represented in MySQL by INT
or INTEGER data type. The data items like 69, 0, -112 belong to INT data type.
(ii) DEC or DECIMAL
Numbers with fractional parts can be represented by DEC or DECIMAL data type.
The standard form of this type is DECIMAL(size,D) or DEC(size,D). The
parameter size indicates the total number of digits the value contains including
decimal part. The parameter D represents the number of digits after the decimal
point. For example, the type specification DEC(5,2) or DECIMAL(5,2) denotes
that 5 is the precision and 2 is the scale. The column with this specification is able to
store any value having a maximum of five digits, out of which two are after the
decimal point. That is, the range of values will be from -999.99 to 999.99.
Table 9.2 shows an overview of numeric data types in MySQL. Remember that the
values are version dependent.
262
9. Structured Query Language
need not require that much. If the number of characters in the data is less than the
declared size of the column, the remaining character positions in the string will be
filled with white spaces (spacebar character). But when we retrieve this value from
the table, all trailing spaces are removed. Note that if the size of a column of type
CHAR is 1, it is not necessary to mention the size, because the default size of CHAR
type is 1.
(ii) VARCHAR(size)
VARCHAR represents variable length strings. It is similar to CHAR, but the space
allocated for the data depends only on the actual size of the string, not on the
declared size of the column. For example, if we want to store data in the column
Name of a table, it is better to declare that column as of type VARCHAR, because the
data in the column may contain different number of characters. The length of the
string can vary from 0 to 65535 characters (MySQL version dependent). The
VARCHAR type saves memory space since VARCHAR type did not append spaces
with the values when they are stored. The data like name of people, addresses etc.
are examples of this data type.
C. Date and Time data types
MySQL has data types for storing dates and times. The data type used to store date
type value is DATE and to store time value is TIME.
(i) DATE
The DATE data type is used to store dates. MySQL represents date values in YYYY-
MM-DD format. The supported range is from 1000-01-01 to 9999-12-31. Dates
are displayed in MySQL in one format, but we can use various date formats in our
SQL statements. The YYYY-MM-DD is the standard format. But we can use any
punctuation character between the date parts. For example, '2011-01-24',
'2011/01/25', '20110126' are valid date combinations in MySQL. We can insert
date type values into a column of DATE data type in any of the above formats.
Although MySQL tries to interpret values in several formats, date parts must always
be given in year-month-day order (for example, '98-09-04').
(ii) TIME
The TIME data type is used to specify a column to store time values in MySQL. It
shows values in the standard HH:MM:SS format. The TIME data type can be used
to store a specific point in time (like 10 hours 05 minutes 25 seconds) as well as an
interval of time between two points in time (like the time between now and the
weekend) that may sometimes be larger than 23 hours. When manually entering a
time into MySQL it is highly recommended that you use the exact format HH:MM:SS.
264
9. Structured Query Language
265
Computer Applications (Commerce) - XII
let us again consider the table student given in Table 9.1. How can we create a table
with a set of columns? The DDL command CREATE TABLE is used to define a
table by specifying the name of the table and giving the column definitions consisting
of name of the column, data type and size, and constraints if any, etc. Remember
that each table must have at least one column. The syntax of CREATE TABLE
command is:
CREATE TABLE <table_name>
(<column_name> <data_type> [<constraint>]
[, <column_name> <data_type> [<constraint>,]
..............................
.............................. );
Here, the <table_name> represents the name of the table that we want to create;
<column_name> represents the name of a column in the table; <data_type>
represents the type of data in a column of the table; and <constraint> specifies
the rules that we can set on the values of a column. All the columns are defined
within a pair of parentheses, and are separated by commas. We can define all the
columns even in a single line.
9.4.1 Rules for naming tables and columns
While naming the tables and columns, certain points are to be remembered and
they are listed below.
• The name may contain letters (A - Z, a - z), digits (0 - 9), under score ( _ ) and
dollar ($) symbol.
• The name must contain at least one character. (Names with only digits are
invalid).
• The name must not contain white spaces, special symbols.
• The name must not be an SQL keyword.
• The name should not duplicate with the names of other tables in the same data
base and with other columns in the same table.
In some MySQL versions, the table name can be a quoted identifier. The
identifier quote character is the backtick ("`"). If we use table name
as quoted, then we can include any special symbols in the name of the
table.
Now, let us create a table student to store the details of a group of higher secondary
students in a school. The fields of the table and their descriptions are given in Table
9.4.
266
9. Structured Query Language
accept any values that violate the criteria concerned. This ensures the accuracy and
reliability of the data in the database. The constraints ensure database integrity and
hence they are often called data base integrity constraints. Constraints could be
column level or table level.
a. Column Constraints
Column constraints are applied only to individual columns. They are written
immediately after the data type of the column. The following are column constraints:
i. NOT NULL
This constraint specifies that a column can never have NULL values. NULL is a keyword
in SQL that represents an empty value. It is important to remember that NULL
does not equate to a blank or a zero; it is something else entirely. Though a blank is
equal to another blank and a zero is equal to another zero, a NULL is never equal to
anything, not even another NULL. Two NULL values cannot be added, subtracted or
compared.
ii. AUTO_INCREMENT
MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature.
If no value is specified for the column with AUTO_INCREMENT constraint, then
MySQL will assign serial numbers automatically and insert the newly assigned value
in the corresponding column of the new record. By default, the starting value for
AUTO_INCREMENT is 1, and it will be incremented by 1 for each new record. This
special behavior also occurs if we explicitly assign the value NULL to the column.
The AUTO_INCREMENT feature makes it easy to assign a unique ID to each new
row, because MySQL generates the values for us. The auto increment column must
be defined as the primary key of the table. Only one AUTO_INCREMENT column
per table is allowed.
iii. UNIQUE
It ensures that no two rows have the same value in the column specified with this
constraint.
iv. PRIMARY KEY
This constraint declares a column as the primary key of the table. This constraint is
similar to UNIQUE constraint except that it can be applied only to one column or a
combination of columns. The primary keys cannot contain NULL values. In other
words, it can be considered as a combination of UNIQUE and NOT NULL constraints.
A PRIMARY KEY constraint is used to enforce a rule that a column should contain
only unique, non-NULL data.
268
9. Structured Query Language
v. DEFAULT
Using this constraint, a default value can be set for a column, in case the user does
not provide a value for that column of a record.
Let us apply some of these constraints in the student table and modify Query 9.1 as
given in Query 9.2.
Query 9.2 CREATE TABLE student
(adm_no INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
gender CHAR DEFAULT 'M',
dob DATE,
course VARCHAR(15)
f_income INT);
In Query 9.2, the constraints PRIMARY KEY and AUTO_INCREMENT are applied to
the column adm_no. So, this column will not allow duplicate values during data
entry. If we donot specify a value for this column, MySQL will generate a data
automatically. The constraint NOT NULL applied to the column name does not
allow to leave the column with a null value. That is, data is a must in this column.
Similarly, if we do not give a value to the column gender, ‘M’ will be stored as the
default value.
b. Table constraints
Table constraints are similar to column constraints; the main difference is that table
constraints can be used not only on individual columns, but also on a group of
columns. When a constraint is to be applied on a group of columns of a table, it is
called table constraint. The table constraint appears at the end of the table definition.
For example, Query 9.3 creates a table named stock. The constraint UNIQUE is
applied to the combination of icode and iname.
Query 9.3 CREATE TABLE stock
(icode CHAR(2) PRIMARY KEY AUTO_INCREMENT,
iname VARCHAR(30) NOT NULL,
dt_purchase DATE,
rate DECIMAL(10,2),
qty INT,
UNIQUE (icode, iname));
Write the structure of the table stock, referring to Figure 9.4 and
Query 9.3. Verify your answer in the lab with the command, DESC
stock;
Let us do
270
9. Structured Query Language
271
Computer Applications (Commerce) - XII
The INSERT statement adds a new row to the table student giving a value for every
column in the table. While inserting a row, if we provide values for all the columns
of the table, we need not specify the name of column(s) in the query. But we need to
make sure that the order of the values is in accordance with the order of the columns
in the table. Now let us insert another row with some modifications as shown in
Query 9.5.
Query 9.5 INSERT INTO student (name, dob, course, f_income)
VALUES ('Nike','1998/11/26','Science',35000);
The response for this statement will be:
Query OK, 1 row affected (0.01 sec)
In Query 9.5, admission number and gender are not provided. Being a record after
the one with admission number 1001, the admission number of this student will be
1002. The gender will be set with the default value 'M'.
While inserting data into tables, the following points are to be taken care of:
• While adding a new row, we should ensure the data type of the value and the
column matches.
• We follow the integrity constraints, if any, defined for the table.
• CHAR or VARCHAR type data should be enclosed in single quotes or double
quotes.
• Column values for DATE type columns are to be provided within single quotes.
The string will internally be converted into DATE data type.
• Null values are specified as NULL (or null) without quotes.
• If no data is available for all columns, then the column list must be included,
following the table name.
MySQL allows inserting several rows into a table with a single INSERT command
by specifying multiple value lists. The general format is as follows:
INSERT INTO <table-name> VALUES(...), (...), ... ;
Let us insert two more records given in Table 9.1 using Query 9.6.
Query 9.6 INSERT INTO student (name, dob, course, f_income)
VALUES('Bharath','1999/01/01','Commerce',45000),
('Virat','1998/12/05','Science',22000);
The response of the system will be:
Query OK, 2 rows affected (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 0
272
9. Structured Query Language
We can observe that the two records are given within separate pairs of parentheses.
The response indicates that the two records are inserted successfully.
Suppose we do not have the monthly income data of a student. How can we insert
the record? Query 9.7 illustrates the solution.
Query 9.7 INSERT INTO student(name, dob, gender, course)
VALUES('Meera','1998/08/15','F','Science');
As a response to this query, the value for adm_no will be generated by the system,
but the value for f_income column will be kept as NULL. The order of columns is
also changed in this query. The absence of values in a row can be managed in another
way also as shown in Query 9.8.
Query 9.8 INSERT INTO student(name, dob, gender, course,
f_income)
VALUES('Divakar','1998/02/21','Science',NULL);
Note that, in the VALUES clause, NULL is given for f_income.
273
Computer Applications (Commerce) - XII
Write SQL statements to insert some records in the table stock created
using Query 9.3. While giving values to the columns, utilise the facility
Let us do
of AUTO_INCREMENT and UNIQUE constraints.
274
9. Structured Query Language
276
9. Structured Query Language
Suppose we want to see the name, course and monthly family income of only the
Science group students whose income is below Rs. 25000. Here we have to constitute
two conditions - one for checking the income and the other for checking the course.
When these two conditions are matched while going through the records in the
table, the values of their name, course and f_income columns will be retrieved
for display. Query 9.13 is the required query and Figure 9.10 shows the output.
Note that AND operator is used to combine the two conditions.
Query 9.13 SELECT name, course, f_income FROM student
WHERE course='Science' AND f_income<25000;
Write a query to display the name, course
and monthly income of students studying
in courses other than Science group (i.e.,
the students of Commerce and Humanities
groups).
While writing the above query, you might
Fig. 9.10: Use of AND operator
have used OR operator for setting the
condition. The same information can be obtained by the use of NOT operator.
Query 9.14 illustrates this and Figure 9.11 shows the corresponding output.
Query 9.14 SELECT name, course, f_income FROM student
WHERE NOT course='Science';
Identify some requirements with respect
to the table stock which can be attained
by setting different conditions, and
construct queries using appropriate
operators.
SQL has a set of special operators for
Fig. 9.11: Use of NOT operator
setting conditions. These include
BETWEEN...AND, IN, LIKE and IS. Let us discuss how these operators help us to
constitute conditions.
a. Condition based on a range of values
A range of values can be given as condition. The SQL operator BETWEEN...AND
is used to specify the range. Suppose we need a list of students whose monthly
income falls in the range of Rs. 25000/- to Rs. 45000/-. We know that this can be
obtained by the statement given in Query 9.15. Figure 9.12 shows the output.
Query 9.15 SELECT name, f_income FROM student
WHERE f_income>=25000 AND f_income<=45000;
277
Computer Applications (Commerce) - XII
The same output can be obtained by using the statement given in Query 9.16. In this
statement the operator BETWEEN...AND is used to construct the condition. The
output includes both the lower and upper values given in the range.
Query 9.16 SELECT name, f_income FROM student
WHERE f_income BETWEEN 25000 AND 45000;
From Query 9.16 and Figure 9.12, we can
conclude that the BETWEEN...AND operator
allows specifying a range of values which belong
to either numeric or date and time type data.
b. Conditions based on a list of values
While setting conditions for the retrieval of Fig. 9.12: Use of BETWEEN...AND
operator
records, a list of values can be provided. The
values may be of any data type, but it should match with those of the column used
in the condition. In such a case, the operator IN is used with the list. Suppose we
want to retrieve the details of students in Commerce and Humanities groups. The
statement in Query 9.17 can generate the details as shown in Figure 9.13.
Query 9.17 SELECT * FROM student
WHERE course='Commerce' OR course='Humanities';
The same output can be obtained by using IN operator in the condition as shown in
Query 9.18.
Query 9.18 SELECT * FROM student
WHERE course IN('Commerce', 'Humanities');
As we see in Query 9.18, the IN operator checks whether the value in the specified
column (here it is course) of a record matches any of the values in the given list.
When matches are found while going through the records, they will be displayed.
Since there are only three courses in the table, the result shown in Figure 9.13 can
also be obtained using Query 9.19.
Query 9.19 SELECT * FROM student
WHERE course NOT IN('Science');
278
9. Structured Query Language
279
Computer Applications (Commerce) - XII
On the other hand, if we want to retrieve the records containing non-null values in
the f_income column, the following statement can fulfill the task:
SELECT name, course FROM student
WHERE f_income IS NOT NULL;
Identify some requirements with respect to the table stock which need
the use of the special SQL operators we discussed, and construct
Let us do
queries to solve the problems.
280
9. Structured Query Language
Fig. 9.16: Details of students according to the alphabetical order of their names
Suppose we want to see the details according to their monthly family income. If we
have to obtain the result from the highest income to the lowest, Query 9.23 can
serve the purpose. Figure 9.17 shows the output.
Query 9.23 SELECT * FROM student
ORDER BY f_income DESC;
As shown in Figure 9.17, if the column used with ORDER BY clause contains NULL
values, they will be listed last.
Multiple sorting can be performed after selection with the help of ORDER BY
clause. For example, if we need a course-based listing of students in the alphabetical
order of their names, a statement as given in Query 9.24 can be used. Figure 9.18
shows its output.
Query 9.24 SELECT name, course FROM student
ORDER BY course, name;
281
Computer Applications (Commerce) - XII
282
9. Structured Query Language
Identify some requirements with respect to the table stock which need
the sorting of records based on different conditions, and construct
Let us do
queries to solve the problems.
Let us discuss these functions to generate useful information from the table. Query
9.26 gives the highest, lowest and average family monthly incomes of the students.
Figure 9.20 shows the result.
Query 9.26 SELECT MAX(f_income), MIN(f_income), AVG(f_income)
FROM student;
While calculating
these values, the
NULL values in the
argument column are
not considered. Fig. 9.20: Use of aggregate functions
These functions can be applied to a subset of the table formed by some selection
crierion as shown in Query 9.27. It gives the number of students in the Science group.
Figure 9.21 shows the output.
Query 9.27 SELECT COUNT(*), COUNT(f_income)
FROM student
WHERE course='Science';
283
Computer Applications (Commerce) - XII
This clause is used along with GROUP BY clause. The condition in HAVING clause is
applied to form groups of records, not individual rows.
Query 9.29 applies a condition for forming groups. Here the groups will be formed
only if the condition provided with HAVING clause is satisfied.
Query 9.29 SELECT course, COUNT(*) FROM student
GROUP BY course
HAVING COUNT(*) > 3;
If we refer to Figures 9.22 and 9.23, we can find
that only Science group has more than 3 students.
Groups are not formed based on values 'Commerce'
and 'Humanities', since the number of records with Fig. 9.23: Condition based
each of these values are 2 and 1, respectively. That grouping
is why details of these groups are not shown by Query 9.29.
Identify some queries with respect to the table stock which requires
the utilisation of aggregate functions and ORDER BY clause. Write
Let us do
SQL statements to answer these queries.
285
Computer Applications (Commerce) - XII
We can use expressions to set the column values in records. Query 9.31 illustrates
this concept.
Query 9.31 UPDATE student
SET f_income=f_income+1000
WHERE f_income<25000;
The output of this query will be as follows:
Query OK, 3 rows affected (0.06 sec)
Rows matched: 3 Changed: 3 Warnings: 0
The output reveals that three records satisfy the given condition and hence the
values in f_income column of these records are incremented by 1000 (refer to
Figures 9.17, 9.25).
The columns with NULL values can also be modified with UPDATE command. Suppose
we want to store Rs. 20000/- as the monthly income in the respective field of the
286
9. Structured Query Language
records in which the column contains NULL value at present. Query 9.32 makes it
possible.
Query 9.32 UPDATE student
SET f_income=20000
WHERE f_income IS NULL;
The changes made by Queries 9.31 and 9.32 can be observed in Figure 9.25, which
is obtained by the query: SELECT * FROM student;
With respect to the table stock, write SQL statements to make some
modifications in some column values.
Let us do
287
Computer Applications (Commerce) - XII
Here the <table_name> indicates the name of the table which is to be altered;
ADD is the keyword to add the new column; <column_name> <data_type>
[<size>] indicates the description of the new column. FIRST | AFTER indicates
the position of the newly added column.
If we want to add a column at the first position, use the clause FIRST. If we want to
add a column at a specified position, use the clause AFTER <column_name>.
Note that if we do not specify the position of the new column, then by default, it
will be added as the last column of the table. Remember that the newly added
column contains only NULL values.
Let us add two columns gr_mks and reg_no in the table student to hold the
grace marks awarded to the students and their register number for the Higher
Secondary examinations, respectively. Query 9.33 can make these changes in the
structure of the table.
Query 9.33 ALTER TABLE student
ADD gr_mks INTEGER AFTER dob,
ADD reg_no INTEGER;
The response of MySQL will be the same as that we obtained for Query 9.30. We
can observe the changes made by the Queries 9.33 and 9.34 using the command:
DESC student;. The output is shown in Figure 9.26.
288
9. Structured Query Language
Fig. 9.27: Contents in the new columns after modifying the structure of table student
Write SQL statements to fill in data in the new columns with proper
values and display the changes in the records.
Make some structural modifications in the table stock and store
Let us do values according to the changes.
289
Computer Applications (Commerce) - XII
292
9. Structured Query Language
Let us create a view that contains the details of only those students who were born
before January 1, 1999. Query 9.40 creates this view named student1998.
Query 9.40 CREATE VIEW student1998
AS SELECT * FROM student2015
WHERE dob < '1999-1-1';
The output of this query will be: Query OK, 0 rows affected (0.31 sec)
Figure 9.31 shows the structure of the view and Figure 9.32 shows the contents of
the view. These can be obtained by the commands DESC student1998; and
SELECT * FROM student1998; respectively.
Let us check the data in the table 'student2015' after executing this query. Figure
9.33 shows the output of the query: SELECT * FROM student2015;
Fig. 9.33: Effect of updation in the base table through the view
The advantages of views lie in the fact that without sparing extra storage space, we
can use the same table as different tables (but virtual). Another advantage is that the
views implement sharing along with privacy. It also helps to reduce the complexity
of conditions with WHERE clause while retrieving, updating or deleting records
from tables.
If a view is no longer needed, it can be removed from the database with DROP
VIEW command. But it will not affect the base table(s). The syntax is:
DROP VIEW <view_name>;
For example, if we want to delete the view student1998 from the database, Query
9.42 can be used.
Query 9.42 DROP VIEW student1998;
We have discussed all the DDL and DML commands of SQL, which
are implemented through MySQL, with examples and their outputs.
Let us summarise them in Table 9.8. The first two rows are filled in
Let us do and the remaining rows are left to you.
294
9. Structured Query Language
DROP TABLE
CREATE VIEW
DROP VIEW
INSERT
SELECT
DML
UPDATE
DELETE
Table 9.8: Summary of SQL command
Let us conclude
Structured Query Language is used to operate on relational database. MySQL is a
popular RDBMS package by which we can implement SQL commands. We have
used various DDL commands to perform operations related with the structure of
database. Constraints have been presented to ensure data validity and integrity in
database. We have also discussed different DML commands to perform operations
associated with the data contained in tables of a database. These operations include
insertion, retrieval, modification and deletion of data in tables. We have also
familiarized ourselves with nested queries and the concept of views. A good
understanding of this chapter is essential for your higher studies in the field of
computers.
Let us practice
1. The structure of a table is given to store the details of marks scored by students
in an examination.
Data Type Description
Register number Numeric A unique and essential data to identify a
student
Name String A maximum of 30 characters
Course String It can be Science, Commerce or
Humanities
Marks of six subjects Numeric each Six separate columns are required
295
Computer Applications (Commerce) - XII
Write SQL statements for the creation of the table and the following
requirements:
a. Insert data into the fields (at least 10 records).
b. Display the details of all students.
c. List the details of Science group students.
d. Count the number of students in each course.
e. Add a new column named Total to store the total marks.
f. Fill the column Total with the sum of the six marks of each student.
g. Display the highest total in each group.
h. Find the highest, lowest and average score in Subject 6 in Commerce
group.
i. Display the names in the alphabetical order in each course.
j. Display the name of the student with the highest total.
296
9. Structured Query Language
g. List the names of items whose price is more than the average price of all
the items.
h. Display the names of items purchased after 1-1-2015.
i. Get the details of items manufactured by two or three companies (specify
the names) avialable in the table .
j. Display the details of items from a company (specify the name) with a stock
of more than 20 pieces.
3. The structure of a table is given to store the details of higher secondary school
teachers.
Data Type Description
Teacher ID Numeric A unique and essential data to identify a teacher
Name String A maximum of 30 characters
Gender Character Male or Female
Date of joining Date Duplication is allowed
Department String Science, Commerce, Humanities or Language
Basic pay Numeric Basic salary of a teacher
Write SQL statements for the creation of the table and the following
requirements:
a. Insert data into the fields (at least 10 records).
b. Display the details of all female teachers in the table.
c. List the details of male teachers in the Science department.
d. Display the names and basic pay of teachers in the Language department
whose basic pay is Rs. 21000/- or more.
e. Display the names and 71% of basic pay of the teachers.
f. Find the number of teachers in each department.
g. Display the details of teachers whose basic pay is less than the average
basic pay.
h. List the male teachers who joined before 1-1-2010.
i. Increment the basic pay of all teachers by Rs. 1000/-.
j. Delete the details of teachers from the Language department.
297
Computer Applications (Commerce) - XII
298
9. Structured Query Language
6. Which of the following is the correct order of clauses for the SELECT
statements?
a. SELECT, FROM, WHERE, ORDER BY
b. SELECT, FROM, ORDER BY, WHERE
c. SELECT, WHERE, FROM, ORDER BY
d. SELECT, WHERE, ORDER BY, FROM
7. The SQL operator ________ is used with pattern matching.
8. Read the following strings:
(i) 'Sree Kumar' (ii) 'Kumaran' (iii) 'Kumar Shanu' (iv) 'Sreekumar'
Choose the correct option that matches with the pattern '%Kumar', when used
with LIKE operator in a SELECT statement.
a. Strings (i) and (ii) only c. Strings (i) and (iii) only
b. Strings (i), (iii) and (iv) only d. All the strings
9. List any five built-in functions of SQL and the value returned by each.
10. Distinguish between WHERE clause and HAVING clause.
11. Write any four DML commands in SQL.
12. Write the essential clause required for each of the following SQL command.
a. INSERT INTO b. SELECT c. UPDATE
13. Consider the given table Customer and write the output of the following SQL
queries:
AccNo Name Branch Amount
1001 Kumar Calicut 10000
1002 Salim Trivandrum 20000
1003 Fida Kottayam 18000
1004 John Kannur 30000
1005 Raju Thrissur 5000
a. SELECT * FROM customer WHERE Amount>25000;
b. SELECT Name FROM customer
WHERE Branch IN ('Calicut, 'Kannur');
c. SELECT COUNT(*) FROM customer WHERE Amount < 20000;
d. SELECT Name FROM customer WHERE Name LIKE "%m%";
e. SELECT * FROM customer ORDER BY Amount DESC;
299
Computer Applications (Commerce) - XII
a. Suggest a suitable primary key for the above table. Give justification.
b. Write SQL statements for the following:
i. To list all stationery items.
ii. To list itemcode, name and profit of all items.
iii. To count the number of items in each category.
iv. To list all stationery items in the descending order of their unit price.
v. To find the item with the highest selling price.
vi. To create a view that contains the details of all stationery items.
16. What are the different modifications that can be made on the structure of a
table? Which is the SQL command required for this? Specify the clauses needed
for each type of modification.
17. A table is created in SQL with 10 records. Which SQL command is used to
change the values in a column of specified rows? Write the format.
18. Name the keyword used with SELECT command to avoid duplication of values
in a column.
19. Distinguish between DISTINCT and UNIQUE in SQL.
20. Pick the odd one out and give reason:
a. CREATE b. SELECT c. UPDATE d. INSERT
300
Enterprise Resourse
10 Planning
I
Significant Learning Outcomes n today's competitive world, one has to
manage the future of an enterprise more
After the completion of this chapter, the cleverly. Managing the future means
learner managing the information. A large enterprise
may generate huge amount of data such as
• identifies the need of Enterprise
financial data, customer details, purchase
Resource Planning (ERP) in an
details, employee data etc. Only the
enterprise.
organization that makes the best possible use
• lists different functional units of an of this information can succeed. In this age of
ERP system. information explosion, it is very difficult to
• explains the importance of manage this huge information by people alone.
Business Process Re-engineering Information technology and its related
(BPR) in the implementation of ERP. technologies can be used for planning and
• recognises different phases in organizing resources and information of an
implementation of an ERP system. enterprise. Hence most of the organizations
• lists some important ERP packages are moving to Enterprise Resource Planning
in the market. (ERP) packages as a solution to their
• explains the benefits and risks of
information management problem.
ERP implementation in an 10.1 Overview of an enterprise
enterprise.
An enterprise is a group of people and other
• becomes familiar with some resources working together for a common
related technologies of ERP goal. An enterprise may consist of different
system. sections or departments such as manufacturing
or production, planning, sales, purchase,
finance, distribution etc. Each department will
have their own duties and responsibilities and
they are working to achieve the objective which
Computer Applications (Commerce) - XII
integrated software that runs off a single database so that the various departments
of an enterprise can share information and communicate with each other more
easily. Conceptually, ERP replaces the old standalone computer systems in each
area of an enterprise such as finance, human resource, manufacturing, sales, etc.
with a single software program that facilitates various functional modules. Thus,
employees in any department get the required information related to the activities
of the respective department. In addition to this, the information will be available
across the departments. For example, someone in the finance department can use
ERP to see if any sale order has been shipped from the warehouse so that he can
now confidently plan for working capital management for the next period. It
organises and integrates operation processes and information flows to make
optimum use of resources such as men, material, money and machine.
ERP system is a fully integrated business management system covering functional
areas of an enterprise like Finance, Human Resources, Production, Sales , Logistics
etc. The key element of ERP is the use of a single database to store data for various
system modules. ERP systems utilise components of both computer software and
hardware.
10.3 Functional units of ERP
The resources available in an enterprise must be utilized effectively. So it is the
responsibility of the management to plan the resources. The ERP system helps the
management in making the planning process more productive and efficient.
The entire ERP package contains many modules or sub units. The number and
functioning of modules vary with the nature of enterprise and the type of ERP
package. Some commonly used modules, available in almost all packages are briefly
explained below.
Financial module
This module is the core of many ERP software packages. It can collect financial
data from various functional departments and generate valuable financial reports.
Financial reports include balance sheets, general ledger, trial balance, financial
statements, etc. This module also includes financial accounting, investment
management, enterprise controlling and treasury.
Manufacturing module
Manufacturing module contains necessary business rules to manage the entire
production process. This module of ERP enables an enterprise to combine
technology and business processes to get integrated solutions. It provides
information for the entire operation to be carried out for the production. It also
303
Computer Applications (Commerce) - XII
304
10. Enterprise Resource Planning
Package selection
In the previous phase, we selected a few packages for evaluating their performance
and efficiency. The package that we select will decide the success or failure of the
project. Since an ERP system needs huge investment, once a package is selected
and purchased, it is not an easy task to switch to another one. The most important
factor kept in mind while evaluating the different screened packages is that, it should
be flexible enough to meet the enterprise requirements.
Project planning
In this phase, the implementation process is planned and designed. The time schedule
and deadlines for different activities are determined. Roles and responsibilities of
the concerned staff are identified and assigned to each person. This phase decides
when to begin the project, how to do it and when to complete it.
Gap analysis
There is no ERP package available in the market which fulfils all the requirements
of an enterprise perfectly. Although ERP vendors may claim that their software
will solve all problems, there will still be some gaps. Even the best ERP package
will be able to meet only 80 percentage of the needs of the enterprise. So, the gap
should be analysed and considered in the following phases of ERP implementation.
Business Process Reengineering (BPR)
The fundamental rethinking and redesign of the business process to achieve
improvements in performance such as cost, quality, service and speed of an
enterprise is called business process re engineering. The importance of BPR in the
implementation of an ERP system has been already discussed (refer to Section 10.4)
Installation and configuration
This is the main functional phase of an ERP implementation. Before installing a
new ERP package, the whole process of the enterprise should be analyzed in detail.
Instead of replacing the old system with the new ERP system, it will be better and
effective to develop an appropriate prototype. This prototype is a miniature of the
actual ERP that is going to be implemented. In future, we have to conduct continuous
testing of the prototype to find out the weakness, and steps can be taken to avoid
these mistakes when the real ERP system gets introduced. The task of configuration
of ERP system should be assigned to experienced staff.
Implementation team training
This is the phase where the company trains its employees to implement and later
run the system. The ERP vendors and the hired consultants will leave the organisation
after the implementation is over. So the company must select employees with the
308
10. Enterprise Resource Planning
right attitude, willingness to change and learn new things, and who are not afraid of
technology.
System testing
The software is tested to ensure that it performs properly from both the technical
and functional areas of an enterprise. The validity of output can be determined
with the help of sample data. If any mistakes are found out at this stage, it should
be corrected before the operation of ERP system.
Going live
This is the phase where ERP is made available to the entire organization. After this
phase, the system is ready for use. After configuration and testing, removing errors,
and checking the correctness of reports, the system becomes 'live' to perform the
enterprise operations. For the smooth functioning, the ERP vendors will provide
support and service to the enterprise.
End-user training
The actual users of the ERP system need training on how to use the system. This
phase may be started before the system goes live. The employees who are going to
use the new system are identified. Their skills are noted and they are divided into
groups, based on the skill. Each group is then given training on the new system.
Since the success of ERP system is in the hands of end-users, this training is very
important.
Post implementation
After installing and operating a new ERP system, there may be the need of updating
and evaluating the system. So, after implementation, it is to be checked whether the
objective set for the ERP system is met. In this phase, errors may be corrected and
necessary steps may be taken to improve the processing efficiency.
10.6 ERP solution providers/ERP packages
Selection of ERP package is very crucial in the implementation of an ERP system.
If an ERP package is chosen correctly, implemented judiciously and used efficiently,
the productivity of the enterprise will be increased. ERP package vendors are
investing huge amount of time, money and effort in the research and development
of packaged solutions. There are so many ERP vendors in the world. Some of the
popular ERP packages are Oracle, SAP, Odoo, Microsoft Dynamics, and Tally.
Oracle
Oracle corporation is headquartered in Redwood shores , California, USA. Oracle
was originally known for its database system rather than its ERP system. The ERP
309
Computer Applications (Commerce) - XII
package from Oracle provides strong finance and accounting module. It also
provides good customer and supplier interaction, effective production analysis,
efficient human resource management and better pricing module. Oracle also
developed Customer Relationship Management (CRM) and Supply Chain
Management (SCM) software.
JD Edwards was a popular ERP package provider
which was purchased by PeopleSoft company in 2003.
Later PeopleSoft company was purchased by Oracle
Corporation in 2005.
SAP
SAP stands for Systems, Applications and Products for data processing. It is a
German multinational software corporation headquartered in Walldorf and founded
in 1972. The company started by developing software for integrated business
solutions. In the beginning, the software was developed aiming at large multinational
companies. After gaining good acceptance from them,
the company started developing packages for small scale
enterprises also. SAP also developed Customer
Relationship Management (CRM), Supply Chain
Management (SCM), and Product Life cycle Management
(PLM) software.
Odoo
Odoo is an open source ERP. In open source ERP the
source code or program can be modified as necessary,
based on the requirement of organization. Odoo was
formerly known as OpenERP until May 2014.
Microsoft Dynamics
Microsoft is an American multinational corporation headquartered in Redmond,
Washington. Microsoft Dynamics is part of Microsoft business solutions. It provides
a group of enterprise resource planning products
primarily aimed at midsized enterprises. This package
can be installed and used easily and it provides good
user interface. It also provides customer relationship
management (CRM) software.
Tally ERP
Tally solutions Pvt Ltd is a Bangalore based Software Company in India. Tally ERP
is a business accounting software for accounting, inventory and payroll.
310
10. Enterprise Resource Planning
Other than the above packages there are so many popular packages in
the market. Some of them aEpicore, Infor, Sage , Reach , Openbravo,
Apache OFBiz, Compiere, WebERP, ERP5 etc.
5. Increased flexibility
An ERP system improves the flexibility of manufacturing operations and the entire
organization. A flexible organization can adapt to the changes in the environment
rapidly. ERP system helps organizations to remain flexible by making enterprise
information available without any departmental barriers.
6. Information integrity
The most important advantage of ERP is in its promotion of integration of various
departments and hence we will get an integrated form of information about the
enterprise. The entire information about an enterprise is stored in a centralized
data base, so that complete visibility into all the important processes across various
departments of an organisation can be achieved.
Moreover, an ERP system provides high security, business intelligence, unified
reporting system, improved supplier performance, use of latest technologies, high
speed delivery of product and better analysis and planning capabilities.
10.7.2 Risks of ERP implementation
Some of the problems and limitations of using an ERP package in an enterprise
are the following:
1. High cost
The cost of ERP software configuration and implementation is very high. The
high price of the package, associated license fees and other charges are the main
problems of ERP installation. There may be additional indirect costs due to ERP
implementation like new IT infrastructure, upgrading the network facilities etc. For
small scale enterprises purchasing and installing such an expensive package may not
be preferable.
2. Time consuming
The ERP implementation process has to go through different phases and it is highly
time consuming. It may take months or even one or two years to get completed and
fully functional.
3. Requirement of additional trained staff
To run an ERP system, trained and experienced employees are to be appointed in
the enterprise. The correct selection of an ERP package alone cannot guarantee the
success of an enterprise. In addition, the contribution of skilled and trained persons
in using ERP system is very important.
312
10. Enterprise Resource Planning
313
Computer Applications (Commerce) - XII
314
10. Enterprise Resource Planning
its users whenever it is needed. MIS has the capability to generate reports as and
when the user demands it. It is mainly used to create reports on the basis of which
decisions are made. Figure 10.9 shows the role of MIS in an organisation.
So Management Infor-
mation System can be
defined as an integrated
system of man and
machine for providing
the infor mation to
support the operations, Fig 10.9: Role of MIS in an organisation
the management and the decision making function in an organisation.
Supply Chain Management (SCM)
The supply chain consists of all the activities associated with moving goods from
the supplier to the customer. It begins with collecting raw materials and ends with
receiving the goods by the consumer, as shown in Figure 10.10. It is very important
for companies to move product to their customers quickly. Faster product delivery
or availability will increase the sale and satisfaction of customers. So it is very
important to manage the activities in supply chain. Software packages are available
in the market for managing the same.
Supply Chain Management
(SCM) is a systematic approach
for managing supply chain.
SCM activities include
inventory management,
transportation management,
warehouse management,
distribution strategy
planning, customer service
performance monitoring,
Fig 10.10: Activities involved in SCM
computer simulation etc.
Decision Support System (DSS)
Decision Support Systems are interactive, computer-based systems that aid users
in judgment and choice activities. It is a computer program application that analyses
business data and presents it so that users can make business decisions more easily.
DSS focuses on providing help in analysing situations rather than providing right
information in the form of various types of reports. DSS is only a support in nature,
315
11 Trends and Issues in ICT
T
he use of Internet has increased
Significant Learning Outcomes rapidly in the last few decades. The
modern society cannot think of a day
After the completion of this chapter, the without the Internet and the services provided
learner by it. The developments in computer
• identifies the various mobile technology have led to the development of
computing terminologies. powerful but cheaper mobile devices. People
have started accessing these services on the
• recognises the features of mobile
Internet using their mobile devices like mobile
operating systems.
phones, tablets, etc.
• discovers the features of Android Information and Communication Technology
operating system. (ICT) is the term often used as an extended
• lists and explains various synonym for Information Technology (IT).
Intellectual Property Rights. ICT is more specific in integrating
• explains cyberspace.
telecommunication and computers. In this
chapter, we discuss the different technologies
• distinguishes different types of and services in mobile communication. The
cyber-crimes. various mobile operating systems available are
• details cyber law and ethics. discussed here with special focus on Android
operating system. The technologies like
• identifies the importance of IT Act.
bigdata, Radio Frequency Identification
• recognises infomania. (RFID) that improve the way of doing business
is also discussed here.
Similar to rights on property like land, house,
etc., intellectual properties like music, films,
software, designs, etc. have also ownership
rights. These rights are called Intellectual
Property Rights (IPR) and the issues related to
Computer Applications (Commerce) - XII
them are discussed in this chapter. Every technology has a dark side. Internet also
has its share of issues and threats. Some people use this medium for performing
illegal activities. We will discuss about such actions and how we can safeguard
ourselves in the Internet.
11.1 Mobile computing
The advances in computer technology have led to the development of more
computing power in small devices. Light weight computing devices with low power
consumption are now cheap and common. Devices like laptops, tablets, smart
phones, etc. have drastically changed the lifestyle and work culture of people. Today
people are able to connect to others, send and receive files or other information
anywhere anytime. This has increased computing demands on a daily basis.
Mobile computing is a technology that has computing capability and can transmit/
receive data while in motion. Mobile computing requires portable computing devices
like laptops, tablets, smart phones, etc., wireless communication networks and
connectivity to the Internet. The demand for mobile computing started the growth
and development of mobile communication technology.
11.2 Mobile communication
The term ‘mobile’ has completely revolutionised communication by opening up
innovative ways for exchanging information. Today, mobile communication has
become the backbone of society. Mobile system technologies have improved
standards of living. Mobile communication networks do not depend on any physical
connection to communicate between two devices.
11.2.1 Generations in mobile communication
The mobile phone was introduced in the year 1946. In the initial stage, growth in
mobile communication was very slow. With the increase in the number of users,
accommodating them within the limited available frequency spectrum became a
major problem. To solve this problem, the concept of cellular communication was
evolved.The cellular concept was developed in the 1960’s at Bell Laboratories.
However, in the late 1990’s, when the
Government of India offered
spectrum licenses for mobile
communication, cellular technology
became a common standard in our
country. Let us discuss different
generations in mobile communication
.
318
11. Trends and Issues in ICT
and other information. The radio signals from the satellites, which are monitored
and corrected by control stations, are picked up by the GPS receiver. GPS receivers
take the information transmitted from the satellites to calculate a user’s exact location
on earth. A GPS receiver needs only three satellites to plot a 2D position, which
will not be very accurate. Ideally, four or more satellites are needed to plot a 3D
position, which is much more accurate.
Cellular
Data
Network Internet
GPS Tracking
Application
Fig. 11.1: GPS fleet tracking
GPS is used for vehicle fleet tracking by transporting companies to track the
movement of their trucks. Figure 11.1 depicts the working of a truck tracking
application using GPS. Vehicle navigation systems will direct the driver to his or
her destination through the best route. In commercial aviation GPS is used for
aircraft navigation. GPS is also used in oil exploration, farming, atmospheric studies
etc. GPS receivers are now integrated in many mobile phones for implementing
various tracking applications.
d. Smart cards
Let us recollect about smart cards and smart card
readers that we discussed in Chapter 2 of Class XI.
A smart card is a plastic card embedded with a
computer chip / memory that stores and transacts
data. The advantages of using smart cards is that it
is secure (data is protected), intelligent (it can store
and process data) and that it is convenient (it is easy Fig. 11.2: A model smart card
322
11. Trends and Issues in ICT
to carry). That is why business firms and other organisations use smart cards for
authentication and storing data.A model of smart card issued by the Government
of India for RSBY scheme is shown in Figure 11.2.
In mobile communication, the smart card technology is used in Subscriber Identity
Modules (SIM) for GSM phone systems (refer to Figure 11.3). The smart card is
inserted or integrated into the mobile handset. The card stores personal subscriber
information and preferences. SIM cards help to identify a subscriber, roam across
networks and provide security to value added services
like Internet browsing, mobile commerce, mobile
banking, etc. Smart cards also work as credit cards, ATM
cards, fuel cards, authorisation cards for television
receiver, high-security identification cards, etc.
Fig. 11.3 : GSM SIM card
11.3 Mobile operating system
A mobile operating system is the operating system used in a mobile device (smart
phone, tablet, etc.), similar to an operating system used in a desktop or laptop
computer.
Android was released along with the formation of the Open Handset Alliance
(OHA).
The user interface of Android is based on touch inputs like swiping, tapping, pinching
and reverse pinching to manipulate on-screen objects. Android allows users to
customise their home screens with shortcuts to applications and widgets. Since its
launch in 2007, the Android operating system’s market share has been growing at a
fast pace to make it the most widely used mobile operating system today. Major
Android versions have been developed under a codename and released according
to alphabetical order. Table 11.1 shows the Android version names.
The Android OS consists of a
kernel based on Linux kernel. Version Code name
Android uses Linux kernel as it 4.4 KitKat
has a powerful memory and
4.1 Jelly Bean
process management system,
permissions-based security 4.0.3 Ice Cream Sandwich
structure and open source 3.1 Honeycomb
nature. An Application
Framework for developers to 2.3 Gingerbread
build applications using the 2.2 Froyo
Android Software
Development Kit is available in 2.0 Eclair
Android. Android Software 1.6 Donut
Development Kit can be used to
develop applications like 1.5 Cupcake
Google Maps, Facebook, etc. Table 11.1: Android version names
that run on Android.
The Android code is released under the Apache License. Apache licensing allows
the software to be freely modified and distributed by device manufacturers and
developers. Android has a large community of developers writing applications
called ‘apps’ that enhance the functionality of devices. Apps are written using a
customised version of the Java programming language.
The acceptance of Android is due to factors like its open source nature. This makes
it easy for developers to make programs/applications for Android OS called
Android apps. Most of these apps are available for free download from the Android
Play Store. It enhances the popularity of this OS.
With remarkable advances in mobile hardware and software, these trimmed-down
operating systems may be heading in a direction that could replace a desktop OS. It
324
11. Trends and Issues in ICT
Once a customer purchases a product, the product has to be billed and transported
to his location. This has to be done with minimum cost and time. The use of ICT in
transporting and tracking the product through its transit improved efficiency and
thereby winning the confidence of the customers. We will now discuss some of the
major developments in business through the use of ICT.
11.4.1 Social networks and big data analytics
Today before buying a product either online or from a nearby shop, people tend to
search websites for their price, user reviews and for comparing similar products.
They also search different social network groups and receive opinions from friends
on a particular product. Therefore business firms have started watching the
conversations and opinions posted in social media. Business firms are using the
power of social media to gain a better understanding of their markets. They use
this data from the social media and also from browsing patterns of users for their
planning. The volume of such data is very large. This data that comes from posts to
social media sites, digital pictures and videos, purchase transaction records, cell
phone data, etc. which are related to a particular business can be considered as big
data in business.
Analysis of large data is difficult. The data sources can be either structured from
databases or unstructured from audio, documents, spreadsheets, social media posts,
etc. Different software tools can be used to analyse big data, store it and take decisions
in the business. Big data analytics is the process of examining large data sets containing
a variety of data types to uncover hidden patterns, market trends, customer
preferences and other useful business information. The analytical findings/reports
can lead to refining marketing campaigns, new revenue opportunities, better customer
service, improved
operational efficiency,
competitive advantages
over rival organisations
and other business
benefits. A schematic
diagram of big data
analytics is given in
Figure 11.5.
Big data analytics
provide an oppor- Fig. 11.5: Big data analytics
tunity for business firms to answer questions that were previously considered beyond
their reach. This opened the doors to a new world of possibilities to interact
effectively with the customer, with the knowledge of his preferences.
326
11. Trends and Issues in ICT
logistic softwares help to lower the operating costs, increase productivity in the
distribution centers, maximize on-time deliveries and improve customer service
and satisfaction.
11.5 Information security
Today, almost all activities that we perform in real life like communication, buying
goods, banking, etc. can be achieved through the Internet. While executing all these
activities, information is exchanged between computers. The security of information
passed over Internet is a primary concern. In this section, we will discuss in detail
about the cyber world and the various issues like copyright and trademark violations,
cyber crimes, etc. that we come across while surfing the Internet.
11.5.1 Intellectual Property Right
Many people are engaged in creative work like music, literary work, artistic work,
discoveries, inventions, designs and software development. These works are the
creation of the mind. They demand a lots of hard work and time. The outcome of
such work is called intellectual property. It is unjust to use the idea of a person
without his permission. The person involved in developing such properties must
get the benefits of it. So, it should be protected from unauthorised access.
The importance of intellectual property was first recognised in the Paris Convention
for the Protection of Industrial Property in 1883 and the Berne Convention for the
Protection of Literary and Artistic Work in 1886. Both treaties are now administered
by the World Intellectual Property Organization (WIPO). WIPO was established in
1960 as an agency of United Nations (UN). It is dedicated to ensure that the rights
of creators or owners of intellectual property are protected worldwide and the
inventors and authors are recognised and rewarded by their creation. The logo of
WIPO and its Indian counterparts is given in Figure 11.7.
Intellectual Property Rights (IPR) are similar to any other
property right like right over land, house, etc. IPR refers to
the exclusive right given to a person over the creation of
his/her mind, for a period of time. IPR enables people to
earn recognition and financial benefit from what they invent
or create. IPR owners can disclose their creations in
exchange for money. The company which receives the rights,
markets and sells this innovation to the society. In this way
the IPR owner, the company and the society benefit from Fig. 11.7: Logo of WIPO
the creation. IPR is encouraged by UN and almost all
countries worldwide with the intention of encouraging innovations.
328
11. Trends and Issues in ICT
Each country has its own IPR registration system which is applicable to that country.
WIPO serves as an international registration system for trademark, industrial design,
etc. which is applicable to its member countries.
Intellectual property is divided into two categories - industrial property and
copyright.
A. Industrial property
Industrial property right applies to industry, commerce and
agricultural products. It protects patents to inventions,
trademarks, industrial designs and geographical indications.
In India, industrial property rights can be registered with
Controller General of Patents Designs and Trademarks
Fig. 11.8: Logo of IP under Ministry of Commerce and Industry. Logo of
India
Intellectual Property India is given in Figure 11.8.
Patents: A patent is the exclusive rights granted for an invention. An invention means
a new product or process (procedure) involving an inventive step, and capable of
industrial application. It is the legal right obtained by an inventor for exclusive control
over the production and sale of his/her mechanical or scientific invention for a limited
period of time. To be patentable, an invention must:
• relate to a process or product
• be new
• involve an inventive step
• be capable of industrial use
• not be developed with the intention to harm others
Patent protection means that the invention cannot be commercially made, used,
distributed or sold without the patent owner's
consent. A patent provides the right to the patent
owner to decide how the invention can be used by
others. The owner can sell the right to the invention to
someone else, who will then become the new owner of
the patent. The term of every patent in India is 20 years
from the date of filing of patent application. Once a
patent expires, the protection ends and an invention
can be used by the public freely. The details of the first
patent filed for a zipper is given in Figure 11.9.
Trademark: A trademark is a distinctive sign that Fig. 11.9: The first patent for
identifies certain goods or services produced or zipper
329
Computer Applications (Commerce) - XII
330
11. Trends and Issues in ICT
B. Copyright
A copyright is a legal right given to the creators for an original work, usually for a
limited period of time. Copyright applies to a wide range of creative, intellectual or
artistic forms of works which include books, music, painting, sculpture, films,
advertisement and computer software. This covers rights for reproduction,
communication to the public, adaptation and translation of the work.
In India, the Copyright Act, 1957 came into effect from January 1958. This Act has
been amended five times. Some of the important amendments to the Copyright Act
in 2012 are extension of copyright protection in the digital environment, liabilities
of Internet Service Providers, ensuring right to receive royalties for music composers
and exception of copyrights for physically disabled to access any work.
Under Indian Copyright Act, a work is automatically protected by copyright when
it is created. The general rule is that the copyright lasts
for 60 years after the death of the last surviving author.
Registration of copyright gives a legal status to a
creative work . This makes it an intellectual property,
giving exclusive legal right over the creation. It should
be noted that it is not necessary to register to get the
copyright. Copyright registrations in India are handled
by the Copyright Office under the Ministry of Human Fig. 11.13: Logo of Copyright
Resource Development. The logo of Indian Copyright Office, India
Office is given in Figure 11.13.
Table 11.2 shows the different symbols used INTELLECTUAL PROPERTY
to specify the registration status of intellectual
property. Registered trademark ®
The copyright holders of a work can authorise Unregistered trademark ™
or prohibit
Copyright ©
• its reproduction in all forms, including
print form and sound recording; Sound-recording copyright !
• its public performance and communi- Table 11.2: Symbols used for intellectual
property
cation to the public;
• its broadcasting;
• its translation into other languages;
• its adaptation, such as from a novel to a screenplay for a film.
Creators often sell the rights of their works to individuals or companies for financial
benefit.
331
Computer Applications (Commerce) - XII
products or services. It is better to register the trademarks to get the legal advantages.
An example of trademark infringement is the legal suit where a small company
manufactured toffees under the trademark 'HORLIKS'. This violated the trademark
rights enjoyed by 'HORLICKS'.
Copyright infringement is reproducing, distributing, displaying or adaptating a work
without permission from the copyright holder. It is often called piracy. Software
piracy is the illegal copying, distribution, or use of software. Music piracy is the
copying and distributing of a piece of music without the consent of the composer,
artist or the copyright holding music company. Enforcement of copyright is generally
the responsibility of the copyright holder.
people organised a movement in support of the girl through messages over the
social media. Thousands of people gathered in the streets of Delhi with lighted
candles as a protest. Taking this incident into account, this incident the Loksabha
passed 'The Criminal Law (Amendment) Act, 2013', which strictly deals with sexual
assault cases. Such movements organised over social media, show its influence on
society.
People purchase mobile phones, shoes, apparels, etc. by visiting showrooms. Today,
many people prefer to purchase these goods online from e-commerce websites.
The e-commerce sites provide catalogs which display different search options like
price range, brands, etc. about the product. This make shopping easier, from the
comfort of home and saves time too. e-Commerce requires payments through credit
cards, debit cards, Internet banking, etc. Nowadays more and more people are
attracted to online buying and selling. Figure 11.14 shows e-Commerce websites.
With the passage of time, more services are going online. Many people spend a
considerable amount of time surfing the Internet to avail of various services in the
web. Internet is often referred to as cyberspace. Figure 11.16 shows a symbolic
representation of cyberspace.
334
11. Trends and Issues in ICT
335
Computer Applications (Commerce) - XII
336
11. Trends and Issues in ICT
iv. Violation of privacy: Violation of privacy is the intrusion into the personal life
of another, without a valid reason. This gives the person whose privacy has been
invaded, the right to file a lawsuit for damages against the person/organisation that
intruded. It consists of distributing private information like personal data,
photography, workplace monitoring videos, etc.
You might have heard of issues regarding the use of hidden cameras, mobile cameras,
etc. to capture images of women in public places. Photography of any person (men
or women) without his/her permission amounts to violation of privacy. Posting
images of others in social media, transferring them to others through e-mail/copying,
etc. without their permission are considered as violation of privacy.
v. Dissemination of obscene material: The Internet has provided a medium for
the facilitation of crimes like pornography. The distribution and posting of obscene
material is one of the important cyber crimes today. Pornography on Internet may
take various forms. It may include hosting website containing prohibited materials,
use of computers for producing obscene material, downloading obscene materials
through the Internet, etc. These obscene content may misguide adolescents.
Most of the cyber crimes occur without the knowledge of the victim, whereas in
some others, the victim also takes part in crime to become rich easily. It should be
noted that various types of preventive mechanisms have been installed to avoid
such crimes. e-mail service providers use spam filter that filters unwanted mails.
Different types of authentication mechanisms that exist for online financial
transactions prevent fraud to a certain extent. Above all, an individual has to be
careful while using the Internet.
B. Cyber crimes against property
Cyber crimes against all forms of property like credit cards, intellectual property,
etc. are termed as cyber crime against property. These crimes include hacking, piracy,
computer vandalism (destruction of others property), unauthorised intrusion
through cyberspace, unauthorised possession of information stored in computers,
etc. Some classifications of cyber crimes against property are given below.
i. Credit card fraud: Credit card fraud involves an unauthorised usage of another
person's credit card information for the purpose of payments for purchases or
transferring funds from it. There are instances where the web servers of large
organisations are hacked and credit card information of a large number of people
is stolen by Internet thieves. They use this information to make payments or they
sell this information to other fraudsters over Internet for a small price.
338
11. Trends and Issues in ICT
ii. Intellectual property theft: The infringement of IPR's come under this category.
Violation of copyright, patent, trademark, etc. are intrusions against property.
Recently, an Indian IT company developed a
software for correcting errors in program code.
One of the employees of this company copied
this software in a CD and tried to sell it to a
competitor for a big price. This led to huge
financial and property loss to the company.
This is considered as theft of intellectual
property. Software piracy is also a crime under
cyber law.
Nowadays intellectual property theft has become common. Information about any
topic is now freely available on the Internet. Copying of an other person's language,
thoughts, ideas or expressions and presenting them as one's own original work is
called plagiarism. There are stringent copyright laws available in India which protect
the intellectual property rights. Plagiarism can be easily detected through various tools
available online.
iii. Internet time theft: Today almost all modems/routers have wireless Internet
facility. They provide sharing of Internet at homes, schools, business establishments,
etc. If this is not properly secured using passwords, other people may use our Internet.
The usage of the Internet time by unauthorised persons, without the permission of
the person who pays for it is called Internet time theft. This leads to loss of Internet
time and money. Above this, others may use our Internet account for committing
crimes, for which we may also be held responsible.
The different types of attacks like viruses, worms, man in the middle attack, etc.,
discussed in Chapter 9 of Class XI also fall under cyber crimes against property.
C. Cyber crimes against government
Increasing popularity of e-governance has made governments vulnerable to cyber
attacks. The various governmental computer networks and websites are vulnerable
to risks and threats of cyber crimes. The different categories of cyber attacks against
government are cyber terrorism, website defacement and e-governance denial attack.
i. Cyber terrorism: Cyber terrorism is a cyber attack against sensitive computer
networks like nuclear power plants, air traffic controls, gas line controls, telecom,
etc. These types of attacks against governments are increasing globally. Cyber
terrorism focuses on the use of the Internet by anti nationals to affect a nation's
economic and technological infrastructure.
339
Computer Applications (Commerce) - XII
340
11. Trends and Issues in ICT
• Use unique and complex passwords for accounts and change your passwords
on a regular basis. (Should have a minimum of 8 characters, contain alphabets,
numbers and special characters)
• Do not select the check boxes or click OK button before reading the contents
of any agreement/message.
• Avoid the use of unauthorised software.
• Do not hide your identity and fool others.
• Do not use bad or rude language in social media and e-mails.
• Remove the check mark against 'Remember me' before logging into your
account using computers other than your personal ones.
343
Computer Applications (Commerce) - XII
344
11. Trends and Issues in ICT
Let us conclude
The convergence of a mobile phone and a computer has shifted the focus from
desktops to mobile computing devices. These devices are always connected to the
Internet and therefore mobile communication technology has gained importance.
The mobile communication technology has evolved through generations from 1G
to 4G, the prime focus being speed. This also has led to the development of features
like SMS, MMS, GPS, etc. Android is one of the popular mobile operating systems,
developed by Google based on Linux kernel. The advances in the development of
this OS are in such a way that it will soon replace desktop operating systems and could
be used in devices like television, washing machines, etc. A person can do a variety
of jobs through cyberspace. Due to its anonymous nature, cyber space has become
a venue for criminals. Crimes can be against a person, property or government. The
best way to be safe is to be aware of the traps in the Internet. The rights of the creator
or owner of music, software, artistic works, inventions, etc. are protected by
Intellectual Property Rights. There are cyber laws which provide the framework for
a secure environment in cyberspace. India has a robust IT Act. It addresses the
different crimes committed using computers, Internet and mobile phones. Cyber
forensics has emerged as a part of legal proceedings of almost all civil and criminal
cases. Any crime committed using IT infrastructure leaves a digital evidence that
makes it easily detectable. While using Internet, ensure that our actions do not harm
others. The term Infomania is used for addressing the problems created by
information overloading.
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
Let us assess 123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
123456789012345678901234567890121234567890123456789012345678901212345678
1. What is mobile computing?
2. Explain generations in mobile communication?
3. Compare GSM and CDMA standards.
4. Write short notes on SMS.
345
Computer Applications (Commerce) - XII
346
11. Trends
References
and Issues in ICT
References
347