Computer Programming & Web Design Guide
Computer Programming & Web Design Guide
PROGRAMMING AND
WEB DESIGNING
[Link]
INTRODUCTION TO COMPUTER PROGRAMMING AND WEB DESIGNING
[Link]
email: info@[Link]
This book contains information obtained from highly regarded resources. Reprinted material sources are
indicated. Copyright for individual articles remains with the authors as indicated and published under
Creative Commons License. A Wide variety of references are listed. Reasonable efforts have been made
to publish reliable data and views articulated in the chapters are those of the individual contributors, and
not necessarily those of the editors or publishers. Editors or publishers are not responsible for the accu-
racy of the information in the published chapters or consequences of their use. The publisher assumes no
responsibility for any damage or grievance to the persons or property arising out of the use of any materi-
als, instructions, methods or thoughts in the book. The editors and the publisher have attempted to trace
the copyright holders of all material reproduced in this publication and apologize to copyright holders if
permission has not been obtained. If any copyright holder has not been acknowledged, please write to
us so we may rectify.
Notice: Registered trademark of products or corporate names are used only for explanation and identifi-
cation without intent of infringement.
In Collaboration with 3G E-Learning LLC. Originally Published in printed book format by 3G E-Learning
LLC with ISBN 978-1-98467-890-4
EDITORIAL BOARD
Aleksandar Mratinković was born on May 5, 1988 in Arandjelovac, Serbia. He has graduated on
Economic high school (2007), The College of Tourism in Belgrade (2013), and also has a master degree
of Psychology (Faculty of Philosophy, University of Novi Sad). He has been engaged in different
fields of psychology (Developmental Psychology, Clinical Psychology, Educational Psychology and
Industrial Psychology) and has published several scientific works.
Dan Piestun (PhD) is currently a startup entrepreneur in Israel working on the interface of Agriculture
and Biomedical Sciences and was formerly president-CEO of the National Institute of Agricultural
Research (INIA) in Uruguay. Dan is a widely published scientist who has received many honours
during his career including being a two-time recipient of the Amit Golda Meir Prize from the Hebrew
University of Jerusalem, his areas of expertise includes stem cell molecular biology, plant and animal
genetics and bioinformatics. Dan’s passion for applied science and technological solutions did not
stop him from pursuing a deep connection to the farmer, his family and nature. Among some of his
interest and practices counts enjoying working as a beekeeper and onboard fishing.
Hazem Shawky Fouda has a PhD. in Agriculture Sciences, obtained his PhD. From the Faculty of
Agriculture, Alexandria University in 2008. He is working in Cotton Arbitration & Testing General
Organization (CATGO).
Felecia Killings is the Founder and CEO of LiyahAmore Publishing, a publishing company committed
to providing technical and educational services and products to Christian Authors. She operates as the
Senior Editor and Writer, the Senior Writing Coach, the Content Marketing Specialist, Editor-in-Chief
to the company’s quarterly magazine, the Executive and Host of an international virtual network,
and the Executive Director of the company’s online school for Authors. She is a former high-school
English instructor and professional development professor. She possesses a Master of Arts degree
in Education and a Bachelor’s degree in English and African American studies.
Dr. Sandra El Hajj, Ph.D. in Health Sciences from Nova Southeastern University, Florida, USA is
a health professional specialized in Preventive and Global Health. With her 12 years of education
obtained from one of the most prominent universities in Beirut, in addition to two leading universities
in the State of Florida (USA), Dr. Sandra made sure to incorporate interdisciplinary and multicultural
approaches in her work. Her long years of studies helped her create her own miniature world of
knowledge linking together the healthcare field with Medical Research, Statistics, Food Technology,
Environmental & Occupational Health, Preventive Health and most noteworthy her precious last
degree of Global Health. Till today, she is the first and only doctor specialized in Global Health in
the Middle East area.
Fozia Parveen has a Dphil in Sustainable Water Engineering from the University of Oxford. Prior to
this she has received MS in Environmental Sciences from National University of Science and Technology
(NUST), Islamabad Pakistan and BS in Environmental Sciences from Fatima Jinnah Women University
(FJWU), Rawalpindi.
Igor Krunic 2003-2007 in the School of Economics. After graduating in 2007, he went on to study
at The College of Tourism, at the University of Belgrade where he got his bachelor degree in 2010.
He was active as a third-year student representative in the student [Link] he went on the
Faculty of science, at the University of Novi Sad where he successfully defended his master’s thesis in
2013. The crown of his study was the work titled Opportunities for development of cultural tourism
in Cacak“. Later on, he became part of a multinational company where he got promoted to a deputy
director of logistic. Nowadays he is a consultant and writer of academic subjects in the field of tourism.
Dr. Jovan Pehcevski obtained his PhD in Computer Science from RMIT University in Melbourne, Australia
in 2007. His research interests include big data, business intelligence and predictive analytics, data and
information science, information retrieval, XML, web services and service-oriented architectures, and
relational and NoSQL database systems. He has published over 30 journal and conference papers and he
also serves as a journal and conference reviewer. He is currently working as a Dean and Associate Professor
at European University in Skopje, Macedonia.
Dr. Tanjina Nur finished her PhD in Civil and Environmental Engineering in 2014 from University
of Technology Sydney (UTS). Now she is working as Post-Doctoral Researcher in the Centre for
Technology in Water and Wastewater (CTWW) and published about eight International journal papers
with 80 citations. Her research interest is wastewater treatment technology using adsorption process.
Stephen obtained his PhD from the University of North Carolina at Charlotte in 2013 where his graduate
research focused on cancer immunology and the tumor microenvironment. He received postdoctoral
training in regenerative and translational medicine, specifically gastrointestinal tissue engineering, at
the Wake Forest Institute of Regenerative Medicine. Currently, Stephen is an instructor for anatomy
and physiology and biology at Forsyth Technical Community College.
Michelle holds a Masters of Business Administration from the University of Phoenix, with a concentration
in Human Resources Management. She is a professional author and has had numerous articles
published in the Henry County Times and has written and revised several employee handbooks for
various YMCA organizations throughout the United States.
HOW TO USE THE BOOK
This book has been divided into many chapters. Chapter gives the motivation for this book and
the use of templates. The text is presented in the simplest language. Each paragraph has been
arranged under a suitable heading for easy retention of concept. Keywords are the words that
academics use to reveal the internal structure of an author’s reasoning. Review questions at the
end of each chapter ask students to review or explain the concepts. References provides the reader
an additional source through which he/she can obtain more information regarding the topic.
INTRODUCTION
Maintenance is the key for providing better built environment to building customers
each chapter “Preventive Maintenance: Don’t start today by doing yesterday’s work.”
- Deniece Schofield
the topic.
a proper preventive maintenance management process easy
and affordable.
Keyword Global Firewood Production and Consumption
Let’s take a look at some of the major benefits your property
Preventive can enjoy when you have a stellar preventive maintenance The existing research on firewood is limited, mainly due to
Remember
maintenance system in place. the fact that the definitions and conversion rates for firewood
is the act of The vary, and that firewood is primarily produced and traded in
performing energy
regularly Better Budgeting and Significant Cost-Cutting with required to heat the informal sector. Statistics are often only available on “wood
scheduled the water vapor fuel”, which is firewood and wood transformed into charcoal.
maintenance Hotel Preventive Maintenance Software is, in turn, not Worldwide wood fuel totals amounted to around 1.86 million
activities to available for
help prevent When your team has installed and is using some type of hotel cooking. It is m³ in 2010. Asia is the region with the highest production of
unexpected maintenance software or platform, hotel management and preferable to wood fuels, accounting for 771 million m³ or nearly 45% of global
KEYWORDS
failures in the authorized maintenance personnel are able to maintain much- avoid using wet
future. production. This is strongly driven by China and India which
needed visibility into the status of all maintenance programs fuel and allow
the sun to dry together consume one quarter of global woodfuel consumption.
and procedures. This includes the status of your equipment and Due to substitution for other fuels, the Asian consumption
it rather than
how it’s functioning, relevant work orders, and vital notes and unnecessarily of woodfuel has decreased by 3.2% from 2005 -2010. Wood
data left by maintenance staff related to all of your hotel’s most waste energy
fuel consumption in Africa and Latin America continue to grow.
important assets that require regular maintenance. on evaporating
water.
Presently, climate policies in Europe and North America
3G E-LEARNING
v
DID YOU KNOW? Start with Your Business Name 35 Start with Your Business Name 19
EXAMPLE
the signature (©) with your name and year created on all of your
Here are a couple of things that you can do instead: Know?
materials, but doing so could potentially help you win your case. Finding
■ If it is a parked domain, consider buying it. It’s probably the right name
going to cost you, but a search-friendly, memorable for your startup
Trademark can have a
domain is worth it. significant impact
Business and product owners use trademarks for names, logos,
How do you trademark a business name and logo? 1.3 BRANDING A BUSINESS NAME
Nowadays, companies around the world (with minor exceptions)
To register a trademark in the U.S., you have to file an application are recognized as legal entities, which mean that companies are
with the United States Patent Trademark Office (USPTO), the authorized to make autonomous decisions regarding business
federal agency that governs the enforceability of trademark activities. As a rule, they are registered and may independently
ROLE MODEL 82 Digital Skills for Small Business Secure Your Domain Name 83
Role Models are important because they give Paul Mockapetris was born on 18 November, 1948 in Boston
Massachusetts. He received BS degrees in Physics and Electrical
Company also used several retail registrars from legacy relationships acquired over
the years by IT, digital marketing and as a result of M&A activity.
Engineering from MIT in 1971, and a PhD in Information and
CASE STUDY At USC’s Information Science Institute, Paul started as a research assistant and
eventually headed the Communications division. During this time Paul’s research
included work on many of the fundamental internet protocols, including development
of the first SMTP server, and later the invention of the Domain Name System, and
The rapid expansion of generic top-level domains (gTLDs) made it apparent to
Company leadership that domain management was becoming more complex and total
cost of ownership was increasing, in part due to having multiple vendors. Company
also recognized that slow, manual and non-integrated domain management processes
provide an opportunity for the development manager for networking at ARPA, and 2 years as IETF chair, as well as numerous
other roles. 1. Vendor consolidation for greater operational efficiency;
2. Cost reduction (internal and vendor cost);
of key skills such as communication, group In 1995, Paul left academia, and took leadership roles at startups including cable
internet at @Home, email at [Link]/Openwave, integrated SONET and IP products
at Fiberlane/Cerent/Siara.
3. Enhanced business intelligence (to gain competitive advantage in the market.)
REVIEW QUESTIONS
a. 10
b. 12 Secure Your Domain Name 89
c. 16
REFERENCES
d. none of the above
1. Department of Revenue Washington State. “Domain Name Registration Services.”
REFERENCES
6. DNS can use the services of ________ using the well-known port 53. Accessed Dec. 20, 2019.
a. UDP 8. [Link]. “About Symbolics.” Accessed Dec. 20, 2019.
b. TCP 9. Verisign. “Verisign Q1 2019 Domain Name Industry Brief.” Accessed Dec. 20, 2019.
c. either (a) or (b) 10. [Link]. “Terms and Conditions of [Link].” Accessed Dec. 20, 2019.
vi
TABLE OF
CONTENTS Preface xiii
Chapter 1 Programming in C 1
Introduction 2
1.1 Character Set 2
1.1.1 Structure of a ‘C’ Program 3
1.2 Data Types in ‘C’ 5
1.2.1 Basic Data Types 6
1.2.2 Data Kinds in C 7
1.3 Operators 13
1.4 Expressions 22
1.4.1 Statements 23
1.4.2 Assignment Statement 27
1.4.3 Conditional Statements 27
1.5 Structure for Looping
Statements 33
1.5.1 Nested Looping Statements 38
1.5.2 Multi Branching Statement (switch),
Break, and Continue 39
1.5.3 Differences between Break and Continue 41
1.5.4 Go to Statement 41
Summary 46
Multiple Choice Questions 46
Review Questions 47
References 48
Chapter 2 An Overview of Object-Oriented
Programming in C++ 49
Introduction 50
2.1 Need to Object-Oriented Programming 50
2.1.1 Procedural Languages 51
2.1.2 Division into Functions 51
2.1.3 Unrestricted Access 51
2.1.4 The Object-Oriented Approach 53
2.1.5 OOP: An Approach to Organization 54
2.2 Characteristics of Object-Oriented Languages 55
2.2.1 Objects 55
2.2.2 Data-Storage Constructs 55
2.2.3 Classes 56
2.2.4 Inheritance 57
2.2.5 Reusability 58
2.2.6 Creating New Data Types 59
2.2.7 Polymorphism and Overloading 59
2.3 C++ and C 59
2.3.1 Laying the Groundwork 60
2.3.2 The Unified Modeling Language (UML) 60
2.4 C++ Programming Basics 61
2.4.1 Basic Program Construction 61
2.4.2 Functions 61
2.4.3 Program Statements 63
2.4.4 Whitespace 63
2.4.5 Output Using cout 64
2.5 Basic Data Types in C++ 65
2.5.1 Built-in-type 65
2.5.2 Derived Data types 67
2.5.3 Variables in C++ 68
2.6 Operators in C++ 70
Summary 84
Multiple-Choice Questions 84
Review Questions 85
References 86
viii
Chapter 3 HTML 87
Introduction 88
3.1 HTML Overview 88
3.2 HTML Tag 90
3.2.1 Logical vs. Physical Tags 90
3.2.2 Basic HTML Tags 91
3.2.3 Other HTML Tags 93
3.2.4 HTML Character Entities 94
3.3 HTML Fonts 95
3.3.1 HTML Backgrounds 96
3.4 HTML Color 100
3.5 HTML Lists 102
3.6 HTML Links 104
3.7 HTML Images 107
3.8 HTML Tables 110
Summary 117
Multiple Choice Questions 117
Review Questions 118
References 119
ix
Chapter 5 Cascading Style Sheets (CSS) 165
Introduction 166
5.1 Overview of CSS 166
5.1.1 Advantages of CSS 167
5.1.2 Who Creates and Maintains CSS? 167
5.2 Inline Styles 168
5.2.1 Embedded Style Sheets 169
5.3 Conflicting Styles 173
5.4 Linking External Style Sheets 175
5.4.1 W3C CSS Validation Service 177
5.5 Positioning Elements 178
5.6 Backgrounds 181
5.7 Element Dimensions 184
5.8 Text Flow and the Box Model 185
5.9 User Style Sheets 191
Summary 195
Multiple Choice Questions 195
Review Questions 197
References 198
xi
7.6.4 JavaScript For-In Loop 287
7.7 Functions 290
7.7.1 Calling a Function 291
7.7.2 Function Parameters 292
7.7.3 The Return Statement 293
7.7.4 Nested Functions 295
7.7.5 Function () Constructor 296
7.8 JavaScript Objects 298
7.8.1 Creating Objects in JavaScript 298
7.8.2 Method in JavaScript Object 300
7.8.3 Arrays 301
7.8.4 String 304
7.8.5 String Methods 305
Summary 312
Multiple Choice Questions 312
Review Questions 313
References 314
Index 315
xii
PREFACE
In the 1990’s majority of web pages were static and intended primarily for
reading and browsing while the first decade of the new century brings more
dynamic web pages and applications. Users not only “browse” the Web but
also contribute to it by producing and up-loading their own content. The
so-called Web 2.0 evolved and brought some major changes also in web
development. The new way of interaction with Web calls also for the evolution
of web languages with the main intention to formalize some of the already
established good practices in web development. At present, many tools are
used for software development. These tools differ in their functionalities and
programming convenience, as well as they are not without disadvantages,
that often appear only in development stage, when system extension or
modules integrating. Therefore, it is an important task to choose toolset and
programming technologies in the planning stage. This choice should satisfy the
software requirements and programming process. In this case, it is necessary
to consider the parameters of the technologies, the guaranteed quality of
data processing, and reliability with extension. In this book we summarize
some important novelties in new web standards and protocols. This book is
comprised of seven chapters.
Chapter 1 presents a focus on Programming in C. C’ is high level language
and is the upgraded version of another language (Basic Combined Program
Language).
Chapter 2 presents an overview of Object-Oriented Programming in C++.
C++ also added several other improvements to the C language, including an
extended set of library routines. However, much of the spirit and flavor of
C++ is directly inherited from C. Therefore, to fully understand and appreciate
C++, you need to understand the “how and why” behind C.
Chapter 3 presents an overview of HTML. HTML is a formal Recommendation
by the World Wide Web Consortium (W3C) and is generally adhered to by
the major browsers, Microsoft’s Internet Explorer and Netscape’s Navigator,
which also provide some additional non-standard codes.
Chapter 4 focuses on XHTML. The plethora of documents already marked up with HTML,
or the infrastructure of knowledge, tools, and technologies that currently support HTML
and the Web. Yet, we do not want to miss the opportunities of XML, either. XHTML is the
bridge. It uses the features of XML to define a markup language that is nearly identical
to standard HTML 4.01 and gets us all started down the XML road.
Chapter 5 sheds light on Cascading Style Sheets (CSS). Define backgrounds, element
dimensions and text flow and the box model. CSS gives more control over the appearance
of a Web page to the page creator than to the browser designer or the viewer.
Chapter 6 focuses on PHP. With PHP, you can do things like create username and password
login pages, check details from a form, create forums, picture galleries, surveys, and a
whole lot more. If you’ve come across a web page that ends in PHP, then the author has
written some programming code to liven up the plain, old HTML.
Chapter 7 is JavaScript Programming. JavaScript is a dynamic computer programming
language. It is lightweight and most commonly used as a part of web pages, whose
implementations allow client-side script to interact with the user and make dynamic pages.
CHAPTER PROGRAMMING IN C
1
“when you don’t create things, you become defined by your tastes rather than ability. your tastes only
narrow & exclude people. so create.”
- The Lucky Stiff
LEARNING OBJECTIVES
INTRODUCTION
‘C’ is high level language and is the upgraded version of another language (Basic
Combined Program Language). C language was designed at Bell laboratories in the
early 1970’s by Dennis Ritchie. C being popular in the modern computer world can
be used in Mathematical Scientific, Engineering and Commercial applications.
The most popular Operating system UNIX is written in C language. This language
also has the features of low level languages and hence called as “System Programming
Language”.
C belongs to the structured, procedural paradigms of languages. It is proven,
flexible and powerful and may be used for a variety of different applications. Although
high-level, C and assembly language share many of the same attributes.
Following are C programming language features:
■■ Fixed number of keywords, including a set of control primitives, such as if,
for, while, switch and do while
■■ Multiple logical and mathematical operators, including bit manipulators
■■ Multiple assignments may be applied in a single statement.
■■ Function return values are not always required and may be ignored if unneeded.
■■ Typing is static. All data has type but may be implicitly converted.
■■ Basic form of modularity, as files may be separately compiled and linked
■■ Control of function and object visibility to other files via extern and static
attributes
3G E-LEARNING
Programming in C 3
useful to build the programs. The C language consists of two character sets namely –
source character set execution character set. Source character set is useful to construct
the statements in the source program. Execution character set is employed at the time
of execution of h program.
1. Source character set: This type of character set includes three types of characters
namely alphabets, Decimals and special symbols.
■■ Alphabets : A to Z, a to z and Underscore( _ )
■■ Decimal digits : 0 to 9
■■ Special symbols: + - * / ^ % = & ! ( ) { } [ ] “ etc
2. Execution character set: This set of characters are also called as non-graphic characters
because these are invisible and cannot be printed or displayed directly.
These characters will have effect only when the program being executed. These
characters are represented by a back slash (\) followed by a character.
3G E-LEARNING
4 Introduction to Computer Programming and Web Designing
Preprocessor Statements
These statements begin with # symbol. They are called preprocessor
directives. These statements direct the C preprocessor to include
header files and also symbolic constants in to C program. Some
of the preprocessor statements are
#include<stdio.h>: for the standard input/output functions
#include<test.h>: for file inclusion of header file Test.
#define NULL 0: for defining symbolic constant NULL = 0 etc.
Keyword
Global Declaration
Function
is a group Variables or functions whose existence is known in the main
of statements
that together () function and other user defined functions are called global
perform a task. variables (or functions) and their declarations is called global
It is declaration declaration. This declaration should be made before main().
tells the compiler
about a function’s
name, return
type, and main()
parameters.
As the name itself indicates it is the main function of every
C program. Execution of C program starts from main (). No
C program is executed without main() function. It should be
written in lowercase letters and should not be terminated by a
semicolon. It calls other Library functions user defined functions.
There must be one and only one main() function in every C
program.
Braces
Every C program uses a pair of curly braces ({,}0. The left brace
indicates beginning of main() function. On the other hand, the
right brace indicates end of the main() function. The braces can
also be used to indicate the beginning and end of user-defined
functions and compound statements.
Declarations
It is part of C program where all the variables, arrays, functions
etc., used in the C program are declared and may be initialized
with their basic data types.
3G E-LEARNING
Programming in C 5
Statements
These are instructions to the specific operations. They may be
input-output statements, arithmetic statements, control statements
and other statements. They are also including comments.
User-defined functions
These are subprograms. Generally, a subprogram is a function,
and they contain a set of statements to perform a specific
task. These are written by the user; hence the name is user-
defined functions. They may be written before or after the
main() function.
3G E-LEARNING
6 Introduction to Computer Programming and Web Designing
Character Data
Any character of the ASCII character set can be considered as
a character data types and its maximum size can be 1 byte or
8 byte long. ‘Char’ is the keyword used to represent character
data type in C.
Char - a single byte size, capable of holding one character
Integer Data
The keyword ‘int’ stands for the integer data type in C and its
size is either 16 or 32 bits. The integer data type can again be
Remember classified as
In early
versions ■■ Long int - long integer with more digits
of C, only
functions that ■■ Short int - short integer with fewer digits.
return types ■■ Unsigned int - Unsigned integer
other than int
must be declared ■■ Unsigned short int – Unsigned short integer
if used before
the function
■■ Unsigned long int – Unsigned long integer
definition; The qualifiers like short, long, signed or unsigned can be
functions used applied to basic data types to derive new data types.
without prior
declaration were int - an Integer with the natural size of the host machine.
presumed to
return type int.
Floating Point Data
The numbers which are stored in floating point representation
with mantissa and exponent are called floating point (real)
numbers. These numbers can be declared as ‘float’ in C.
float – Single – precision floating point number value.
Double Data
Double is a keyword in C to represent double precision floating
point numbers.
3G E-LEARNING
Programming in C 7
Numeric Constants
Numeric constants, as the name itself indicates, are those which
consist of numerals, an optional sign and an optional period.
They are further divided into two types:
(a) Integer Constants Keyword
(b) Real Constants Integer
constants
are constant
Integer Constants data elements
that have no
A whole number is an integer constant Integer constants do not fractional parts or
have a decimal point. These are further divided into three types exponents. They
always begin
depending on the number systems they belong to. They are: with a digit.
■■ Decimal integer constants
■■ Octal integer constants
■■ Hexadecimal integer constants
i. A decimal integer constant is characterized by the following
properties
■■ It is a sequence of one or more digits ([0…9], the symbols
of decimal number system).
3G E-LEARNING
8 Introduction to Computer Programming and Web Designing
3G E-LEARNING
Programming in C 9
Real Constants
The real constants also known as floating point constants are written in two forms:
■■ Fractional form
■■ Exponential form.
i. Fractional Form
The real constants in Fractional form are characterized by the following characteristics:
■■ Must have at least one digit.
■■ Must have a decimal point.
■■ May be positive or negative and in the absence of sign taken as positive.
■■ Must not contain blanks or commas in between digits.
■■ May be represented in exponential form, if the value is too higher or too low.
Some examples of valid real constants:
456.78
-123.56
Some examples of invalid real constants:
4.56 - Blank spaces are not permitted
3G E-LEARNING
10 Introduction to Computer Programming and Web Designing
In the above examples, 0.56 and 0.234 are the mantissa parts of the first and second
numbers, respectively, and 8 and -6 are the exponent parts of the first and second
number, respectively.
The real constants in exponential form and characterized by the following
characteristics:
■■ The mantissa must have at least one digit.
■■ The mantissa is followed by the letter E or e and the exponent.
■■ The exponent must have at least one digit and must be an integer.
■■ A sign for the exponent is optional.
Some examples of valid real constants:
3E4
23e-6
0.34E6
Some examples of invalid real constants:
23E - No digit specified for exponent
23e4.5 - Exponent should not be a fraction
3G E-LEARNING
Programming in C 11
Character Constants
Any character enclosed with in single quotes (‘) is called character constant. A character
constant:
■■ May be a single alphabet, single digit or single special character placed with
in single quotes.
■■ Has a maximum length of 1 character.
Here are some examples,
■■ ‘C’
■■ ‘c’
■■ ‘:’
■■ ‘*’
String Constants
A string constant is a sequence of alphanumeric characters enclosed in double quotes
whose maximum length is 255 characters. Following are the examples of valid string
constants:
■■ “My name is Krishna”
■■ “Bible”
■■ “Salary is 18000.00”
Following are the examples of invalid string constants:
My name is Krishna - Character are not enclosed in double quotation marks.
“My name is Krishna - Closing double quotation mark is missing.
‘My name is Krishna’ - Characters are not enclosed in double quotation marks
b. Reserve Words/Keywords
In C language, some words are reserved to do specific tasks intended for them and
are called Keywords or Reserve words. The list reserve words are
3G E-LEARNING
12 Introduction to Computer Programming and Web Designing
c. Delimiters
This is symbol that has syntactic meaning and has got significance. These will not
specify any operation to result in a value. C language delimiters list is given are:
d. Variables / Identifiers
These are the names of the objects, whose values can be changed during the program
execution. Variables are named with description that transmits the value it holds.
[A quantity of an item, which can be change its value during the execution of
program is called variable. It is also known as Identifier].
3G E-LEARNING
Programming in C 13
1.3 OPERATORS
An Operator is a symbol that operates on a certain data type. The data items that
operators act upon are called operands. Some operators require two operands, some
operators act upon only one operand. In C, operators can be classified into various
categories based on their utility and action.
■■ Arithmetic Operators
■■ Relational Operators
■■ Logical Operator
■■ Assignment Operator
■■ Increment & Decrement Operator
■■ Conditional Operator
■■ Bitwise Operator
■■ Comma Operator
3G E-LEARNING
14 Introduction to Computer Programming and Web Designing
Arithmetic Operators
The Arithmetic operators performs arithmetic operations. The Arithmetic operators can
operate on any built in data type. A list of arithmetic operators are
Relational Operators
Relational Operators are used to compare arithmetic, logical and character expressions.
The Relational Operators compare their left hand side expression with their right hand
side expression. Then evaluates to an integer. If the Expression is false it evaluate to
“zero” (0) if the expression is true it evaluate to “one”
Examples:
Expression Evaluate to
3G E-LEARNING
Programming in C 15
Logical Operators
A logical operator is used to evaluate logical and relational expressions. The logical
operators act upon operands that are themselves logical expressions. There are three
logical operators.
Logical And (&&): A compound Expression is true when two expression when
two expressions are true. The && is used in the following manner.
Exp1 && Exp2.
The result of a logical AND operation will be true only if both operands are true.
The results of logical operators are:
Exp1 Op. Exp2 Result
True && True True
True && False False
3G E-LEARNING
16 Introduction to Computer Programming and Web Designing
Logical OR: A compound expression is false when all expression are false otherwise
the compound expression is true. The operator “||” is used as It evaluates to true if
either exp-1 or exp-2 is true. The truth table of “OR” is Exp1 || Exp2
Logical NOT: The NOT ( ! ) operator takes single expression and evaluates to
true(1) if the expression is false (0) or it evaluates to false (0) if expression is true (1).
The general form of the expression.
! ( Relational Expression )
The truth table of NOT :
Operator. Exp1 Result
! True False
! False True
3G E-LEARNING
Programming in C 17
Example: a = 5; b = 10; c = 15
1. !( a< b ) False
2. !( a> b ) True
Assignment Operator
An assignment operator is used to assign a value to a variable.
The most commonly used assignment operator is =. The general
format for assignment operator is:
< Identifer >= < expression >
3G E-LEARNING
18 Introduction to Computer Programming and Web Designing
2. I - = 5 I = I - 5 10
3. I * = 5 I = I * 5 50
4. I / = 5 I = I / 5 10
Example: ++ a; Pre-increment (or) a++ Post increment —a; Pre-Decrement (or) a— Post
decrement
1. ++ a Immediately increments the value of a by 1.
2. a ++ The value of the a will be increment by 1 after it is utilized.
Example 1: Suppose a = 5 ;
Statements Output
printf ( “a value is %d”, a ); a value is 5
printf ( “a value is %d”, ++ a ); a value is 6
printf ( “a value is %d “, a) ; a value is 6
Example 2: Suppose : a = 5 ;
Statements Output
printf (“a value is %d “, a); a value is 5
printf (“a value is %d “, a++); a value is 5
printf (“a value is %d “,a); a value is 6
3G E-LEARNING
Programming in C 19
2. a = 3; b = 3;
(a> b ? printf (“a is larger”) : printf (“b is larger”));
Output is :b is larger
Bitwise Operator
A bitwise operator operates on each bit of data. These bitwise operator can be divided
into three categories.
■■ The logical bitwise operators.
■■ The shift operators
■■ The one’s complement operator
3G E-LEARNING
20 Introduction to Computer Programming and Web Designing
i) The logical Bitwise Operator: There are three logical bitwise operators.
Meaning Operator:
a) Bitwise AND &
b) Bitwise OR |
c) Bitwise exclusive XOR ^
Suppose b1 and b2 represent the corresponding bits with in the first and second
operands, respectively.
B1 B2 B1 & B2 B1 | B2 B1 ^ B2
11110
10011
01011
00000
The operations are carried out independently on each pair of corresponding bits
within the operand thus the least significant bits (ie the right most bits) within the
two operands. Will be compared until all the bits have been compared. The results of
these comparisons are
A Bitwise AND expression will return a 1 if both bits have a value of 1. Other
wise, it will return a value of 0.
A Bitwise OR expression will return a 1 if one or more of the bits have a value
of 1. Otherwise, it will return a value of 0.
A Bitwise EXCLUSIVE OR expression will return a 1 if one of the bits has a value
of 1 and the other has a value of 0. Otherwise, if will return a value of 0.
Example::Variable Value Binary Pattern
3G E-LEARNING
Programming in C 21
X 5 0101
Y 2 0010
X & Y 0 0000
X | Y 7 0111
X ^ Y 7 0111
ii) The Bitwise shift Operations: The two bitwise shift operators are Shift left (<<) and
shift right (>>). Each operator requires two operands. The first operand that represents
the bit pattern to be shifted. The second is an unsigned integer that indicates the
number of displacements.
Example: c = a << 3;
The value in the integer a is shifted to the left by three bit position. The result is
assigned to the c.
A = 13; c= A<<3;
Left shit << c= 13 * 2 3 = 104;
Binary no 0000 0000 0000 1101
After left bit shift by 3 places ie,. a<<3
0000 0000 0110 1000
The right –bit – shift operator ( >> ) is also a binary operator
Example: c = a >> 2 ;
The value of a is shifted to the right by 2 position
insert 0’s Right – shift >> drop off 0’s
0000 0000 0000 1101
After right shift by 2 places is a>>2
0000 0000 0000 0011 c=13>>2
c= 13/4=3
iii) Bit wise complement: The complement op.~ switches all the bits in a binary pattern,
that is all the 0’s becomes 1’s and all the 1’s becomes 0’s.
3G E-LEARNING
22 Introduction to Computer Programming and Web Designing
Comma Operator
A set of expressions separated by using commas is a valid construction in c language.
Example :int i, j;
i= ( j = 3, j + 2 ) ;
Size of operator: The operator size operator gives the size of the data type or variable
in terms of bytes occupied in the memory. This operator allows a determination of
the no of bytes allocated to various Data items
1.4 EXPRESSIONS
An expression can be defined as collection of data object and operators that can be
evaluated to lead a single new data object. A data object is a constant, variable or
another data object.
3G E-LEARNING
Programming in C 23
Example:
a+b
x + y + 6.0
3.14 * r * r
( a + b ) * ( a – b)
Keyword
Arithmetic
operator is a
The above expressions are called as arithmetic expressions mathematical
function that
because the data objects (constants and variables) are connected takes two
using arithmetic operators. operands and
performs a
Evaluation Procedure: The evaluation of arithmetic calculation on
expressions is as per the hierarchy rules governed by the C them. They are
used in common
compiler. The precedence or hierarchy rules for arithmetic arithmetic and
expressions are most computer
languages
1. The expression is scanned from left to right. contain a set of
such operators
2. While scanning the expression, the evaluation preference that can be used
for the operators are within equations
to perform a
number of types
of sequential
calculation.
3. To overcome the above precedence rules, user has to
make use of parenthesis. If parenthesis is used, the
expression/ expressions with in parenthesis are evaluated
first as per the above hierarchy.
1.4.1 Statements
3G E-LEARNING
24 Introduction to Computer Programming and Web Designing
getchar()
Single characters can be entered into the computer using the C library Function
getchar(). It returns a single character from a standard input device. The function does
not require any arguments.
Syntax: <Character variable> = getchar();
Example: char c;
c = getchar();
putchar()
Single characters can be displayed using function putchar(). It returns a single character
to a standard output device. It must be expressed as an argument to the function.
Syntax: putchar(<character variable>);
Example: char c;
————
putchar(c);
gets()
The function gets() receives the string from the standard input device.
Syntax: gets(<string type variable or array of char> );
Where s is a string.
The function gets accepts the string as a parameter from the keyboard, till a newline
character is encountered. At end the function appends a “null” terminator and returns.
puts()
The function puts() outputs the string to the standard output device.
3G E-LEARNING
Programming in C 25
Syntax: puts(s);
scanf()
Scanf() function can be used input the data into the memory from the standard input
device. This function can be used to enter any combination of numerical Values, single
characters and strings. The function returns number of data items.
Syntax:-scanf (“control strings”, &arg1,&arg2,——&argn);
Where control string referes to a string containing certain required formatting information
and arg1, arg2——argn are arguments that represent the individual input data items.
Example:
#include<stdio.h>
main()
{
char item[20];
intpartno;
float cost;
scanf(“%s %d %f”,&item,&partno,&cost);
}
3G E-LEARNING
26 Introduction to Computer Programming and Web Designing
Where s, d, f with % are conversion characters. The conversion characters indicate the
type of the corresponding data. Commonly used conversion characters from data input.
Conversion Characters
printf()
The printf() function is used to print the data from the computer’s memory onto
a standard output device. This function can be used to output any combination of
numerical values, single character and strings.
Syntax: printf(“control string”, arg-1, arg-2,———arg-n );
Where control string is a string that contains formatted information, and arg-1,
arg-2 —— are arguments that represent the output data items.
Example:
#include<stdio.h>
main()
{
char item[20];
intpartno;
3G E-LEARNING
Programming in C 27
float cost;
———————
printf (“%s %d %f”, item, partno, cost);
} (Where %s %d %f are conversion characters.)
if statement
The if statement is used to express conditional expressions. If the given condition is
true then it will execute the statements otherwise skip the statements.
The simple structure of ‘if’ statement is
i. If (< condtional expressione>)
statement-1;
3G E-LEARNING
28 Introduction to Computer Programming and Web Designing
(or)
ii. If (< condtional expressione>)
{
statement-1;
statement-2;
statement-3;
……………
……………
STATEMENT-N
}
The expression is evaluated and if the expression is true the statements will be executed.
If the expression is false the statements are skipped and execution continues with the
next statements.
Example:
a=20; b=10;
if ( a > b )
printf (“big number is %d” a);
if-else Statements
The if-else statements is used to execute the either of the two statements depending
upon the value of the exp. The general form is
if(<exp>)
{
Statement-1;
Statement -2;
………….. “ SET-I”
3G E-LEARNING
Programming in C 29
……………
Statement- n;
}
else
{
Statement1;
Statement 2;
………….. “ SET-II
……………
Statement n;
}
Example:
if ( a> b )
printf (“a is greater than b”);
else
printf (“a is not greater than b”);
Nested else-if statements
If some situations if may be desired to nest multiple if-else statements. In this situation
one of several different course of action will be selected.
Syntax
if ( <exp1> )
Statement-1;
3G E-LEARNING
30 Introduction to Computer Programming and Web Designing
else if ( <exp2> )
Statement-2;
else if ( <exp3> )
Statement-3;
else
Statement-4;
When a logical expression is encountered whose value is true the corresponding
statements will be executed and the remainder of the nested else if statement will be
bypassed. Thus control will be transferred out of the entire nest once a true condition
is encountered.
The final else clause will be apply if none of the exp is true.
nestedif-else statement
It is possible to nest if-else statements, one within another. There are several different
form that nested if-else statements can take.
The most general form of two-layer nesting is
if(exp1)
if(exp3)
Statement-3;
else
Statement-4;
else
if(exp2)
Statement-1;
else
Statement-2;
3G E-LEARNING
Programming in C 31
One complete if-else statement will be executed if expression1 is true and another
complete if-else statement will be executed if expression1 is false.
Switch Statement
A switch statement is used to choose a statement (for a group of statement) among
several alternatives. The switch statements is useful when a variable is to be compared
with different constants and in case it is equal to a constant a set of statements are
to be executed.
Syntax:
Switch (exp)
{
case
constant-1:
statements1;
case
constant-2:
statements2;
———
———
default:
statement n;
}
3G E-LEARNING
32 Introduction to Computer Programming and Web Designing
Example:
main()
{
char choice;
printf(“Enter Your Color (Red - R/r, White – W/w)”);
choice=getchar();
switch(choice= getchar())
{
case‘r’:
case‘R’:
printf (“Red”);
break;
case‘w’:
case‘W’:
printf (“white”);
break;
default :
printf (“no colour”);
}
Example 2:
switch(day)
{
case 1:
printf (“Monday”);
break;
3G E-LEARNING
Programming in C 33
———
———
}
While Statement
while loop will be executed as long as the exp is true.
Syntax: while (exp)
{
statements;
}
Example:
int digit = 1;
While (digit <=5) FALSE
{
printf (“%d”, digit); TRUE
Cond Exp
3G E-LEARNING
34 Introduction to Computer Programming and Web Designing
Statements; ++digit;
}
The while loop is top tested i.e., it evaluates the condition before executing statements in
the body. Then it is called entry control loop.
do-while statement
The do-while loop evaluates the condition after the execution of the statements in the
body.
Syntax: do
Statement;
While<exp>;
Here also the statements will be executed as long as the exp value is true. If the expression
is false the control come out of the loop.
Example:
-int d=1;
do
{
printf (“%d”, d); FALSE
++d;
} while (d<=5); TRUE
Cond Exp
statements
exit
3G E-LEARNING
Programming in C 35
for statement
The for loop is used to executing the structure number of times.
Remember
The for loop includes three expressions. First expression specifies
Generally
an initial value for an index (initial value), second expression for loop
that determines whether or not the loop is continued (conditional used when the
statement) and a third expression used to modify the index number of passes
(increment or decrement) of each pass. is known in
advance.
Syntax: for (exp1;exp2;exp3)
{
Statement –1;
Statement – 2;
—————; FALSE
—————;
Statement - n; TRUE
}
exp2
Statements;
exp3
Exit loop
exp1
start
3G E-LEARNING
36 Introduction to Computer Programming and Web Designing
Formate - I
for( ; exp2; exp3 )
Statements;
In this format the initialization expression (i.e., exp1) is omitted. The initial value of the
variable can be assigned outside of the for loop.
Example 1
int i = 1;
for( ; i<=10; i++ )
printf (“%d \n”, i);
Formate - II
for( ; exp2 ; )
Statements;
In this format the initialization and increment or decrement expression (i.e expression-1
and expression-3) are omitted. The exp-3 can be given at the statement part.
Example 2
int i = 1;
for( ; i<=10; )
3G E-LEARNING
Programming in C 37
{
printf (“%d \n”,i);
i++;
}
Formate - III
for( ; ; )
Statements;
In this format the three expressions are omitted. The loop itself assumes the expression-
2is true. So Statements will be executed infinitely.
Example 3
int i = 1;
for ( ; i<=10; )
{
printf (“%d \n”,i);
i++;
}
3G E-LEARNING
38 Introduction to Computer Programming and Web Designing
3G E-LEARNING
Programming in C 39
Break Statement
The break statement is used to terminate the control form the loops or to exit from a
switch. It can be used within a for, while, do-while, for.
The general format is:
break;
If break statement is included in a while, do-while or for then control will immediately
be transferred out of the loop when the break statement is encountered.
Example
for ( ; ; ) normal loop
{
break
Condition
within loop
scanf (“%d”,&n);
if ( n < -1)
break;
sum = sum + n;
}
3G E-LEARNING
40 Introduction to Computer Programming and Web Designing
through the loop. The “continue” that can be included with in a while a do-while and
a for loop statement.
General form :
continue;
The continue statement is used for the inverse operation of the break statement.
Condition
with in loop
Remaining part of loop
continue
Example
while (x<=100)
{
if (x <= 0)
{
printf (“zero or negative value found \n”);
continue;
}
}
The above program segment will process only the positive whenever a zero or negative
value is encountered, the message will be displayed and it continue the same loop as
long as the given condition is satisfied.
3G E-LEARNING
Programming in C 41
1.5.4 Go to Statement
The go to statement is used to alter the program execution sequence by transferring
the control to some other part of the program.
Syntax
Where label is an identifier used to label the target statement to which the control would
be transferred the target statement will appear as:
Syntax
goto<label>;
label :
statements;
Example
#include <stdio.h>
main();
{
inta,b;
printf (“Enter the two numbers”);
scanf (“%d %d”,&a,&b);
3G E-LEARNING
42 Introduction to Computer Programming and Web Designing
if (a>b)
gotobig;
else
gotosmall;
big :printf (“big value is %d”,a);
gotostop;
small :printf (“small value is %d”,b);
gotostop;
stop;
}
3G E-LEARNING
Programming in C 43
ROLE MODEL
DENNIS RITCHIE: COMPUTER LANGUAGES AND
OPERATING SYSTEMS
Dennis MacAlistair Ritchie (born 1941) is best known for his work
on computer languages and operating systems ALTRAN, B, BCPL,
C, Multics, and especially Unix. For a man who did not start
out in the computer industry, he has had a profound influence
on the entire computer programming world. He told Investor’s
Business Daily , “It’s not the actual programming that’s interesting.
But it’s what you can accomplish with the end results that are
important.” And if that is the case, then Ritchie has had an
important effect on most, if not all, computer users today.
3G E-LEARNING
44 Introduction to Computer Programming and Web Designing
3G E-LEARNING
Programming in C 45
3G E-LEARNING
46 Introduction to Computer Programming and Web Designing
SUMMARY
■■ The most popular Operating system UNIX is written in C language. This
language also has the features of low level languages and hence called as
“System Programming Language”.
■■ Derived data types such as arrays, structures, union and pointers and user
defined data types such as typedef and enum.
■■ Numeric constants, as the name itself indicates, are those which consist of
numerals, an optional sign and an optional period.
■■ A string constant is a sequence of alphanumeric characters enclosed in double
quotes whose maximum length is 255 characters.
■■ An Operator is a symbol that operates on a certain data type. The data items
that operators act upon are called operands.
■■ Relational Operators are used to compare arithmetic, logical and character
expressions. The Relational Operators compare their left hand side expression
with their right hand side expression.
■■ A logical operator is used to evaluate logical and relational expressions. The
logical operators act upon operands that are themselves logical expressions.
■■ An expression can be defined as collection of data object and operators that
can be evaluated to lead a single new data object. A data object is a constant,
variable or another data object.
■■ An expression can be defined as collection of data object and operators that
can be evaluated to lead a single new data object. A data object is a constant,
variable or another data object.
■■ Nesting can be defined as the method of embedding one control structure
with in another control structure.
3G E-LEARNING
Programming in C 47
c. -32668 to 32667
d. -32768 to 32767
3. C programs are converted into machine language with the help of
a. An Editor
b. A compiler
c. An operating system
d. None of these.
4. In which numbering system can the binary number 1011011111000101 be easily
converted to?
a. Decimal system
b. Hexadecimal system
c. Octal system
d. No need to convert
5. Which bitwise operator is suitable for turning on a particular bit in a number?
a. && operator
b. & operator
c. || operator
d. | operator
REVIEW QUESTIONS
1. Write about data types used in C.
2. What is Constant? Explain various types of constants in C.
3. Explain various conditional looping statements in C.
4. Differentiate between break and continue.
5. Write a C program to find out smallest value among A, B,C.
6. Write a ‘C’ program to find greatest among three numbers.
3G E-LEARNING
48 Introduction to Computer Programming and Web Designing
REFERENCES
1. Prinz, Peter; Crawford, Tony (December 16, 2005). C in a Nutshell. O’Reilly Media,
Inc. p. 3. ISBN 9780596550714.
2. Fruderica (December 13, 2020). “History of C”. The [Link]. Archived
from the original on October 24, 2020. Retrieved October 24, 2020.
3. “Verilog HDL (and C)” (PDF). The Research School of Computer Science at the
Australian National University. June 3, 2010. Archived from the original (PDF)
on November 6, 2013. Retrieved August 19, 2013. 1980s: ; Verilog first introduced
; Verilog inspired by the C programming language
4. “The name is based off of, and pronounced like the letter C in the English
alphabet”. English Chinese Dictionary. Retrieved November 17, 2022.
5. “C Language Drops to Lowest Popularity Rating”. [Link]. August 9,
2016. Retrieved August 1, 2022.
6. “Programming Language Popularity”. 2009. Archived from the original on January
16, 2009. Retrieved January 16, 2009.
7. “TIOBE Programming Community Index”. 2009. Archived from the original on
May 4, 2009. Retrieved May 6, 2009.
8. “History of C”. [Link]. Archived from the original on May 29,
2018. Retrieved May 28, 2018.
9. “TIOBE Index for October 2021”. Retrieved October 7, 2021.
10. Ritchie, Dennis. “BCPL to B to C”. Archived from the original on December 12,
2019. Retrieved September 10, 2019.
11. Jensen, Richard (December 9, 2020). “”A damn stupid thing to do”—the origins
of C”. Ars Technica. Retrieved March 28, 2022.
3G E-LEARNING
CHAPTER AN OVERVIEW OF
2 OBJECT-ORIENTED
PROGRAMMING IN C++
“Within C++, there is a much smaller and cleaner language struggling to get out.”
-Bjarne Stroustrup
LEARNING OBJECTIVES
INTRODUCTION
The history of C++ begins with C. C++ is built upon the foundation of C. Thus, C++
is a superset of C. C++ expanded and enhanced the C language to support object-
oriented programming (which is described later in this module). C++ also added
several other improvements to the C language, including an extended set of library
routines. However, much of the spirit and flavor of C++ is directly inherited from C.
Therefore, to fully understand and appreciate C++, you need to understand the “how
and why” behind C.
C++ was invented by Bjarne Stroustrup in 1979, at Bell Laboratories in Murray Hill,
New Jersey. He initially called the new language “C with classes” However in 1983 the
name was changed to C++ Stroustrup built C++ on the foundation of C including all of
C’s features attributes and benefits He also adhered to C’s underlying philosophy that
the programmer not the language is in charge t this point it is critical to understand
that Stroustrup did not create an entirely new programming language. Instead, he
enhanced an already highly successful language
Most of the features that Stroustrup added to C were designed to support object-
oriented programming. In essence, C++ is the object-oriented version of C. By building
upon the foundation of C, Stroustrup provided a smooth migration path to OOP. Instead
of having to learn an entirely new language, a C programmer needed to learn only
a few new features before reaping the benefits of the object-oriented methodology.
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 51
3G E-LEARNING
52 Introduction to Computer Programming and Web Designing
Keyword
Variable
is
named memory
locations whose
contents can
change
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 53
3G E-LEARNING
54 Introduction to Computer Programming and Web Designing
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 55
2.2.1 Objects
When you approach a programming problem in an object-oriented language, you no
longer ask how the problem will be divided into functions, but how it will be divided
into objects. Thinking in terms of objects, rather than functions, has a surprisingly
helpful effect on how easily programs can be designed. This results from the close
match between objects in the programming sense and objects in the real world.
What kinds of things become objects in object-oriented programs? The answer to
this is limited only by your imagination, but here are some typical categories to start
you thinking:
Physical Objects
■■ Automobiles in a traffic-flow simulation
■■ Electrical components in a circuit-design program
■■ Countries in an economics model
■■ Aircraft in an air traffic control system
3G E-LEARNING
56 Introduction to Computer Programming and Web Designing
Human Entities
■■ Employees
■■ Students
■■ Customers
■■ Salespeople
Collections of Data
■■ An inventory
■■ A personnel file
■■ A dictionary
■■ A table of the latitudes and longitudes of world cities
2.2.3 Classes
In OOP we say that objects are members of classes. What does this mean? Let us look
at an analogy. Almost all computer languages have built-in data types. For instance, a
data type int, meaning integer, is predefined in C++. You can declare as many variables
of type int as you need in your program:
int day;
int count;
int divisor;
int answer;
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 57
In a similar way, you can define many objects of the same class. A class serves
as a plan, or blueprint. It specifies what data and what functions will be included in
objects of that class. Defining the class does not create any objects, just as the mere
existence of data type int does not create any variables. A class is thus a description
of a number of similar objects. This fits our non-technical understanding of the word
class. Prince, Sting, and Madonna are members of the rock musician class. There is
no one person called “rock musician,” but specific people with specific names are
members of this class if they possess certain characteristics. An object is often called
an “instance” of a class.
2.2.4 Inheritance
The idea of classes leads to the idea of inheritance. In our daily lives, we use the
concept of classes divided into subclasses. We know that the animal class is divided
into mammals, amphibians, insects, birds, and so on. The vehicle class is divided into
cars, trucks, buses, motorcycles, and so on.
Figure 5. Inheritance.
The principle in this sort of division is that each subclass shares common
characteristics with the class from which it is derived. Cars, trucks, buses, and motorcycles
all have wheels and a motor; these are the defining characteristics of vehicles. In
addition to the characteristics shared with other members of the class, each subclass
also has its own particular characteristics: Buses, for instance, have seats for many
people, while trucks have space for hauling heavy loads.
3G E-LEARNING
58 Introduction to Computer Programming and Web Designing
This idea is shown in Figure 5. Notice in the figure that features A and B, which
are part of the base class, are common to all the derived classes, but that each derived
class also has features of its own.
An OOP class can become a parent of several subclasses. In C++ the original class
is called the base class; other classes can be defined that share its characteristics, but
add their own as well. These are called derived classes.
Do not confuse the relation of objects to classes, on the one hand, with the
relation of a base class to derived classes, on the other. Objects, which exist in the
computer’s memory, each embody the exact characteristics of their class, which serves
as a template. Derived classes inherit some characteristics from their base class, but
add new ones of their own. Inheritance is somewhat analogous to using functions to
simplify a traditional procedural program. If we find that three different sections of
a procedural program do almost exactly the same thing, we recognize an opportunity
to extract the common elements of these three sections and put them into a single
function. The three sections of the program can call the function to execute the common
actions, and they can perform their own individual processing as well. Similarly, a
base class contains elements common to a group of derived classes. As functions do
in a procedural program, inheritance shortens an object-oriented program and clarifies
the relationship among program elements.
2.2.5 Reusability
Once a class has been written, created, and debugged, it can be distributed to other
programmers for use in their own programs. This is called reusability. It is similar
to the way a library of functions in a procedural language can be incorporated into
different programs.
However, in OOP, the concept of inheritance provides an important extension to the
idea of reusability. A programmer can take an existing class and, without modifying
it, add additional features and capabilities to it. This is done by deriving a new class
from the existing one. The new class will inherit the capabilities of the old one, but is
free to add new features of its own. For example, you might have written (or purchased
from someone else) a class that creates a menu system, such as that used in Windows
or other Graphic User Interfaces (GUIs). This class works fine, and you do not want
to change it, but you want to add the capability to make some menu entries flash on
and off. To do this, you simply create a new class that inherits all the capabilities of
the existing one but adds flashing menu entries. The ease with which existing software
can be reused is an important benefit of OOP. Many companies find that being able
to reuse classes on a second project provides an increased return on their original
programming investment.
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 59
where the variables position1, position2, and origin each represent a pair of independent
numerical quantities. By creating a class that incorporates these two values, and
declaring position1, position2, and origin to be objects of this class, we can, in effect,
create a new data type. Many features of C++ are intended to facilitate the creation
of new data types in this manner.
3G E-LEARNING
60 Introduction to Computer Programming and Web Designing
The practical differences between C and C++ are larger than you might think.
Although you can write a program in C++ that looks like a program in C, hardly
anyone does. C++ programmers not only make use of the new features of C++, they also
emphasize the traditional C features in different proportions than do C programmers.
If you already know C, you will have a head start in learning C++ (although you may
also have some bad habits to unlearn), but much of the material will be new.
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 61
2.4.2 Functions
Functions are one of the fundamental building blocks of C++. The FIRST program
consists almost entirely of a single function called main(). The only parts of this
program that are not part of the function are the first two lines—the ones that start
with #include and using.
That a function can be part of a class, in which case it is called a member function.
However, functions can also exist independently of classes. We are not yet ready to
talk about classes, so we will show functions that are separate standalone entities, as
main() is here.
Function Name
The parentheses following the word main are the distinguishing feature of a function.
3G E-LEARNING
62 Introduction to Computer Programming and Web Designing
Without the parentheses the compiler would think that main refers to a variable or to
some other program element. When we discuss functions in the text, we will follow
the same convention that C++ uses: We will put parentheses following the function
name. That the parentheses are not always empty. They are used to hold function
arguments: values passed from the calling program to the function.
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 63
2.4.4 Whitespace
We mentioned that the end of a line is not important to a C++ compiler. Actually, the
compiler ignores whitespace almost completely. Whitespace is defined as spaces, carriage
returns, linefeeds, tabs, vertical tabs, and formfeeds. These characters are invisible to
the compiler. You can put several statements on one line, separated by any number of
spaces or tabs, or you can run a statement over two or more lines. It is all the same
to the compiler. Thus the FIRST program could be written this way:
#include <iostream>
using
namespace std;
int main () { cout
<<
3G E-LEARNING
64 Introduction to Computer Programming and Web Designing
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 65
2.5.1 Built-in-type
Integral Type: – The data types in this type are int and char. The modifiers signed,
unsigned, long & short may be applied to character & integer basic data type. The
size of int is 2 bytes and char is 1 byte.
3G E-LEARNING
66 Introduction to Computer Programming and Web Designing
Void function1(void)
iii) In the declaration of generic pointers.
void *gp
A generic pointer can be assigned a pointer value of any basic data type.
int *ip // this is int pointer
gp = ip //assign int pointer to void.
A void pointer cannot be directly assigned to their type pointers in c++ we need
to use cast operator.
Void * ptr1;
Char * ptr2;
ptr2 = ptr1;
is allowed in c but not in c++
ptr2 = (char *)ptr1
is the correct statement
Floating Type: The data types in this are float & double. The size of the float is
4 byte and double is 8 byte. The modifier long can be applied to double & the size
of long double is 10 byte.
User-defined type:
i) The user-defined data type structure and union are same as that of C.
ii) Classes – Class is a user defined data type which can be used just like any
other basic data type once declared. The class variables are known as objects.
iii) Enumeration
a) An enumerated data type is another user defined type which provides a way
of attaching names to numbers to increase simplicity of the code.
b) It uses enum keyword which automatically enumerates a list of words by
assigning them values 0, 1, 2,..etc.
c) Syntax:-
enum shape {
circle,
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 67
square,
triangle
}
d) In C++, enumerated data type has its own separate type. Therefore c++ does not
permit an int value to be automatically converted to an enum value.
shape shapes1 = triangle, // is allowed
shape shape1 = 2; // Error in c++
shape shape1 = (shape)2; //ok
e) By default, enumerators are assigned integer values starting with 0, but we can
over-ride the default value by assigning some other value.
enum colour {red, blue, pink = 3}; //it will assign red to o, blue to 1, & pink to 3 or
enum colour {red = 5, blue, green}; //it will assign red to 5, blue to 6 & green to 7.
2) Functions
Functions in c++ are different than in c there is lots of modification in functions in
c++ due to object orientated concepts in c++.
3) Pointers
Pointers are declared & initialized as in c
int * ip; // int pointer
ip = &x; //address of x through indirection
3G E-LEARNING
68 Introduction to Computer Programming and Web Designing
c++ adds the concept of constant pointer & pointer to a constant pointer
char const *p2 = .HELLO.; // constant pointer
as well as the range of values that can be represented with each one:
Declaration of Variables
C requires all the variables to be defined at the beginning of a scope. But c++ allows the
declaration of variable anywhere in the scope. That means a variable can be declared
right at the place of its first use. It makes the program easier to understand.
In order to use a variable in C++, we must first declare it specifying which data
type we want it to be. The syntax to declare a new variable is to write the specifier
of the desired data type (like int, bool, float...) followed by a valid variable identifier.
For Example:
int a;
float mynumber;
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 69
These are two valid declarations of variables. The first one declares a variable of
type int with the identifier a. The second one declares a variable of type float with
the identifier mynumber. Once declared, the variables a and mynumber can be used
within the rest of their scope in the program.
If you are going to declare more than one variable of the same type, you can
declare all of them in a single statement by separating their identifiers with commas.
For Example:
int a, b, c;
This declares three variables (a, b and c), all of them of type int, and has exactly
the same meaning as:
int a;
int b;
int c;
The integer data types char, short, long and int can be either signed or unsigned
depending on the range of numbers needed to be represented. Signed types can
represent both positive and negative values, whereas unsigned types can only represent
positive values (and zero). This can be specified by using either the specifier signed
or the specifier unsigned before the type name.
For Example:
unsigned short int Number OfSisters;
signed int My Account Balance;
with exactly the same meaning (with or without the keyword signed)
An exception to this general rule is the char type, which exists by itself and is
considered a different fundamental data type from signed char and unsigned char,
3G E-LEARNING
70 Introduction to Computer Programming and Web Designing
thought to store characters. You should use either signed or unsigned if you intend
to store numerical values in a char-sized variable. short and long can be used alone
as type specifiers. They refer to their respective integer fundamental types: short is
equivalent to short int and long is equivalent to long int. The following two variable
declarations are equivalent:
short Year;
short int Year;
Finally, signed and unsigned may also be used as standalone type specifiers,
meaning the same as signed int and unsigned int respectively.
The following two declarations are equivalent:
unsigned NextYear;
unsigned int NextYear;
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 71
c++;
c+=1;
c=c+1;
are all equivalent in its functionality: the three of them increase by one the value of c.
A characteristic of this operator is that it can be used both as a prefix and as a
suffix. That means that it can be written either before the variable identifier (++a) or
after it (a++). Although in simple expressions like a++ or ++a both have exactly the
same meaning, in other expressions in which the result of the increase or decrease
operation is evaluated as a value in an outer expression they may have an important
difference in their meaning: In the case that the increase operator is used as a prefix
(++a) the value is increased before the result of the expression is evaluated and therefore
3G E-LEARNING
72 Introduction to Computer Programming and Web Designing
the increased value is considered in the outer expression; in case that it is used as a
suffix (a++) the value stored in a is increased after being evaluated and therefore the
value stored before the increase operation is evaluated in the outer expression. Notice
the difference:
Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
Outpu //A contains 4 //A contains 3, B contains 4
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 73
instead of using only numeric constants, we can use any valid expression, including
variables. Suppose that a=2, b=3 and c=6,
(a == 5) // evaluates to false since a is not equal to 5.
(a*b >= c) // evaluates to true since (2*3 >= 6) is true.
(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
((b=2) == a) // evaluates to true.
The operator = (one equal sign) is not the same as the operator == (two equal signs),
the first one is an assignment operator (assigns the value at its right to the variable
at its left) and the other one (==) is the equality operator that compares whether both
expressions in the two sides of it are equal to each other. Thus, in the last expression
((b=2) == a), we first assigned the value 2 to b and then we compared it to a, that also
stores the value 2, so the result of the operation is true.
The logical operators && and || are used when evaluating two expressions to
obtain a single relational result. The operator && corresponds with Boolean logical
operation AND. This operation results true if both its two operands are true, and
false otherwise. The following panel shows the result of operator && evaluating the
expression a && b:
3G E-LEARNING
74 Introduction to Computer Programming and Web Designing
&& OPERATOR
a b a && b
true true true
true false false
false true false
false false false
The operator || corresponds with Boolean logical operation OR. This operation results true
if either one of its two operands is true, thus being false only when both operands are false
themselves. Here are the possible results of a || b:
|| OPERATOR
a b a || b
true true true
true false true
false true true
false false false
For Example:
( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
Conditional Operator ( ? )
The conditional operator evaluates an expression returning a value if that expression
is true and a different one if the expression is evaluated as false.
Its format is:
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 75
If condition is true the expression will return result1, if it is not it will return result2.
7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is greater than 3.
a>b ? a : b // returns whichever is greater, a or b.
Comma Operator ( , ):
The comma operator (,) is used to separate two or more expressions that are included
where only one expression is expected. When the set of expressions has to be evaluated
for a value, only the rightmost expression is considered. For example, the following
code: a = (b=3, b+2);
Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the
end, variable a would contain the value 5 while variable b would contain value 3.
sizeof()
This operator accepts one parameter, which can be either a type or a variable itself
and returns the size in bytes of that type or object:
a = sizeof (char);
This will assign the value 1 to a, because char is a one-byte long type.
The value returned by sizeof is a constant, so it is always determined before program
execution.
Some of the new operators in c++ are-
1. :: Scope resolution operators.
2. ::* pointer to member decelerator.
3. →* pointer to member operator.
4. .* pointer to member operator.
5. delete memory release operator.
6. endl Line feed operator
7. new Memory allocation operator.
8. stew Field width operator.
3G E-LEARNING
76 Introduction to Computer Programming and Web Designing
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 77
5) A major application of the scope resolution operator is in the classes to identify the
class to which a member functions belongs.
3G E-LEARNING
78 Introduction to Computer Programming and Web Designing
object created inside a block with new, will remain existence until it is explicitly
destroyed by using delete.
3) It takes following form.
variable = new data type
The new operator allocated sufficient memory to hold a data object of type data-
type & returns the address of the object.
p = new int.
Where p is a pointer of type int. Here p must have already been declared as pointer of
appropriate types.
4) New can be used to create a memory space for any data type including user defined type
such all array, classes etc.
int * p = new int [10]
Creates a memory space for an array of 10 integers.
5) When a data object is no longer needed, it is destroyed to release the memory space for
reuse. The general form is delete variable. If we want to free a dynamically allocated array,
we must use following form.
delete [size] variable
The size specifies the no of elements in the array to be freed.
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 79
CASE STUDY
CASE STUDY 1
My concept has two functions: one produces a value, and the other one later consumes
this value:
3 {
6 [Link](state, buffer);
7 }
How to reflect in a concept that the result of init() is a type that can be later
passed to encode()?
A simple way to do it would be to put a combined expression as one of the concept
requirements:
3 {
4 [Link]([Link](), b);
5 };
But this has limitations. First, if our concept has two “init”
functions init_1() and init_2() producing the value of the same type, and two “encode”
functions encode_1() and encode_2() consuming the value of the same type, we will
need a lot of combined expressions to reflect all the combinations.
Second, if function encode() modifies the state of the object in-place, and its argument
type is an lvalue reference to non-const, such combined expression is actually ill-formed.
3G E-LEARNING
80 Introduction to Computer Programming and Web Designing
3 typename E::state_t& s,
4 span<byte> b)
5 {
7 [Link](s, b);
8 };
Note that I have expressed the nested type requirement in an unusual way. It is
not a separate declaration ending with a semicolon: it is in the “argument list” of
the requires-expression.
3 {
4 typename E::state_t;
6 }
7 && requires(E& e,
8 typename E::state_t& s,
9 span<byte> b)
10 {
11 [Link](s, b);
12 };
This makes the definition shorter, but this was not the reason. I needed to introduce
the name s so that I can use it in the description of member function encode(). Otherwise,
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 81
3 {
4 typename E::state_t;
8 span<byte> b)
9 {
10 [Link](s, b);
11 };
12 };
This is a nested requirement and uses the peculiar requires requires syntax. Another
alternative uses std::declval:
3 {
4 typename E::state_t;
7 };
3G E-LEARNING
82 Introduction to Computer Programming and Web Designing
substitute std::declval<E&>() for e in all the above examples, but using an argument
name makes the declarations easier to read.
Anyway, in all these examples, including the first one, we have to repeat the typename
E::state_t. This is a known inconvenience in C++20 concepts, and solutions are explored
to resolve this problem in the future version of C++.
CASE STUDY 2
In the above example, we were using a buffer of type std::span<std::byte>. Let’s
change our concept a bit, and say that a type models concept Encoder if it has
function encode that works with any type modelling concept Buffer. How do we do
that? We could write something like this:
2 concept Encoder =
3 Buffer<B> &&
5 {
7 [Link](s, b);
8 };
This would compile, and could be used to check if a given encoder works with
a given buffer, but this is not what we wanted. We want to check if an encoder can
encode any type modelling concept Buffer.
Unfortunately, there is no way to do it. And this is not an omission in the concepts
syntax. While this need occurs from time to time when we are doing template meta-
programming, it is not in scope of what we call Generic Programming. In order to test if a
given type (or set of types) satisfies a concept, we have to provide concrete types, and see
if all the necessary declarations are present. Checking if a type satisfies a concept is similar
to instantiating a template (although no template instantiation actually takes place).
If we have an encoder class:
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 83
1 struct MyEncoder
2 {
4 state_t init();
6 };
We can pass it to our concept, and it can test that all expressions are there, by
substituting MyEncode for the template parameter E in concept Encoder:
1 static_assert(Encoder<MyEncoder>);
And once we do it, all types are known and concrete: there is no template anymore.
We could test if our encoder works with one buffer type, or another buffer type, but
there is no way a compiler can check — using template parameter substitution — if
the encoder works with all possible types modelling concept Buffer that were ever
defined or are yet to be defined. This would require an infinite number of tests. This
is somewhat similar to virtual function templates: we do not have them, because it
would require virtual tables of infinite sizes: one slot per any combination of function
arguments’ types.
3G E-LEARNING
84 Introduction to Computer Programming and Web Designing
SUMMARY
■■ A procedural program is divided into functions, and (ideally, at least) each
function has a clearly defined purpose and a clearly defined interface to the
other functions in the program.
■■ Dividing a program into functions and modules is one of the cornerstones
of structured programming, the somewhat loosely defined discipline that
influenced programming organization for several decades before the advent
of object-oriented programming.
■■ The fundamental idea behind object-oriented languages is to combine into a
single unit both data and the functions that operate on that data. Such a unit
is called an object.
■■ The most important elements added to C to create C++ concern classes, objects,
and object-oriented programming.
■■ C++ programmers not only make use of the new features of C++, they also
emphasize the traditional C features in different proportions than do C
programmers.
■■ The UML provides a way to visualize the higher-level organization of programs
without getting mired down in the details of actual code.
MULTIPLE-CHOICE QUESTIONS
1. C++ was originally developed by
a. Nicolas wirth
b. Donald knuth
c. Bjarne Steoustrup
d. Ken Thompson
2. The standard C++ comment
a. /
b. //
c. /* and */
d. None of these
3. The operator << is called
a. an insertion operator
b. put to operator
c. either a or b
d. None of these
3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 85
REVIEW QUESTIONS
1. What is the object-oriented programming (OOP)?
2. Discuss about the object-oriented approach.
3. Define characteristics of object-oriented languages.
4. Differentiate between C++ and C.
5. Define data type and operator in C++.
3G E-LEARNING
86 Introduction to Computer Programming and Web Designing
REFERENCES
1. Balagurusamy, E. (2001). Object oriented programming with C++. New Delhi:
Tata McGraw-Hill.
2. Booch, G. (2002). Object-oriented analysis and design with applications. Upper
Saddle River, NJ: Pearson Education.
3. Cheesman, John and John Daniels. UML Components: A Simple Process for
Specifying Component-Based Software. Addison-Wesley, 2001.
4. Cline, M. (2006). C++ FAQs (2nd ed). Pearson Education.
5. Dewhurst, S. C. (2006). C++ common knowledge essential intermediate
programming. Pearson Education.
6. Ellis, M. A., & Stroustrup, B. (2000). The annotated C++ reference manual. Reading,
MA: Addison-Wesley (Pearson Education Asia).
7. Grimes, Richard. “.NET Data I/O.” CodeGuru, December 2000.
8. Lange, Sebastian, et al. .NET Framework Security. Addison-Wesley, 2002.
9. Lau, Yun-Tung, Ph.D. The Art of Objects: Object-Oriented Design and Architecture.
Addison-Wesley, 2001.
10. Rammer, Ingo. Advanced .NET Remoting. APress, 2002.
11. Richter, Jeffrey. “Overview of the BCL Collection Types.” CodeGuru, November
2000. ...
3G E-LEARNING
CHAPTER HTML
3
“Words can be like X-rays, if you use them properly—they’ll go through anything. You read and you’re
pierced.”
-Aldous Huxley,
LEARNING OBJECTIVES
INTRODUCTION
HTML (Hypertext Markup Language) is the set of markup symbols or codes inserted
in a file intended for display on a World Wide Web browser page. The markup tells
the Web browser how to display a Web page’s words and images for the user. Each
individual markup code is referred to as an element (but many people also refer to
it as a tag). Some elements come in pairs that indicate when some display effect is to
begin and when it is to end.
3G E-LEARNING
HTML 89
3G E-LEARNING
90 Introduction to Computer Programming and Web Designing
3G E-LEARNING
HTML 91
Tag Description
<!DOCTYPE...> This tag defines the document type and HTML
version.
<html> This tag encloses the complete HTML document
and mainly comprises of document header which
is represented by <head>...</head> and document
body which is represented by <body>...</body> tags.
<head> This tag represents the document’s header which
can keep other HTML tags like <title>, <link> etc.
<title> The <title> tag is used inside the <head> tag to
mention the document title.
<body> This tag represents the document’s body which
keeps other HTML tags like <h1>, <div>, <p> etc.
<h1> This tag represents the heading.
<p> This tag represents a paragraph.
Headings
Headings are defined with the <h1> to <h6> tags. <h1> defines
the largest heading while <h6> defines the smallest.
3G E-LEARNING
92 Introduction to Computer Programming and Web Designing
Paragraphs
Paragraphs are defined with the <p> tag. Think of a paragraph as
a block of text. You can use the align attribute with a paragraph
tag as well.
Remember
You must
indicate
paragraphs with
<p> elements. A Line Breaks
browser ignores
any indentations The <br> tag is used when you want to start a new line, but
or blank lines
in the source don’t want to start a new paragraph. The <br> tag forces a line
text. Without break wherever you place it. It is similar to single spacing in
<p> elements, a document.
the document
becomes one
large paragraph.
HTML
automatically
adds an extra
blank line before
and after a The <br> tag has no closing tag.
paragraph.
Horizontal Rule
Horizontal lines are used to visually break up sections of a
document. The <hr> tag creates a line from the current position in
the document to the right margin and breaks the line accordingly.
Comments in HTML
The comment tag is used to insert a comment in the HTML
source code. A comment can be placed anywhere in the document
3G E-LEARNING
HTML 93
and the browser will ignore everything inside the brackets. You
can use comments to write notes to yourself, or write a helpful
message to someone looking at your source code.
Remember
You
need an
exclamation
Notice you don’t see the text between the tags <!-- and -->. point after the
opening bracket
If you look at the source code, you would see the comment. To <!-- but not
view the source code for this page, in your browser window, before the closing
select View and then select Source. bracket -->.
Logical Tags
3G E-LEARNING
94 Introduction to Computer Programming and Web Designing
Physical Tags
Character tags like <strong> and <em> produce the same physical display as <b>
and <i> but are more uniformly supported across different browsers.
A character entity has three parts: an ampersand (&), an entity name or an entity
number, and finally a semicolon (;). The & means we are beginning a special character,
the; means ending a special character and the letters in between are sort of an abbreviation
for what it’s for. To display a less than sign in an HTML document we must write: <
or < The advantage of using a name instead of a number is that a name is easier to
remember. The disadvantage is that not all browsers support the newest entity names,
while the support for entity numbers is very good in almost all browsers.
3G E-LEARNING
HTML 95
Non-breaking Space
The most common character entity in HTML is the non-breaking space ..
Normally HTML will truncate spaces in your text. If you add 10 spaces in your text,
HTML will remove 9 of them. To add spaces to your text, use the character entity.
body {
font-family: verdana, arial;
color: #333;
}
3G E-LEARNING
96 Introduction to Computer Programming and Web Designing
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Result
3G E-LEARNING
HTML 97
Example
Here are the examples to set background of an HTML tag:
<!DOCTYPE html>
<html>
<head>
<title>HTML Background Colors</title>
</head>
<body>
3G E-LEARNING
98 Introduction to Computer Programming and Web Designing
</body>
</html>
3G E-LEARNING
HTML 99
The most frequently used image formats are JPEG, GIF and PNG
images.
Example
Here are the examples to set background images of a table.
<!DOCTYPE html>
<html>
<head>
<title>HTML Background Images</title>
</head>
<body>
3G E-LEARNING
100 Introduction to Computer Programming and Web Designing
</body>
</html>
This will produce following result:
3G E-LEARNING
HTML 101
3G E-LEARNING
102 Introduction to Computer Programming and Web Designing
Remember
All the
browsers
does not support
rgb() property
of color so it is
recommended
not to use it.
3G E-LEARNING
HTML 103
<li>Pineapple Cake</li>
</ul>
The output of the above example will look something like this:
The output of the above example will look something like this:
Example
<dl>
3G E-LEARNING
104 Introduction to Computer Programming and Web Designing
<dt>Bread</dt>
<dd>A baked food made of flour.</dd>
<dt>Coffee</dt>
<dd>A drink made from roasted coffee beans.</dd>
</dl>
The output of the above example will look something like this:
Local Links
A Local link uses a page name (including sub-directories if needed) as the target. It
is “local” to the current server.
<a href=”Page_in_the_same_server.html“>
Click here to go to the local page
</a>
3G E-LEARNING
HTML 105
Internal Links
Internal links can also be called page jump, u can make this jump with two simple steps
First step:
assign the place of the page where u want the pointer to move, and bookmark it by
adding this cod in it
<A NAME=”ur bookmark name“></A>
u will need the “ur bookmark name” in the next step.
Second step:
u need to add a link in anyplace in ur page to let the user move to ur bookmark
point from it
<A HREF=”#ur bookmark name “> Add the text to be displayed and clicked by the
user </A></P>
The A stands for Anchor. In general, the anchor tag tells the browser to anchor or
to attach to something else. Every Anchor tag must have a closing or end tag (</A>)
to signal the end of the anchor. HREF stands for Hypertext REFerence. It means that
“this is where the link is going to.
Example:
lets add a link to move the user to the top of the current page
first step: we add the bookmark code at the top of the page
<A NAME=”top“></A>
<A HREF=”#top “> click here to go to the top of this page </A></P>
3G E-LEARNING
106 Introduction to Computer Programming and Web Designing
the link will take u few lines above since we are not far from the top of this page
External Links
To link to any page in the world,u need the (URL) of the page you want to link to.
Download Links
File links are used for allowing a visitor to download a file. These links are set up
exactly the same as the local or external links. Instead of “pointing” to another page
or site, it points to a file. When the user clicks on this link, the browser knows it is
a file and will ask the visitor if they want to download the file. The types of files
available to be used for download depends on your online server. A common and
most accepted type is a ZIP file.
<a href=”File [Link]“>
Click here to d ownload this file
</a>
E-mail Links
The e-mail link is for receiving e-mail and feedback from visitors. This link will prompt
the browser’s e-mail program to start and place the e-mail address in automatically.
3G E-LEARNING
HTML 107
The subject line of an e-mail can be filled in automatically by adding a SUBJECT property:
<a href = “mailto: mail_address@[Link]?subject = ‘e-mail from the web-site’“>
click here ti send me e-mail </a>
the cc and bcc can be added in the same way replacing their name instead of the subject
word.
Link Colors
Links, by default, show up in different colors from the rest of the text on your web
page. These settings are found in the individual browser settings. To over-ride these
settings, you can declare your own link colors in the opening BODY tag:
■■ LINK: Color of an non-activated link. (default blue)
■■ VLINK: Color of a previously visited link. (default red)
■■ ALINK: Color of a currently active link. (default orange)
<body link= “#0000ff” vlink= “#ff0000” alink= “#ff8429” > ur HTML code here </body>
Using the hex color codes, you can choose the colors to suit your page. The
ALINK is not used much. There aren’t many instances when there is an open link
at the same time as the current page. Be sure you are just inserting these properties
into the current opening BODY [Link] NOT create a second opening BODY tag. Any
given HTML document can have only one BODY tag set. Any more than one set will
result with page errors.
Insert Image
You can insert any image in your web page by using <img> tag. Following is the
simple syntax to use this tag.
<img src=”Image URL” ... attributes-list/>
The <img> tag is an empty tag, which means that it can contain only list of attributes and
it has no closing tag.
3G E-LEARNING
108 Introduction to Computer Programming and Web Designing
Example
Assuming our image location is “/html/image/[Link]”, try the following example:
<!DOCTYPE html>
<html>
<head>
<title>Using Image in Webpage</title>
</head>
<body>
<p>Simple Image Insert</p>
<img src=”/html/images/[Link]” alt=”Test Image” />
</body>
</html>
3G E-LEARNING
HTML 109
<!DOCTYPE html>
<html>
<head>
<title>Set Image Border</title>
</head>
<body>
<p>Setting image Border</p>
<img src=”/html/images/[Link]” alt=”Test Image” border=”3”/>
</body>
</html>
3G E-LEARNING
110 Introduction to Computer Programming and Web Designing
</head>
<body>
<p>Setting image Alignment</p>
<img src=”/html/images/[Link]” alt=”Test Image” border=”3”
align=”right”/>
</body>
</html>
and....
3G E-LEARNING
HTML 111
Open up your text editor. Type in your <html>, <head> and <body> tags. From here on I
will only be writing what goes between the <body> tags. Type in the following:
<table border=”1”>
<tr>
<td>Tables can be used to layout information</td>
<td> <img src=”[Link]
</td>
</tr>
</table>
Headings in a Table
Headings in a table are defined with the <th> tag.
3G E-LEARNING
112 Introduction to Computer Programming and Web Designing
Cellspacing is the pixel width between the individual data cells in the table (The
thickness of the lines making the table grid). The default is zero. If the border is set
at 0, the cellspacing lines will be invisible.
Cellpadding is the pixel space between the cell contents and the cell border. The
default for this property is also zero. This feature is not used often, but sometimes
comes in handy when you have your borders turned on and you want the contents to
be away from the border a bit for easy viewing. Cellpadding is invisible, even with
the border property turned on. Cellpadding can be handled in a style sheet.
Table Tags
3G E-LEARNING
HTML 113
Tables Backgrounds
You can set table background using one of the following two ways:
■■ bgcolor attribute - You can set background color for whole table or just for
one cell.
■■ background attribute - You can set background image for whole table or just
for one cell.
You can also set border color also using bordercolor attribute.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Background</title>
</head>
<body>
<table border=”1” bordercolor=”green” bgcolor=”yellow”>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr><td rowspan=”2”>Row 1 Cell 1</td><td>Row 1 Cell 2</td><td>Row 1 Cell 3</td></tr>
<tr><td>Row 2 Cell 2</td><td>Row 2 Cell 3</td></tr>
<tr><td colspan=”3”>Row 3 Cell 1</td></tr>
</table>
</body>
</html>
3G E-LEARNING
114 Introduction to Computer Programming and Web Designing
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Background</title>
</head>
<body>
<table border=”1” bordercolor=”green” background=”/images/[Link]”>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr><td rowspan=”2”>Row 1 Cell 1</td><td>Row 1 Cell 2</td><td>Row 1 Cell 3</
td></tr>
<tr><td>Row 2 Cell 2</td><td>Row 2 Cell 3</td></tr>
<tr><td colspan=”3”>Row 3 Cell 1</td></tr>
</table>
</body>
</html>
This will produce following result. Here background image did not apply to table’s
header.
3G E-LEARNING
HTML 115
3G E-LEARNING
116 Introduction to Computer Programming and Web Designing
</html>
3G E-LEARNING
HTML 117
SUMMARY
■■ HTML (Hypertext Markup Language) is the set of markup symbols or codes
inserted in a file intended for display on a World Wide Web browser page.
The markup tells the Web browser how to display a Web page’s words and
images for the user.
■■ HTML is a formal Recommendation by the World Wide Web Consortium
(W3C) and is generally adhered to by the major browsers, Microsoft’s Internet
Explorer and Netscape’s Navigator, which also provide some additional non-
standard codes
■■ HTML tags are the hidden keywords within a web page that define how the
browser must format and display the content.
■■ Paragraphs are defined with the <p> tag. Think of a paragraph as a block of
text. You can use the align attribute with a paragraph tag as well.
■■ An HTML font or web font is the type of text displayed, designated using
CSS. Aspects of the font could be changed using attribute and value pairs
within the <font> tag.
■■ Colors are very important to give a good look and feel to your website. You
can specify colors on page level using <body> tag or you can set colors for
individual tags using bgcolor attribute.
■■ An unordered list created using the <ul> tag, and each list item starts with
the <li> tag. The list items in unordered lists are marked with bullets (small
black circles), by default.
■■ Tables are defined with the <table> tag. A table is divided into rows (with
the <tr> tag), and each row is divided into data cells (with the <td> tag). The
letters td stands for table data, which is the content of a data cell.
3G E-LEARNING
118 Introduction to Computer Programming and Web Designing
REVIEW QUESTIONS
1. What is HTML? Discuss the basic HTML document.
2. What is the difference between HTML elements and tags?
3. What are some common lists that are used when designing a page?
4. How to create links to sections on the same page in HTML.
5. How to create a fixed background image on a web page.
3G E-LEARNING
HTML 119
REFERENCES
1. “HTML5 – Hypertext Markup Language – 5.0”. Internet Engineering Task Force.
28 October 2014. Archived from the original on October 28, 2014. Retrieved
November 25, 2014. This document recommends HTML 5.0 after completion.
2. “HTML 3.2 Reference Specification”. World Wide Web Consortium. January 14,
1997. Retrieved November 16, 2008.
3. “IETF HTML WG”. Retrieved June 16, 2007. Note: This working group is closed
4. Arnoud Engelfriet. “Introduction to Wilbur”. Web Design Group. Retrieved June
16, 2007.
5. “HTML 4.0 Specification”. World Wide Web Consortium. December 18, 1997.
Retrieved November 16, 2008.
6. “HTML 4 – 4 Conformance: requirements and recommendations”. Retrieved
December 30, 2009.
7. “HTML 4.0 Specification”. World Wide Web Consortium. April 24, 1998. Retrieved
November 16, 2008.
8. “HTML 4.01 Specification”. World Wide Web Consortium. December 24, 1999.
Retrieved November 16, 2008.
9. ISO (2000). “ISO/IEC 15445:2000 – Information technology – Document description
and processing languages – HyperText Markup Language (HTML)”. Retrieved
December 26, 2009.
10. [Link]. [Link] (2000-05-15). Retrieved on 2012-02-16.
11. “HTML5: A vocabulary and associated APIs for HTML and XHTML”. World Wide
Web Consortium. 28 October 2014. Retrieved 31 October 2014.
12. “Open Web Platform Milestone Achieved with HTML5 Recommendation” (Press
release). World Wide Web Consortium. 28 October 2014. Retrieved 31 October 2014.
13. “HTML 5.1”. World Wide Web Consortium. 1 November 2016. Retrieved 6 January
2017.
3G E-LEARNING
CHAPTER XHTML
4
“Measuring programming progress by lines of code is like measuring aircraft building progress by weight.”
-Bill Gates
LEARNING OBJECTIVES
INTRODUCTION
XHTML stands for EXtensible HyperText Markup Language. It
is the next step in the evolution of the internet. The XHTML
1.0 is the first document type in the XHTML family. XHTML is
almost identical to HTML 4.01 with only few differences. This
is a cleaner and stricter version of HTML 4.01. If you already
know HTML, then you need to give little attention to learn this
latest version of HTML.
XHTML was developed by World Wide Web Consortium
(W3C) to help web developers make the transition from HTML
to XML. By migrating to XHTML today, web developers can
enter the XML world with all of its benefits, while still remaining
confident in the backward and future compatibility of the content.
3G E-LEARNING
XHTML 123
3G E-LEARNING
124 Introduction to Computer Programming and Web Designing
■■ XHTML documents are XML conforming as they are readily viewed, edited,
and validated with standard XML tools.
■■ XHTML documents can be written to operate better than they did before in
existing browsers as well as in new browsers.
■■ XHTML documents can utilize applications such as scripts and applets that
rely upon either the HTML Document Object Model or the XML Document
Object Model.
■■ XHTML gives you a more consistent, well-structured format so that your
webpages can be easily parsed and processed by present and future web
browsers.
■■ You can easily maintain, edit, convert and format your document in the long
run.
■■ Since XHTML is an official standard of the W3C, your website becomes more
compatible with many browsers and it is rendered more accurately.
■■ XHTML combines strength of HTML and XML. Also, XHTML pages can be
rendered by all XML enabled browsers.
■■ XHTML defines quality standard for your webpages and if you follow that,
then your web pages are counted as quality web pages. The W3C certifies
those pages with their quality stamp.
Web developers and web browser designers are constantly discovering new ways
to express their ideas through new markup languages. In XML, it is relatively easy
to introduce new elements or additional element attributes. The XHTML family is
designed to accommodate these extensions through XHTML modules and techniques for
developing new XHTML-conforming modules. These modules permit the combination
of existing and new features at the time of developing content and designing new
user agents.
What is HTML?
This is Standard Generalized Markup Language (SGML) application conforming to
International Standard ISO 8879. HTML is widely regarded as the standard publishing
language of the World Wide Web.
3G E-LEARNING
XHTML 125
What is SGML?
This is a language for describing markup languages, particularly those used in electronic
document exchange, document management, and document publishing. HTML is an
example of a language defined in SGML.
What is XML?
XML stands for EXtensible Markup Language. XML is a markup language much like
HTML and it was designed to describe data. XML tags are not predefined. You must
define your own tags according to your needs.
DOCTYPE Declaration
All XHTML documents must have a DOCTYPE declaration at the start.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“[Link]
Case Sensitivity
XHTML is case sensitive markup language. All the XHTML tags and attributes need
to be written in lower case only.
3G E-LEARNING
126 Introduction to Computer Programming and Web Designing
The following syntax shows the correct way of writing above tags in XHTML.
Difference is that, here we have closed both the tags properly.
Attribute Quotes
All the values of XHTML attributes must be quoted. Otherwise, your XHTML document
is assumed as an invalid document. Here is the example showing syntax:
3G E-LEARNING
XHTML 127
Attribute Minimization
XHTML does not allow attribute minimization. It means you need to explicitly state
the attribute and its value. The following example shows the difference:
The id Attribute
The id attribute replaces the name attribute. Instead of using name=”name”, XHTML
prefers to use id=”id”. The following example shows how:
3G E-LEARNING
128 Introduction to Computer Programming and Web Designing
Element Prohibitions
The following elements are not allowed to have any other
element inside them. This prohibition applies to all depths of
nesting. Means, it includes all the descending elements.
3G E-LEARNING
XHTML 129
For Example
This example used the strict DTD, meaning that every single tag must be closed
properly, all attributes assigned values, etc:
<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html
PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“DTD/[Link]”>
<html xmlns=”[Link] xml:lang=”en” lang=”en”>
<head>
<title> Strict DTD XHTML Example </title>
</head>
<body>
<p>
Please Choose a Day:
<br /><br />
<select name=”day”>
<option selected=”selected”>Monday</option>
<option>Tuesday</option>
<option>Wednesday</option>
</select>
3G E-LEARNING
130 Introduction to Computer Programming and Web Designing
</p>
</body>
</html>
4.3 HEADERS
Some text in an XHTML document might be more important than other text. For
example, the text in this method is considered more important than a footnote. XHTML
provides six headers, called header elements, for specifying the relative importance of
information. Figure 1 demonstrates these elements (h1 through h6).
3G E-LEARNING
XHTML 131
XHTML
documents must
4.4 LINKING use lower case
One of the most important XHTML features is the hyperlink, for all HTML
elements and
which references (or links to) other resources, such as XHTML attribute names.
documents and images. In XHTML, both text and images can act
as hyperlinks. Web browsers typically underline text hyperlinks
and color their text blue by default, so that users can distinguish
hyperlinks from plain text. In Figure 2, we create text hyperlinks
to four different Web sites. Line 17 introduces the tag. Browsers
typically display text marked up with in a bold font.
Links are created using the a (anchor) element. Line 21
defines a hyperlink that links the text Deitel to the URL assigned
to attribute href, which specifies the location of a linked resource,
such as a Web page, a file or an e-mail address. This particular
anchor element links to a Web page located at [Link]
com. When a URL does not indicate a specific document on the
Web site, the Web server returns a default Web page. This page
often is called [Link]; however, most Web servers can be
configured to use any file as the default Web page for the site.
(Open [Link] in one browser window and http://
Keyword
A
[Link]/[Link] in a second browser window to hyperlink
confirm that they are identical.) If the Web server cannot locate is a word, phrase,
a requested document, the server returns an error indication to or image that
you can click
the Web browser, and the browser displays an error message on to jump to a
to the user. new document
or a new
section within
the current
document.
3G E-LEARNING
132 Introduction to Computer Programming and Web Designing
Anchors can link to e-mail addresses through a mailto: URL. When someone clicks
this type of anchored link, most browsers launch the default e-mail program (e.g.,
Outlook Express) to enable the user to write an e-mail message to the linked address.
Figure 3 demonstrates this type of anchor.
3G E-LEARNING
XHTML 133
Lines 17–19 contain an e-mail link. The form of an e-mail anchor is <a href
=”[Link] …. In this case, we link to the e-mail address deitel@
[Link].
4.5 IMAGES
Most Web pages contain both text and images. In fact, images are an equal and
essential part of Web-page design. The two most popular image formats used by Web
developers are Graphics Interchange Format (GIF) and Joint Photographic Experts
3G E-LEARNING
134 Introduction to Computer Programming and Web Designing
Keyword
Graphics
Interchange
Format (GIF)
is an image
file format
commonly used
for images on the
web and sprites
in software
programs.
Figure 4. Placing images in XHTML files.
3G E-LEARNING
XHTML 135
3G E-LEARNING
136 Introduction to Computer Programming and Web Designing
element’s src attribute value specifies that this image ([Link]) resides in a directory
named buttons. The buttons directory and the XHTML document are in the same
directory. Images from other Web documents also can be referenced (after obtaining
permission from the document’s owner) by setting the src attribute to the name and
location of the image.
3G E-LEARNING
XHTML 137
On line 19, we introduce the br element, which most browsers render as a line
break. Any markup or text following a br element is rendered on the next line. Like
the img element, br is an example of an empty element terminated with a forward
slash. We add a space before the forward slash to enhance readability.
3G E-LEARNING
138 Introduction to Computer Programming and Web Designing
3G E-LEARNING
XHTML 139
3G E-LEARNING
140 Introduction to Computer Programming and Web Designing
The first ordered list begins in line 33. Attribute type specifies the sequence type
(i.e., the set of numbers or letters used in the ordered list). Setting type to “I” specifies
upper-case roman numerals. Line 47 begins the second ordered list and sets attribute
type to “a”, specifying lowercase letters for the list items. The last ordered list (lines
71– 75) does not use attribute type. By default, the list’s items are enumerated from
one to three.
A Web browser indents each nested list to indicate a hierarchal relationship. By
default, the items in the outermost unordered list (line 18) are preceded by discs. List
items nested inside the unordered list of line 18 are preceded by circles. Although not
demonstrated in this example, subsequent nested list items are preceded by squares.
Unordered list items can be explicitly set to discs, circles or squares by setting the ul
element’s type attribute to “disc”, “circle” or “square”, respectively.
3G E-LEARNING
XHTML 141
3G E-LEARNING
142 Introduction to Computer Programming and Web Designing
3G E-LEARNING
XHTML 143
Tables are defined with the table element. Lines 16–18 specify
the start tag for a table element that has several attributes. The
border attribute specifies the table’s border width in pixels. To
create a table without a border, set border to “0”. This example Keyword
assigns attribute width “40%”, to set the table’s width to 40
Pixel
percent of the browser’s width. A developer can also set attribute is the
width to a specified number of pixels. basic unit of
programmable
As its name implies, attribute summary (line 17) describes color on a
the table’s contents. Speech devices use this attribute to make computer display
or in a computer
the table more accessible to users with visual impairments. image.
The caption element (line 22) describes the table’s content and
helps text based browsers interpret the table data. Text inside
the tag is rendered above the table by most browsers. Attribute
summary and element caption are two of many XHTML features
that make Web pages more accessible to users with disabilities.
3G E-LEARNING
144 Introduction to Computer Programming and Web Designing
A table has three distinct sections—head, body and foot. The head section (or header
cell) is defined with a thead element (lines 26–31), which contains header information,
such as column names. Each tr element (lines 27–30) defines an individual table row.
The columns in the head section are defined with th elements. Most browsers center
text for- matted by th (table header column) elements and display it in bold. Table
header elements are nested inside table row elements.
The body section, or table body, contains the table’s primary data. The table body
(lines 34–54) is defined in a tbody element. Data cells contain individual pieces of data
and are defined with td (table data) elements.
The foot section (lines 58–63) is defined with a tfoot (table foot) element and
represents a footer. Text commonly placed in the footer includes calculation results
3G E-LEARNING
XHTML 145
and footnotes. Like other sections, the foot section can contain table rows and each
row can contain columns.
3G E-LEARNING
146 Introduction to Computer Programming and Web Designing
3G E-LEARNING
XHTML 147
3G E-LEARNING
148 Introduction to Computer Programming and Web Designing
server can access through the network. When a browser requests a Web page or file
that is located on a server, the server processes the request and returns the requested
resource. A request contains the name and path of the desired resource and the method
of communication (called a protocol). XHTML documents use the Hypertext Transfer
Protocol (HTTP).
Figure 11 sends the form data to the Web server, which passes the form data to
a form handler. The form handler processes the data received from the Web server
and typically returns information to the Web server. The Web server then sends the
information in the form of an XHTML document to the Web browser.
3G E-LEARNING
XHTML 149
Figure 11. Simple form with hidden fields and a text box.
Forms can contain visual and non-visual components. Visual components include
clickable buttons and other graphical user interface components with which users
interact. Non-visual components, called hidden inputs, store any data that the document
author specifies, such as e-mail addresses and XHTML document file names that act
as links. The form begins on line 23 with the form element. Attribute method specifies
how the form’s data is sent to the Web server.
3G E-LEARNING
150 Introduction to Computer Programming and Web Designing
Using method = “post” appends form data to the browser request, which contains
the protocol (i.e., HTTP) and the requested resource’s URL. Scripts located on the
Web server’s computer (or on a computer accessible through the network) can access
the form data sent as part of the request. For example, a script may take the form
information and update an electronic mailing list. The other possible value, method =
“get”, appends the form data directly to the end of the URL. For example, the URL /
cgi-bin/formmail might have the form information name = bob appended to it.
The action attribute in the <form> tag specifies the URL of a script on the Web
server; it specifies a script that e-mails form data to an address. Most Internet Service
Providers (ISPs) have a script like this on their site; ask the Web-site system administrator
how to set up an XHTML document to use the script correctly.
Lines 29–36 define three input elements that specify data to provide to the script
that processes the form (also called the form handler). These three input elements have
type attribute “hidden”, which allows the document author to send form data that is
not entered by a user to a script.
The three hidden inputs are an e-mail address to which the data will be sent, the
email’s subject line and a URL where the browser will be redirected after submitting
the form. Two other input attributes are name, which identifies the input element,
and value, which provides the value that will be sent (or posted) to the Web server.
The input element’s size attribute specifies the number of characters visible in the
text box. Optional attribute maxlength limits the number of characters input into the
text box. The user is not permitted to type more than 30 characters into the text box.
There are two types of input elements in lines 52–56. The “submit” input element
is a button. When the user presses a “submit” button, the browser sends the data in
the form to the Web server for processing. The value attribute sets the text displayed
on the button (the default value is Submit). The “reset” input element allows a user
to reset all form elements to their default values. The value attribute of the “reset”
input element sets the text displayed on the button (the default value is Reset).
3G E-LEARNING
XHTML 151
The “password” input in lines 52–53 inserts a password box with the specified
size. A password box allows users to enter sensitive information, such as credit card
numbers and passwords, by “masking” the information input with asterisks. The actual
value input is sent to the Web server, not the asterisks that mask the input.
Lines 60–78 introduce the checkbox form element. Checkboxes enable users to
select from a set of options. When a user selects a checkbox, a check mark appears in
the check box. Otherwise, the checkbox remains empty. Each “checkbox” input creates
a new checkbox. Checkboxes can be used individually or in groups. Checkboxes that
belong to a group are assigned the same name (in this case, “thingsliked”).
We introduce two new input types. The first type is the radio button (lines
90–113), specified with type “radio”. Radio buttons are similar to checkboxes, except
that only one radio button in a group of radio buttons may be selected at any time.
All radio buttons in a group have the same name attribute; they are distinguished by
their different value attributes. The attribute–value pair checked = “checked” (line 92)
indicates which radio button, if any, is selected initially. The checked attribute also
applies to checkboxes.
3G E-LEARNING
152 Introduction to Computer Programming and Web Designing
3G E-LEARNING
XHTML 153
The select element (lines 123–136) provides a drop-down list from which the user
can select an item. The name attribute identifies the drop-down list. The option element
(lines 124–135) adds items to the drop-down list. The option element’s selected attribute
specifies which item initially is displayed as the selected item in the select element.
3G E-LEARNING
154 Introduction to Computer Programming and Web Designing
3G E-LEARNING
XHTML 155
3G E-LEARNING
156 Introduction to Computer Programming and Web Designing
3G E-LEARNING
XHTML 157
3G E-LEARNING
158 Introduction to Computer Programming and Web Designing
ROLE MODEL
TIMOTHY JOHN BERNERS-LEE AS A
SOFTWARE ENGINEER
Born 1955.
Tim Berners-Lee is a software engineer who invented the Internet
(or the World Wide Web) in 1989 while at CERN, the European
Particle Physics Laboratory.
He is director of the World Wide Web Consortium that he
founded and a Professor in the Computer Science Department
at the University of Oxford.
In 2001 he became a Fellow of the Royal Society and in
2004 he was knighted.
3G E-LEARNING
XHTML 159
which was run by two of his friends Dennis Nash and John Poole, where he created
type-setting software for printers and wrote and a multitasking operating system.
From June to December in 1980, he worked for the European Organization for
Nuclear Research (CERN) as an independent software engineer. While he was there,
he made a proposal for a project based on “hypertext” which would make sharing
and updating of information by researchers easier and more convenient. Berners-Lee
then devised a prototype system called ENQUIRE to demonstrate how it would work.
The name came from a Victorian book called “Enquire Within Upon Everything.”
After he left CERN in late 1980, Berners-Lee became a Director at John Poole’s Image
Computer Systems LTD in Bournemouth, Dorset. For three years he was in charge
of the technical side of the company and gained experience in computer networking,
graphics and communications software.
In 1983 Vinton Cerf created the first commercial internet “email” system where
information could be shared between individuals using email addresses. Berners-
Lee, with his ENQUIRE proposal, wanted to devise a system that was automatically
available to everyone.
Berners-Lee returned to CERN in 1984 as a Fellow and by 1989 CERN was also
the largest internet node in the European continent.
Berners-Lee saw his chance to meld hypertext with the internet and produced
his idea, Information Management: A Proposal”, in March 1989, to share information
globally, without the need for emails. Thee system was named World Wide Web and
Berners-Lee also designed and built the first web browser.
Early Web
The first website was built at CERN and was published on August 6, 1991; its address
was [Link]. and it acted as both a web server and web site. A NeXT computer
located at CERN was used to run it. The first web site contained information about
Berners-Lee’s project so visitors could learn about hypertext (HTTP) and learn about
building webpages, so they could make their own.
By 1992 there were 50 servers and by 1994 there were over 2 million users, with
150,000 new users being added every month. However the Web was still heavily in
the academic field.
In 1994 Berners-Lee founded the World Wide Web Consortium (W3C) at the
Laboratory of Computer Science (LCS) at the Massachusetts Institute of Technology
in Boston. It was made up of companies that wanted to work together to create Web
standards and also improve the Web. It was quickly agreed that the technology should
be free of royalties and patents. Berners-Lee has served as director of this W3C since
3G E-LEARNING
160 Introduction to Computer Programming and Web Designing
it was founded. In 1995 Microsoft produced the first version of Internet Explorer and
this commercial browser created enormous growth in websites and web users.
The Web was first used for e-commerce in 1997.
Later Career
In June 2009, British PM Gordon Brown made the announcement that Berners-Lee,
together with Nigel Shadbolt, would be working with the UK government so they
could make data more accessible and open to people that needed it on the web site
[Link].
Berners-Lee holds the founders chair in Computer Science at the Massachusetts
Institute of Technology.
In 2016 he joined the Department of Computer Science at Oxford University as a
professorial research fellow.
3G E-LEARNING
XHTML 161
SUMMARY
■■ XHTML stands for EXtensible HyperText Markup Language. It is the next step
in the evolution of the internet. The XHTML 1.0 is the first document type in
the XHTML family.
■■ HTML began as a simple markup language similar in appearance and usage to
other Standard Generalized Markup Language (SGML)-based markup languages.
■■ XHTML syntax is very similar to HTML syntax and almost all the valid
HTML elements are valid in XHTML as well. But when you write an XHTML
document, you need to pay a bit extra attention to make your HTML document
compliant to XHTML.
■■ XHTML documents that are syntactically correct are guaranteed to render
properly. XHTML documents that contain syntax errors might not display
properly.
■■ Most Web pages contain both text and images. In fact, images are an equal
and essential part of Web-page design. The two most popular image formats
used by Web developers are Graphics Interchange Format (GIF) and Joint
Photographic Experts Group (JPEG) images.
■■ XHTML provides six headers (h1 through h6) for specifying the relative
importance of information. Header element h1 is considered the most significant
header and is rendered in a larger font than the other five headers. Each
successive header element (i.e., h2, h3, etc.) is rendered in a smaller font.
■■ The img element’s src attribute specifies an image’s location. Optional attributes
width and height specify the image width and height, respectively. Images
are measured in pixels (“picture elements”), which represent dots of color on
the screen.
■■ A form begins with the form element. Attribute method specifies how the
form’s data is sent to the Web server.
3G E-LEARNING
162 Introduction to Computer Programming and Web Designing
c. Paragraph
d. None of the above
3. Which statement is true
a. XML and HTML will be replaced by XHTML
b. HTML will be replaced by XHTML
c. XML will be replaced by XHTML
d. all are false
4. What is the correct XHTML for a paragraph?
a. </p><p>
b. <P></P>
c. <p></p>
d. <P></p>
5. What is the correct XHTML for a line break?
a. <br />
b. <br/>
c. <br>
d. </br>
REVIEW QUESTIONS
1. What is XHTML?
2. How to write the opening tag of an XHTML element?
3. Differentiation between HTML and XHTML.
4. How to create a table in XHTML?
5. Discuss the XHTML forms.
3G E-LEARNING
XHTML 163
REFERENCES
1. “XHTML Media Types – Second Edition, W3C Working Group Note 16 January
2009”. World Wide Web Consortium. 2009-01-16. Retrieved 2009-01-28. This
document supersedes the HTML Compatibility Guidelines originally found in
XHTML 1.0 Appendix C.
2. “XHTML Basic, W3C Recommendation 19 December 2000”. World Wide Web
Consortium. 2000-12-19. Retrieved 2008-07-19.
3. “Modularization of XHTML, W3C Recommendation 10 April 2001”. World Wide
Web Consortium. 2001-04-10. Retrieved 2008-07-19.
4. “XHTML 1.1 - Module-based XHTML, W3C Recommendation 31 May 2001”.
World Wide Web Consortium. 2001-05-31. Retrieved 2008-07-19.
5. “XHTML Media Types, W3C Working Group Note 1 August 2002”. World Wide
Web Consortium. 2002-08-01. Retrieved 2008-07-19.
6. Simon Pieters. “Results of mobile tests”. Retrieved 2009-10-31.
7. Ian Hickson; David Hyatt (2011-01-13). “HTML5: A vocabulary and associated
APIs for HTML and XHTML”. Retrieved 2011-02-16.
8. “XHTML 1.0: The Extensible HyperText Markup Language, W3C Recommendation
26 January 2000”. World Wide Web Consortium. 2000-01-26. Retrieved 2008-07-19.
9. “XHTML 1.0 The Extensible HyperText Markup Language (Second Edition)”.
World Wide Web Consortium. 2002-08-01. Retrieved 2008-07-19.
10. “XHTML Modularization 1.1 - Second Edition, W3C Recommendation 29 July
2010”. World Wide Web Consortium. 2010-07-29. Retrieved 2010-12-31.
11. “XHTML 1.1, XHTML Basic 1.1, XHTML Print Recommendations Revised”. W3C
NEWS ARCHIVE: 2010. World Wide Web Consortium. Retrieved 12 December
2010.
12. “XHTML 1.1 - Module-based XHTML – Second Edition”. World Wide Web
Consortium. 2009-05-07. Archived from the original on 2009-05-12. Retrieved
2009-05-25.
3G E-LEARNING
CHAPTER CASCADING STYLE
5 SHEETS (CSS)
LEARNING OBJECTIVES
INTRODUCTION
A cascading style sheet (CSS) is a Web page derived from
multiple sources with a defined order of precedence where the
definitions of any style element conflict. The Cascading Style
Sheet, level 1 (CSS1) recommendation from the World Wide
Web Consortium (W3C), which is implemented in the latest
versions of the Netscape and Microsoft Web browsers, specifies
the possible style sheets or statements that may determine how
a given element is presented in a Web page.
CSS gives more control over the appearance of a Web page
to the page creator than to the browser designer or the viewer.
With CSS, the sources of style definition for a given document
element are in this order of precedence:
■■ The STYLE attribute on an individual element tag
■■ The STYLE element that defines a specific style sheet
Keyword containing style declarations or a LINK element that
A web
page
links to a separate document containing the STYLE
or webpage is element. In a Web page, the STYLE element is placed
a document between the TITLE statement and the BODY statement.
commonly
written in ■■ An imported style sheet, using the CSS @import notation
HyperText to automatically import and merge an external style
Markup sheet with the current style sheet
Language
(HTML) that ■■ Style attributes specified by the viewer to the browser
is accessible
through the ■■ The default style sheet assumed by the browser
Internet or other
network using an
Internet browser. 5.1 OVERVIEW OF CSS
Cascading Style Sheets, fondly referred to as CSS, is a simple
design language intended to simplify the process of making
web pages presentable. CSS handles the look and feel part of a
web page. Using CSS, you can control the color of the text, the
style of fonts, the spacing between paragraphs, how columns
are sized and laid out, what background images or colors are
used, as well as a variety of other effects. CSS is easy to learn
and understand but it provides a powerful control over the
presentation of an HTML document. Most commonly, CSS is
combined with the markup languages HTML or XHTML.
3G E-LEARNING
Cascading Style Sheets (CSS) 167
3G E-LEARNING
168 Introduction to Computer Programming and Web Designing
3G E-LEARNING
Cascading Style Sheets (CSS) 169
The example below shows how to change the color and the left margin of
a <h1> element:
Example
<h1 style=”color:blue;margin-left:30px;”>This is a heading.</h1>
3G E-LEARNING
170 Introduction to Computer Programming and Web Designing
3G E-LEARNING
Cascading Style Sheets (CSS) 171
Keyword
MIME
(Multi-
Purpose Internet
Mail Extensions)
is an extension
of the original
Internet e-mail
protocol that
Figure 2. Embedded style sheets. lets people use
the protocol
The style element (lines 13–24) defines the embedded style to exchange
sheet. Styles placed in the head apply to matching elements different kinds of
wherever they appear in the entire document. The style data files on the
Internet: audio,
element’s type attribute specifies the Multipurpose Internet video, images,
Mail Extensions (MIME) type that describes a file’s content. application
CSS documents use the MIME type text/ css. Other MIME types programs, and
other kinds, as
include image/gif (for GIF images) and text/javascript. well as the ASCII
text handled
The body of the style sheet (lines 15–22) declares the CSS in the original
rules for the style sheet. We declare rules for em (lines 15–16), protocol, the
h1 (line 18) and p (line 20) elements. When the browser renders Simple Mail
Transport
this document, it applies the properties defined in these rules to Protocol (SMTP).
every element to which the rule applies. For example, the rule in
lines 15–16 will be applied to all em elements (in this example,
there is one in line 43). The body of each rule is enclosed in
curly braces ({and}).
3G E-LEARNING
172 Introduction to Computer Programming and Web Designing
3G E-LEARNING
Cascading Style Sheets (CSS) 173
makes pages more accessible to users with disabilities. Users with impaired vision,
for example, may configure their browser to use a larger default font, upon which all
relative sizes are based. Text that the author specifies to be smaller than the main text
still displays in a smaller size font, yet it is clearly visible to each user.
Line 30 uses attribute class in an h1 element to apply a style class—in this case
class special (declared as .special in the style sheet). When the browser renders the
h1 element, note that the text appears on screen with the properties of both an h1
element (arial or sans-serif font defined in line 18) and the .special style class applied
(the color blue defined in line 22).
The formatting for the p element and the .special class are applied to the text in
lines 42–49. All the styles applied to an element (the parent or ancestor element) also
apply to the element’s nested elements (child or descendant elements). The em element
nested in the p element in line 43 inherits the style from the p element (namely, the
14-point font size in line 20), but retains its italic style. The em element has its own
color property, so it overrides the color property of the special class.
3G E-LEARNING
174 Introduction to Computer Programming and Web Designing
3G E-LEARNING
Cascading Style Sheets (CSS) 175
3G E-LEARNING
176 Introduction to Computer Programming and Web Designing
Figure 5 contains an XHTML document that references the external style sheet
in Figure 4. Lines 11–12 (Figure 5) show a link element that uses the rel attribute to
specify a relationship between the current document and another document. In this
case, we declare the linked document to be a stylesheet for this document. The type
attribute specifies the MIME type as text/css. The href attribute provides the URL for
the document containing the style sheet. In this case, [Link] is in the same directory
as [Link].
3G E-LEARNING
Cascading Style Sheets (CSS) 177
3G E-LEARNING
178 Introduction to Computer Programming and Web Designing
Submit this CSS file for validation to upload the file for validation. Figure 7 shows
the results of validating [Link] (Figure 4).
3G E-LEARNING
Cascading Style Sheets (CSS) 179
and a capability called absolute positioning, which gives authors greater control over
how document elements are displayed. Figure 8 demonstrates absolute positioning.
Lines 15–17 position the first img element ([Link]) on the page. Specifying an
element’s position as absolute removes the element from the normal flow of elements
on the page, instead positioning it according to the distance from the top, left, right
or bottom margins of its containing block-level element (i.e., an element such as body
or p). Here, we position the element to be 0 pixels away from both the top and left
margins of the p element (lines 15–17).
The z-index attribute allows you to layer overlapping elements properly. Elements
that have higher z-index values are displayed in front of elements with lower z-index
values. In this example, [Link] has the lowest z-index (1), so it displays in the background.
3G E-LEARNING
180 Introduction to Computer Programming and Web Designing
The img element in lines 20–22 ([Link]) has a z-index of 2, so it displays in front of
[Link]. The p element in lines 18–19 (Positioned Text) has a z-index of 3, so it displays
in front of the other two. If you do not specify a z-index or if elements have the same
z-index value, the elements are placed from background to foreground in the order
they are encountered in the document.
Absolute positioning is not the only way to specify page layout. Figure 9 demonstrates
relative positioning, in which elements are positioned relative to other elements.
3G E-LEARNING
Cascading Style Sheets (CSS) 181
Setting the position property to relative, as in class super (lines 21–22),lays out the
element on the page and offsets it by the specified top, bottom, left or right value.
Unlike absolute positioning, relative positioning keeps elements in the general flow of
elements on the page, so positioning is relative to other elements in the flow. Recall
that ex (line 22) is the x-height of a font, a relative length measurement typically equal
to the height of a lowercase x.
We introduce the span element in line 39. Element span is a grouping element—
it does not apply any inherent formatting to its contents. Its primary purpose is to
apply CSS rules or id attributes to a block of text. Element span is an inline-level
element—it is displayed inline with other text and with no line breaks. Lines 17–19
define the CSS rule for span. A similar element is the div element, which also applies
no inherent styles but is displayed on its own line, with margins above and below (a
block-level element).
5.6 BACKGROUNDS
CSS provides control over the element backgrounds. We introduced the background-
color property. CSS also can add background images to documents. Figure 10 adds
a corporate logo to the bottom-right corner of the document. This logo stays fixed in
the corner even when the user scrolls up or down the screen.
3G E-LEARNING
182 Introduction to Computer Programming and Web Designing
3G E-LEARNING
Cascading Style Sheets (CSS) 183
The background-image property (line 14) specifies the image URL for the image logo.
gif in the format url( fileLocation ). The Web-page author also can set the background-
color property in case the image is not found. The background-position property (line
15) places the image on the page. The keywords top, bottom, center, left and right are
used individually or in combination for vertical and horizontal positioning. An image
can be positioned using lengths by specifying the horizontal length followed by the
vertical length. For example, to position the image as horizontally centered (positioned
at 50% of the distance across the screen) and 30 pixels from the top, use
background-position: 50% 30px;
The background-repeat property (line 16) controls the tiling of the background image.
Tiling places multiple copies of the image next to each other to fill the background.
Here, we set the tiling to no-repeat to display only one copy of the background image.
The background-repeat property can be set to repeat (the default) to tile the image
vertically and horizontally, repeat-x to tile the image only horizontally or repeat-y to
tile the image only vertically.
The final property setting, background-attachment: fixed (line 17), fixes the image
in the position specified by background-position. Scrolling the browser window will
not move the image from its position. The default value, scroll, moves the image as
the user scrolls through the document.
Line 21 indents the first line of text in the element by the specified amount, in this
case 1em. An author might use this property to create a Web page that reads more
like a novel, in which the first line of every paragraph is indented.
Line 24 uses the font-weight property to specify the “boldness” of text. Possible
values are bold, normal (the default), bolder (bolder than bold text) and lighter (lighter
than normal text). Boldness also can be specified with multiples of 100, from 100 to 900
(e.g., 100, 200, …, 900). Text specified as normal is equivalent to 400, and bold text is
equivalent to 700. However, many systems do not have fonts that can scale with this
level of precision, so using the values from 100 to 900 might not display the desired
3G E-LEARNING
184 Introduction to Computer Programming and Web Designing
effect. Another CSS property that formats text is the font-style property, which allows
the developer to set text to none, italic or oblique (oblique will default to italic if the
system does not support oblique text).
3G E-LEARNING
Cascading Style Sheets (CSS) 185
The inline style in line 22 illustrates how to set the width of an element on screen;
here, we indicate that the div element should occupy 20% of the screen width. Most
elements are left-aligned by default; however, this alignment can be altered to position
the element elsewhere. The height of an element can be set similarly, using the height
property. The height and width values also can be specified as relative or absolute
lengths. For example
width: 10em
sets the element’s width to be equal to 10 times the font size. Line 27 sets text in the
element to be center aligned; other values for the text-align property include left and
right. One problem with setting both dimensions of an element is that the content
inside the element can exceed the set boundaries, in which case the element is simply
made large enough for all the content to fit. However, in line 32, we set the overflow
property to scroll, a setting that adds scrollbars if the text overflows the boundaries.
3G E-LEARNING
186 Introduction to Computer Programming and Web Designing
3G E-LEARNING
Cascading Style Sheets (CSS) 187
Keyword
Figure 12. Floating elements, aligning text and setting box Box
model
dimensions. is essentially a
box that wraps
In addition to text, whole elements can be floated to the around every
left or right of content. This means that any nearby text will HTML element.
wrap around the floated element. For example, in lines 30–32 It consists of:
margins, borders,
we float a div element to the right side of the screen. As you padding, and the
can see from the sample screen capture, the text from lines actual content.
34–39 flows cleanly to the left and underneath the div element.
The second property in line 30, margin, specifies the distance
between the edge of the element and any other element on the
page. When the browser renders elements using the box model,
the content of each element is surrounded by padding, a border
and a margin (Figure 13).
Margins for individual sides of an element can be specified
by using the properties margin-top, margin-right, margin-left
and margin-bottom.
Lines 41–43 specify a div element that floats at the right side
of the content. Property padding for the div element is set to
.5em (half a line’s height). Padding is the distance between the
content inside an element and the element’s border. Like the
margin, the padding can be set for each side of the box, with
padding-top, padding-right, padding-left and padding-bottom.
3G E-LEARNING
188 Introduction to Computer Programming and Web Designing
Lines 49–54 show that you can interrupt the flow of text around a floated element
by setting the clear property to the same direction as that in which the element is
floated— right or left. Notice in the screen capture that the text from lines 45–47 flows
to the left of the floated div element (lines 43–45), but the text from lines 49–54 does
not. Setting the clear property to all interrupts the flow on both sides of the document.
Another property of every block-level element on screen is the border, which lies
between the padding space and the margin space, and has numerous properties for
adjusting its appearance, as shown in Figure 14.
3G E-LEARNING
Cascading Style Sheets (CSS) 189
3G E-LEARNING
190 Introduction to Computer Programming and Web Designing
3G E-LEARNING
Cascading Style Sheets (CSS) 191
3G E-LEARNING
192 Introduction to Computer Programming and Web Designing
User style sheets are external style sheets. Figure 17 shows a user style sheet that
sets the body’s font-size to 20pt, color to yellow and background-color to #000080.
User style sheets are not linked to a document; rather, they are set in the browser’s
options. To add a user style sheet in Internet Explorer 6, select Internet Options...,
located in the Tools menu. In the Internet Options dialog (Figure 18) that appears,
click Accessibility..., check the Format documents using my style sheet checkbox, and
type the location of the user style sheet. Internet Explorer 6 applies the user style sheet
to any document it loads.
The Web page from Figure 16 is displayed in Figure 19, with the user style sheet
from Figure 17 applied.
3G E-LEARNING
Cascading Style Sheets (CSS) 193
3G E-LEARNING
194 Introduction to Computer Programming and Web Designing
Figure 21 displays the Web page from Figure 20 with the user style sheet from
Figure 16 applied. Note that the second line of text displayed is larger than the same
line of text in Figure 19.
3G E-LEARNING
Cascading Style Sheets (CSS) 195
SUMMARY
■■ A cascading style sheet (CSS) is a Web page derived from multiple sources
with a defined order of precedence where the definitions of any style element
conflict. The Cascading Style Sheet, level 1 (CSS1) recommendation from the
World Wide Web Consortium (W3C), which is implemented in the latest
versions of the Netscape and Microsoft Web browsers, specifies the possible
style sheets or statements that may determine how a given element is presented
in a Web page.
■■ A Web developer can declare document styles in many ways. This method
presents inline styles that declare an individual element’s format using the
XHTML attribute style.
■■ The inline style allows a developer to declare a style for an individual element
by using the style attribute in the element’s start tag.
■■ Embedded style sheets enable a Web-page author to embed an entire CSS
document in an XHTML document’s head section.
■■ The style element (lines 13–24) defines the embedded style sheet. Styles placed
in the head apply to matching elements wherever they appear in the entire
document. The style element’s type attribute specifies the Multipurpose Internet
Mail Extensions (MIME) type that describes a file’s content.
■■ Cascading style sheets are “cascading” because styles may be defined by a
user, an author or a user agent (e.g., a Web browser). Styles “cascade,” or flow
together, such that the ultimate appearance of elements on a page results from
combining styles defined in several ways.
■■ Style sheets are a convenient way to create a document with a uniform theme.
With external style sheets (i.e., separate documents that contain only CSS rules),
Web-page authors can provide a uniform look and feel to an entire Web site.
■■ The text-decoration property applies decorations to text within an element,
such as underline, overline, line-through and blink.
3G E-LEARNING
196 Introduction to Computer Programming and Web Designing
3G E-LEARNING
Cascading Style Sheets (CSS) 197
REVIEW QUESTIONS
1. What is cascading style sheets (CSS)? Discuss the advantage of CSS.
2. Discuss the external style sheets.
3. Write a CSS rule that removes the underlines from all links inside list items (li) and
shifts all list items left by 3 ems.
4. Write a CSS rule that places a background image halfway down the page, tiling it
horizontally. The image should remain in place when the user scrolls up or down.
5. Write a CSS rule that changes the color of all elements containing attribute class =
“greenMove” to green and shifts them down 25 pixels and right 15 pixels.
3G E-LEARNING
198 Introduction to Computer Programming and Web Designing
REFERENCES
1. “CSS developer guide”. MDN Web Docs. Archived from the original on 2015-
09-25. Retrieved 2015-09-24.
2. “What is CSS?”. World Wide Web Consortium. Archived from the original on
2010-11-29. Retrieved 2010-12-01.
3. “Web-based Mobile Apps of the Future Using HTML 5, CSS and JavaScript”.
HTMLGoodies. 23 July 2010. Archived from the original on 2014-10-20. Retrieved
2014-10-16.
4. “W3C CSS validation service”. Archived from the original on 2011-02-14. Retrieved
2012-06-30.
5. see the complete definition of selectors at the W3C Web site Archived 2006-04-23
at the Wayback Machine.
6. “Selectors Level 3”. [Link]. Archived from the original on 2014-06-03. Retrieved
2014-05-30.
7. “Full property table”. [Link]. Archived from the original on 2014-05-30. Retrieved
2014-05-30.
8. “5. Distance Units: the <length> type”. CSS Values and Units Module Level 3. 6
June 2019. Archived from the original on 7 June 2019. Retrieved 20 June 2019.
9. W3C HTML Working Group. “HTML 5. A vocabulary and associated APIs for
HTML and XHTML”. World Wide Web Consortium. Archived from the original
on 15 July 2014. Retrieved 28 June 2014.
10. Meyer, Eric A. (2006). Cascading Style Sheets: The Definitive Guide (3rd ed.).
O’Reilly Media, Inc. ISBN 0-596-52733-0. Archived from the original on 2014-02-
15. Retrieved 2014-02-16.
11. “Assigning property values, Cascading, and Inheritance”. Archived from the
original on 2014-06-11. Retrieved 2014-06-10.
12. “Can a CSS class inherit one or more other classes?”. StackOverflow. Archived
from the original on 2017-10-14. Retrieved 2017-09-10.
13. Flanagan, David (18 April 2011). JavaScript: the definitive guide. Beijing; Farnham:
O’Reilly. p. 1. ISBN 978-1-4493-9385-4. OCLC 686709345. JavaScript is part of the
triad of technologies that all Web developers must learn: HTML to specify the
content of web pages, CSS to specify the presentation of web pages, and JavaScript
to specify the behavior of web pages.
14. “CSS Color”. MDN Web Docs. 2016-06-28. Archived from the original on 2016-
09-21. Retrieved 2016-08-23.
15. “W3C CSS2.1 specification for pseudo-elements and pseudo-classes”. World Wide
Web Consortium. 7 June 2011. Archived from the original on 30 April 2012.
Retrieved 30 April 2012.
3G E-LEARNING
CHAPTER PHP
6
“Responsive Web Design always plays important role whenever going to promote your website.”
-Josh Wilson
LEARNING OBJECTIVES
INTRODUCTION
PHP is probably the most popular scripting language on the web. It is used to enhance
web pages. With PHP, you can do things like create username and password login
pages, check details from a form, create forums, picture galleries, surveys, and a whole
lot more. If you’ve come across a web page that ends in PHP, then the author has
written some programming code to liven up the plain, old HTML.
PHP is known as a server-sided language. That’s because the PHP doesn’t get
executed on your computer, but on the computer you requested the page from. The
results are then handed over to you, and displayed in your browser. Other scripting
languages you may have heard of are ASP, Python and Perl.
The most popular explanation of just what PHP stands for is “Hypertext Pre-
processor”. But that would make it HPP, surely? An alternative explanation is that
the initials come from the earliest version of the program, which was called Personal
Home Page Tools. At least you get the letters “PHP” in the right order!
3G E-LEARNING
PHP 201
<head>
<title>Example</title>
</head>
<body>
<?php
echo “Hi, I’m a PHP script!”;
?>
</body>
</html>
Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages
contain HTML with embedded code that does “something” (in this case, output “Hi,
I’m a PHP script!”). The PHP code is enclosed in special start and end processing
instructions <?php and ?> that allow you to jump into and out of “PHP mode.”
3G E-LEARNING
202 Introduction to Computer Programming and Web Designing
3G E-LEARNING
PHP 203
HTML can also be written inside the PHP code of your page, which allows you
to format text while keeping blocks of code together. This will also help you write
organized, efficient code, and the browser (and, more importantly, the person viewing
the site) won’t know the difference.
PHP can also be written as a standalone program with no HTML at all. This is
helpful for storing your connection variables, redirecting your visitors to another page
of your site, or performing other functions.
3G E-LEARNING
204 Introduction to Computer Programming and Web Designing
Short tags are, as one might expect, the shortest option You
must do one of two things to enable PHP to recognize the tags:
■■ Choose the --enable-short-tags configuration option
when you’re building PHP.
■■ Set the short_open_tag setting in your [Link] file to on.
This option must be disabled to parse XML with PHP
because the same syntax is used for XML tags.
ASP-style tags
ASP-style tags mimic the tags used by Active Server Pages to
delineate code blocks. ASPstyle tags look like this:
<%...%>
3G E-LEARNING
PHP 205
Multi-lines printing: Here are the examples to print multiple lines in a single print
statement:
<?
# First Example
print <<<END
This uses the “here document” syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
# Second Example
print “This spans
3G E-LEARNING
206 Introduction to Computer Programming and Web Designing
Multi-lines comments: They are generally used to provide pseudocode algorithms and
more detailed explanations when necessary. The multiline style of commenting is the
same as in C. Here are the example of multi lines comments.
<?
/* This is a comment with multiline
Author : Mohammad Mohtashim
Purpose: Multiline Comments Demo
Subject: PHP
*/
print “An example with multi line comments”;
?>
3G E-LEARNING
PHP 207
2; // multiple lines
3G E-LEARNING
208 Introduction to Computer Programming and Web Designing
<?php
echo “Hello PHP!!!!!”;
?>
Now run this script as command prompt as follows:
$ php [Link]
Hello PHP!!!!!
3G E-LEARNING
PHP 209
3G E-LEARNING
210 Introduction to Computer Programming and Web Designing
define(“PROGRAM”, “PHP”);
define(“VERSION”, “5.5.14”);
// Using constants
echo ‘Current ‘ . PROGRAM . ‘ version is: ‘ . VERSION;
?>
PHP Integers
Integers are whole numbers, without a decimal point (..., -2,
-1, 0, 1, 2, ...). Integers can be specified in decimal (base 10),
hexadecimal (base 16 - prefixed with 0x) or octal (base 8 -
prefixed with 0) notation, optionally preceded by a sign (- or +).
<?php
$a = 123; // decimal number
var_dump($a);
3G E-LEARNING
PHP 211
echo “<br>”;
Remember
$c = 0x1A; // hexadecimal number Since PHP
5.4+ you
var_dump($c); can also specify
integers in binary
echo “<br>”; (base 2) notation.
To use binary
notation precede
the number with
0b (e.g. $var =
$d = 0123; // octal number 0b11111111;).
var_dump($d);
?>
PHP Strings
Strings are sequences of characters, where every character is
the same as a byte.
A string can hold letters, numbers, and special characters and
it can be as large as up to 2GB (2147483647 bytes maximum).
The simplest way to specify a string is to enclose it in single
quotes (e.g. ‘Hello world!’), however you can also use double
quotes (“Hello world!”).
<?php
$a = ‘Hello world!’;
echo $a;
echo “<br>”;
$b = “Hello world!”;
3G E-LEARNING
212 Introduction to Computer Programming and Web Designing
echo $b;
echo “<br>”;
$b = 10.2e3;
var_dump($b);
echo “<br>”;
$c = 4E-10;
var_dump($c);
?>
PHP Booleans
Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).
<?php
// Assign the value TRUE to a variable
$show_error = True;
3G E-LEARNING
PHP 213
var_dump($show_error);
?>
PHP Arrays
An array is a variable that can hold more than one value at a time. It is useful to
aggregate a series of related items together, for example a set of country or city names.
An array is formally defined as an indexed collection of data values. Each index (also
known as the key) of an array is unique and references a corresponding value.
<?php
$colors = array(“Red”, “Green”, “Blue”);
var_dump($colors);
echo “<br>”;
$color_codes = array(
“Red” => “#ff0000”,
“Green” => “#00ff00”,
“Blue” => “#0000ff”
);
var_dump($color_codes);
?>
PHP Objects
An object is a data type that not only allows storing data but also information on,
how to process that data. An object is a specific instance of a class which serve as
templates for objects. Objects are created based on this template via the new keyword.
Every object has properties and methods corresponding to those of its parent class.
Every object instance is completely independent, with its own properties and methods,
and can thus be manipulated independently of other objects of the same class.
Here’s a simple example of a class definition followed by the object creation.
3G E-LEARNING
214 Introduction to Computer Programming and Web Designing
<?php
// Class definition
class greeting{
// properties
public $str = “Hello World!”;
// methods
function show_greeting(){
return $this->str;
}
}
PHP NULL
The special NULL value is used to represent empty variables in PHP. A variable of type
NULL is a variable without any data. NULL is the only possible value of type null.
<?php
$a = NULL;
var_dump($a);
echo “<br>”;
$b = “Hello World!”;
$b = NULL;
3G E-LEARNING
PHP 215
var_dump($b);
?>
When a variable is created without a value in PHP like $var; it is automatically assigned
a value of null. Many novice PHP developers mistakenly considered both $var1 =
NULL; and $var2 = “”; are same, but this is not true. Both variables are different —
the $var1 has null value while $var2 indicates no value assigned to it.
PHP Resources
A resource is a special variable, holding a reference to an external resource.
Resource variables typically hold special handlers to opened files and database
connections.
<?php
// Open a file for reading
$handle = fopen(“[Link]”, “r”);
var_dump($handle);
echo “<br>”;
3G E-LEARNING
216 Introduction to Computer Programming and Web Designing
The following example will show you these arithmetic operators in action:
Example:
<?php
$x = 10;
$y = 4;
echo($x + $y); // 0utputs: 14
echo($x - $y); // 0utputs: 6
echo($x * $y); // 0utputs: 40
echo($x / $y); // 0utputs: 2.5
echo($x % $y); // 0utputs: 2
?>
3G E-LEARNING
PHP 217
The following example will show you these assignment operators in action:
Example:
<?php
$x = 10;
echo $x; // Outputs: 10
$x = 20;
$x += 30;
echo $x; // Outputs: 50
$x = 50;
$x -= 20;
echo $x; // Outputs: 30
$x = 5;
$x *= 25;
echo $x; // Outputs: 125
$x = 50;
3G E-LEARNING
218 Introduction to Computer Programming and Web Designing
$x /= 10;
echo $x; // Outputs: 5
$x = 100;
$x %= 15;
echo $x; // Outputs: 10
?>
3G E-LEARNING
PHP 219
$x = 10;
echo $x++; // Outputs: 10
echo $x; // Outputs: 11
$x = 10;
echo --$x; // Outputs: 9
3G E-LEARNING
220 Introduction to Computer Programming and Web Designing
$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>
3G E-LEARNING
PHP 221
The following example will show you these string operators in action:
Example:
<?php
$x = “Hello”;
$y = “ World!”;
echo $x . $y; // Outputs: Hello World!
$x .= $y;
echo $x; // Outputs: Hello World!
?>
3G E-LEARNING
222 Introduction to Computer Programming and Web Designing
The following example will show you these array operators in action:
Example:
<?php
$x = array(“a” => “Red”, “b” => “Green”, “c” => “Blue”);
$y = array(“u” => “Yellow”, “v” => “Orange”, “w” => “Pink”);
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y); // Outputs: boolean false
var_dump($x === $y); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x <> $y); // Outputs: boolean true
var_dump($x !== $y); // Outputs: boolean true
?>
3G E-LEARNING
PHP 223
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The following example will output “Have a nice weekend!” if the current day is Friday,
otherwise it will output “Have a nice day!”:
<html>
<body>
<?php
$d=date(“D”);
if ($d==”Fri”)
echo “Have a nice weekend!”;
else
echo “Have a nice day!”;
?>
</body>
</html>
3G E-LEARNING
224 Introduction to Computer Programming and Web Designing
Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The following example will output “Have a nice weekend!” if the current day is Friday,
and “Have a nice Sunday!” if the current day is Sunday. Otherwise it will output “Have a
nice day!”:
<html>
<body>
<?php
$d=date(“D”);
if ($d==”Fri”)
echo “Have a nice weekend!”;
elseif ($d==”Sun”)
echo “Have a nice Sunday!”;
else
3G E-LEARNING
PHP 225
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
3G E-LEARNING
226 Introduction to Computer Programming and Web Designing
Example
The switch statement works in an unusual way. First it evaluates the given expression,
then seeks a label to match the resulting value. If a matching value is found, then the
code associated with the matching label will be executed. If none of the labels match,
then the statement will execute any specified default code.
<html>
<body>
<?php
$d=date(“D”);
switch ($d)
{
case “Mon”:
echo “Today is Monday”;
break;
case “Tue”:
echo “Today is Tuesday”;
break;
case “Wed”:
echo “Today is Wednesday”;
break;
case “Thu”:
echo “Today is Thursday”;
break;
case “Fri”:
echo “Today is Friday”;
break;
case “Sat”:
3G E-LEARNING
PHP 227
Syntax
for (initialization; condition; increment)
{
3G E-LEARNING
228 Introduction to Computer Programming and Web Designing
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop
iterations. A variable may be declared here for this purpose and it is traditional to
name it $i.
Example
The following example makes five iterations and changes the assigned value of two
variables on each pass of the loop:
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo (“At the end of the loop a=$a and b=$b” );
?>
</body>
</html>
3G E-LEARNING
PHP 229
Example
This example decrements a variable value on each iteration of the loop and the counter
increments until it reaches 10 when the evaluation becomes false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo (“Loop stopped at i = $i and num = $num” );
?>
</body>
3G E-LEARNING
230 Introduction to Computer Programming and Web Designing
</html>
Syntax
do
{
code to be executed;
}while (condition);
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10:
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}while( $i < 10 );
echo (“Loop stopped at i = $i” );
3G E-LEARNING
PHP 231
?>
</body>
</html>
Loop stopped at i = 10
Syntax
foreach (array as value)
{
code to be executed;
}
Example
Try out the following example to list out the values of an array.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo “Value is $value <br />”;
3G E-LEARNING
232 Introduction to Computer Programming and Web Designing
}
?>
</body>
</html>
Numeric Array
These arrays can store numbers, strings and any object but their
index will be represented by numbers. By default, the array
index starts from zero.
3G E-LEARNING
PHP 233
Example
The following example demonstrates how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in
function reference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo “Value is $value <br />”;
}
/* Second method to create array. */
$numbers[0] = “one”;
$numbers[1] = “two”;
$numbers[2] = “three”;
$numbers[3] = “four”;
$numbers[4] = “five”;
foreach( $numbers as $value )
{
echo “Value is $value <br />”;
}
?>
</body>
</html>
3G E-LEARNING
234 Introduction to Computer Programming and Web Designing
Associative Arrays
Remember
The associative arrays are very similar to numeric arrays in
Don’t
keep
term of functionality but they are different in terms of their
associative index. Associative array will have their index as string so that
array inside you can establish a strong association between key and values.
double quote To store the salaries of employees in an array, a numerically
while printing,
otherwise it indexed array would not be the best choice. Instead, we could
would not return use the employees names as the keys in our associative array,
any value. and the value would be their respective salary.
Example
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(
“mohammad” => 2000,
“qadir” => 1000,
“zara” => 500
3G E-LEARNING
PHP 235
);
echo “Salary of mohammad is “. $salaries[‘mohammad’] . “<br />”;
echo “Salary of qadir is “. $salaries[‘qadir’]. “<br />”;
echo “Salary of zara is “. $salaries[‘zara’]. “<br />”;
/* Second method to create array. */
$salaries[‘mohammad’] = “high”;
$salaries[‘qadir’] = “medium”;
$salaries[‘zara’] = “low”;
echo “Salary of mohammad is “. $salaries[‘mohammad’] . “<br />”;
echo “Salary of qadir is “. $salaries[‘qadir’]. “<br />”;
echo “Salary of zara is “. $salaries[‘zara’]. “<br />”;
?>
</body>
</html>
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional
array are accessed using multiple index.
3G E-LEARNING
236 Introduction to Computer Programming and Web Designing
Example
In this example, we create a two dimensional array to store marks of three students in
three subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
“mohammad” => array
(
“physics” => 35,
“maths” => 30,
“chemistry” => 39
),
“qadir” => array
(
“physics” => 30,
“maths” => 32,
“chemistry” => 29
),
“zara” => array
(
“physics” => 31,
“maths” => 22,
“chemistry” => 39
)
);
3G E-LEARNING
PHP 237
You can also use double quotation marks (“). However, single and double quotation
marks work in different ways. Strings enclosed in single-quotes are treated almost
literally, whereas the strings delimited by the double quotes replaces variables with
the string representations of their values as well as specially interpreting certain escape
sequences.
The escape-sequence replacements are:
■■ \n is replaced by the newline character
■■ \r is replaced by the carriage-return character
3G E-LEARNING
238 Introduction to Computer Programming and Web Designing
// Outputs: 28
echo strlen($my_str);
?>
3G E-LEARNING
PHP 239
Example
<?php
$my_str = ‘The quick brown fox jumps over the lazy dog.’;
// Outputs: 9
echo str_word_count($my_str);
?>
Example
<?php
$my_str = ‘If the facts do not fit the theory, change the facts.’;
You can optionally pass the fourth argument to the str_replace() function to know how
many times the string replacements was performed, like this.
3G E-LEARNING
240 Introduction to Computer Programming and Web Designing
Example
<?php
$my_str = ‘If the facts do not fit the theory, change the facts.’;
Reversing a String
The strrev() function reverses a string.
Example
<?php
$my_str = ‘You can do anything, but not everything.’;
3G E-LEARNING
PHP 241
3G E-LEARNING
242 Introduction to Computer Programming and Web Designing
{
$browser = “Mozilla”;
}
$platform = “An unidentified OS!”;
if( preg_match( “/Windows/i”, “$viewer” ) )
{
$platform = “Windows!”;
}
else if ( preg_match( “/Linux/i”, “$viewer” ) )
{
$platform = “Linux!”;
}
echo(“You are using $browser on $platform”);
?>
</body>
</html>
This is producing the following result on my machine. This result may be different
for your computer, depending on what browser you are using.
3G E-LEARNING
PHP 243
<html>
<body>
<?php
srand( microtime() * 1000000 );
$num = rand( 1, 4 );
switch( $num )
{
case 1: $image_file = “/home/images/[Link]”;
break;
case 2: $image_file = “/home/images/[Link]”;
break;
case 3: $image_file = “/home/images/[Link]”;
break;
case 4: $image_file = “/home/images/[Link]”;
break;
}
echo “Random Image : <img src=$image_file />”;
?>
</body>
</html>
3G E-LEARNING
244 Introduction to Computer Programming and Web Designing
3G E-LEARNING
PHP 245
Browser Redirection
The PHP header() function supplies raw HTTP headers to the
browser and can be used to redirect it to another location. Keyword
The redirection script should be at the very top of the page to Browser
prevent any other part of the page from loading. The target is an
is specified by the Location: header as the argument to the application
program that
header() function. After calling this function the exit() function provides a way
can be used to halt parsing of rest of the code. The following to look at and
example demonstrates how you can redirect a browser request interact with all
the information
to another web page. Try out this example by putting the source on the World
code in [Link] script. Wide Web.
<?php
if( $_POST[“location”] )
{
$location = $_POST[“location”];
header( “Location:$location” );
exit();
}
?>
<html>
<body>
<p>Choose a site to visit :</p>
3G E-LEARNING
246 Introduction to Computer Programming and Web Designing
3G E-LEARNING
PHP 247
# HTTP Header
print “Content-Type:application/octet-stream; name=\”FileName\”\r\n”;
print “Content-Disposition: attachment; filename=\”FileName\”\r\n\n”;
# Actual File Content
open( FILE, “<FileName” );
while(read(FILE, $buffer, 100) )
{
print(“$buffer”);
}
Spaces are removed and replaced with the + character and any other non-
alphanumeric characters are replaced with a hexadecimal values. After the information
is encoded, it is sent to the server.
■■ The GET method produces a long string that appears in your server logs, in
the browser’s Location: box.
■■ The GET method is restricted to send up to 1024 characters only.
3G E-LEARNING
248 Introduction to Computer Programming and Web Designing
■■ Never use GET method if you have password or other sensitive information
to be sent to the server.
■■ GET can’t be used to send binary data, like images or word documents, to
the server.
■■ The data sent by GET method can be accessed using QUERY_STRING
environment variable.
■■ The PHP provides $_GET associative array to access all the sent information
using GET method.
Try out the following example by putting the source code in [Link] script.
<?php
if( $_GET[“name”] || $_GET[“age”] )
{
echo “Welcome “. $_GET[‘name’]. “<br />”;
echo “You are “. $_GET[‘age’]. “ years old.”;
exit();
}
?>
<html>
<body>
<form action=”<?php $_PHP_SELF ?>” method=”GET”>
Name: <input type=”text” name=”name” />
Age: <input type=”text” name=”age” />
<input type=”submit” />
</form>
</body>
</html>
3G E-LEARNING
PHP 249
<?php
if( $_POST[“name”] || $_POST[“age”] ) Did You
{ Know?
Some
echo “Welcome “. $_POST[‘name’]. “<br />”; huge websites
like Facebook,
Yahoo, Flickr,
echo “You are “. $_POST[‘age’]. “ years old.”; and Wikipedia
are built in PHP.
exit(); Most of the
major content
} management
systems
?> (CMS), such
as WordPress,
<html> Drupal, Joomla
and Magento are
<body> also built in PHP.
3G E-LEARNING
250 Introduction to Computer Programming and Web Designing
3G E-LEARNING
PHP 251
ROLE MODEL
RASMUS LERDORF: FATHER OF PHP
Lerdorf’s Career
From September 2002 to November 2009 he was employed
by Yahoo! Inc. as an Infrastructure Architecture Engineer. In
2010, he joined WePay in order to develop their application
programming [Link] 2011 he was a roving
consultant for startups. On 22 February 2012 he announced
on Twitter that he had joined [Link] July, 2013 Rasmus joined
Jelastic as a senior advisor to help them with the creation of
new technology. Lerdorf is a frequent speaker at Open Source
conferences around the world. During his keynote presentation
at OSCMS 2007, he presented a security vulnerability in each
of the projects represented at the conference that year.
3G E-LEARNING
252 Introduction to Computer Programming and Web Designing
SUMMARY
■■ PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used
open source general-purpose scripting language that is especially suited for
web development and can be embedded into HTML.
■■ PHP programs are written using a text editor, such as Notepad, Simple Text, or
vi, just like HTML pages. However, unlike HTML, PHP files end with a .php
extension. This extension signifies to the server that it needs to parse the PHP
code before sending the resulting HTML code to the viewer’s web browser.
■■ PHP not only allows HTML pages to be created on the fly, but it is invisible
to your web site visitors. The only thing they see when they view the source
of your code is the resulting HTML output. In this respect, PHP gives you a
bit more security by hiding your programming logic.
■■ A statement in PHP is any expression that is followed by a semicolon (;).Any
sequence of valid PHP statements that is enclosed by the PHP tags is a valid
PHP program.
■■ A constant is an identifier (name) for a simple value. A constant value cannot
change during the execution of the script (except for magic constants). Constants
are useful for storing data that doesn’t change while the script is running.
■■ The values assigned to a PHP variable may be of different data types including
simple string and numeric types to more complex data types like arrays and
objects.
■■ An array is a variable that can hold more than one value at a time. It is useful
to aggregate a series of related items together, for example a set of country
or city names.
■■ An object is a data type that not only allows storing data but also information
on, how to process that data. An object is a specific instance of a class which
serve as templates for objects. Objects are created based on this template via
the new keyword.
■■ The arithmetic operators are used to perform common arithmetical operations,
such as addition, subtraction, multiplication etc.
3G E-LEARNING
PHP 253
a. 78
b. 19
c. NULL
d. 5
e. 0
3. There are three different kind of arrays:
a. Numeric array, String array, Multidimensional array
b. Numeric array, Associative array, Dimensional array
c. Numeric array, Associative array, Multidimensional array
d. Const array, Associative array, Multidimensional array
4. Variables always start with a ........ in PHP
a. Pond-sign
b. Yen-sign
c. Dollar-sign
d. Euro-sign
5. PHP runs on different platforms (Windows, Linux, Unix, etc.)
a. True
b. False
REVIEW QUESTIONS
1. What is PHP? Explain the PHP syntax.
2. How can we encrypt the username and password using php?
3G E-LEARNING
254 Introduction to Computer Programming and Web Designing
3G E-LEARNING
PHP 255
REFERENCES
1. “Usage statistics of PHP for websites”. W3Techs - World Wide Web Technology
Surveys. W3Techs. 26 April 2021. Retrieved 26 April 2021.
2. Lerdorf, Rasmus (2007). “Slide 3”. slides for ‘PHP on Hormones’ talk. The PHP
Group. Retrieved 2009-06-22.
3. “Rasmus Lerdorf, Senior Technical Yahoo: PHP, Behind the Mic”. 2003-11-19.
Archived from the original on 2013-07-28.
4. “[Link]: Re: Function name consistency”. [Link]. 2013-12-28. Retrieved
2014-02-09.
5. “PHP – Acronym Meaning Vote”. [Link]. Archived from the original on August
15, 2000.
6. Lerdorf, Rasmus (1995-06-08). “Announce: Personal Home Page Tools (PHP Tools)”.
Newsgroup: [Link]. Retrieved 2006-09-17.
7. Lerdorf, Rasmus (2007-04-26). “PHP on Hormones”. The Conversations Network.
Archived from the original (mp3) on 2019-01-06. Retrieved 2009-06-22.
8. “Problems with PHP”. Retrieved 20 December 2010.
9. Lerdorf, Rasmus (2012-07-20). “I wonder why people keep writing that PHP was
ever written in Perl. It never was. #php”. Twitter. Retrieved 2014-09-04.
10. Rasmus Lerdorf (Dec 16, 2013). “Re: Flexible function naming”. Newsgroup: php.
internals. Retrieved December 26, 2013.
3G E-LEARNING
CHAPTER JAVASCRIPT
7 PROGRAMMING
LEARNING OBJECTIVES
1. Define JavaScript
2. Explain the JavaScript syntax
3. Describe the JavaScript data types
4. Discuss the operators and If-Else
5. Understand the JavaScript loops and functions
6. Discuss the JavaScript objects
258 Introduction to Computer Programming and Web Designing
INTRODUCTION
JavaScript was introduced in 1995 as a way to add programs to web pages in the
Netscape Navigator browser. The language has since been adopted by all other major
graphical web browsers. It has made modern web applications possible—applications
with which you can interact directly, without doing a page reload for every action. But
it is also used in more traditional websites to provide various forms of interactivity
and cleverness. It is important to note that JavaScript has almost nothing to do with
the programming language named Java. The similar name was inspired by marketing
considerations, rather than good judgment. When JavaScript was being introduced,
the Java language was being heavily marketed and was gaining popularity. Someone
thought it was a good idea to try to ride along on this success. JavaScript uses some
of the same ideas found in Java, the compiled object-oriented programming derived
from C++. JavaScript code can be imbedded in HTML pages and interpreted by the
Web browser (or client). JavaScript can also be run at the server as in Microsoft’s Active
Server Pages before the page is sent to the requestor. Both Microsoft and Netscape
browsers support JavaScript, but sometimes in slightly different ways.
3G E-LEARNING
JavaScript Programming 259
founder of Netscape. In September of 1995 the name was changed to LiveScript, then
in December of the same year, upon receiving a trademark license from Sun, the name
JavaScript was adopted. This was somewhat of a marketing move at the time, with
Java being very popular around then.
In 1996 - 1997 JavaScript was taken to ECMA to carve out a standard specification,
which other browser vendors could then implement based on the work done at
Netscape. The work done over this period of time eventually led to the official release
of ECMA-262 Ed.1: ECMAScript is the name of the official standard, with JavaScript
being the most well-known of the implementations. ActionScript 3 is another well-
known implementation of ECMAScript, with extensions.
The standards process continued in cycles, with releases of ECMAScript 2 in 1998
and ECMAScript 3 in 1999, which is the baseline for modern day JavaScript. The “JS2”
or “original ES4” work led by Waldemar Horwat (then of Netscape, now at Google)
started in 2000 and at first, Microsoft seemed to participate and even implemented
some of the proposals in their [Link] language.
Over time it was clear though that Microsoft had no intention of cooperating or
implementing proper JS in IE, even though they had no competing proposal and they
had a partial (and diverged at this point) implementation on the .NET server side. So
by 2003 the JS2/original-ES4 work was mothballed.
The next major event was in 2005, with two major happenings in JavaScript’s
history. First, Brendan Eich and Mozilla rejoined Ecma as a not-for-profit member and
work started on E4X, ECMA-357, which came from ex-Microsoft employees at BEA
(originally acquired as Crossgain). This led to working jointly with Macromedia, who
were implementing E4X in ActionScript 3(ActionScript 3 was a fork of Waldemar’s
JS2/original-ES4 work).
So, along with Macromedia (later acquired by Adobe), work restarted on ECMAScript
4 with the goal of standardizing what was in AS3 and implementing it in SpiderMonkey.
To this end, Adobe released the “AVM2”, code named Tamarin, as an open source
project. But Tamarin and AS3 were too different from web JavaScript to converge, as
was realized by the parties in 2007 and 2008.
Alas, there was still turmoil between the various players; Doug Crockford — then
at Yahoo! — joined forces with Microsoft in 2007 to oppose ECMAScript 4, which led
to the ECMAScript 3.1 effort.
While all of this was happening the open source and developer communities set
to work to revolutionize what could be done with JavaScript. This community effort
was sparked in 2005 when Jesse James Garrett released a white paper in which he
coined the term Ajax, and described a set of technologies, of which JavaScript was the
3G E-LEARNING
260 Introduction to Computer Programming and Web Designing
3G E-LEARNING
JavaScript Programming 261
Advantages of JavaScript
The merits of using JavaScript are:
■■ Less server interaction: You can validate user input
before sending the page off to the server. This saves
server traffic, which means less load on your server.
■■ Immediate feedback to the visitors: They don’t have to
wait for a page reload to see if they have forgotten to
enter something.
■■ Increased interactivity: You can create interfaces that
react when the user hovers over them with a mouse
or activates them via the keyboard.
■■ Richer interfaces: You can use JavaScript to include such
items as dragand-drop components and sliders to give
a Rich Interface to your site visitors. Did You
Know?
The
Limitations of JavaScript first popular
graphical Web
We cannot treat JavaScript as a full-fledged programming browser, which
language. It lacks the following important features: played an
important part
■■ Client-side JavaScript does not allow the reading or in expanding the
writing of files. This has been kept for security reason. growth of the
nascent World
■■ JavaScript cannot be used for networking applications Wide Web.
because there is no such support available.
■■ JavaScript doesn’t have any multithreading or
multiprocessor capabilities.
Once again, JavaScript is a lightweight, interpreted
programming language that allows you to build interactivity
into otherwise static HTML pages.
3G E-LEARNING
262 Introduction to Computer Programming and Web Designing
<script ...>
JavaScript code
</script>
The script tag takes two important attributes:
■■ Language: This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
■■
Type: This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to “text/javascript”.
So your JavaScript syntax will look as follows.
<script language=”javascript” type=”text/javascript”>
JavaScript code
</script>
<html>
<body>
<script language=”javascript” type=”text/javascript”>
<!--
[Link] (“Hello World!”)
//-->
</script>
3G E-LEARNING
JavaScript Programming 263
</body>
</html>
Hello World!
But when formatted in a single line as follows, you must use semicolons:
<script language=”javascript” type=”text/javascript”>
<!--
var1 = 10; var2 = 20;
//-->
3G E-LEARNING
264 Introduction to Computer Programming and Web Designing
</script>
Case Sensitivity
JavaScript is a case-sensitive language. This means that the
language keywords, variables, function names, and any other
Remember identifiers must always be typed with a consistent capitalization
Care of letters. So the identifiers Time and TIME will convey different
should
be taken while meanings in JavaScript.
writing variable
and function
names in
JavaScript.
7.3 JAVASCRIPT DATA TYPES
One of the most fundamental characteristics of a programming
language is the set of data types it supports. These are the
type of values that can be represented and manipulated in a
programming language.
JavaScript allows you to work with three primitive data types:
3G E-LEARNING
JavaScript Programming 265
//-->
</script>
You can also declare multiple variables with the same var
keyword as follows:
<script type=”text/javascript”>
Remember
<!--
Java does
not make
var money, name; a distinction
between integer
//--> values and
floating-point
</script> values. All
numbers in
JavaScript are
represented as
Storing a value in a variable is called variable initialization. You floating-point
can do variable initialization at the time of variable creation or values. JavaScript
represents
at a later point in time when you need that variable. numbers using
the 64-bit
For instance, you might create a variable named money and floating-point
assign the value 2000.50 to it later. For another variable, you format defined
can assign a value at the time of initialization as follows. by the IEEE 754
standard.
<script type=”text/javascript”>
<!--
var name = “Ali”;
var money;
money = 2000.50;
//-->
</script>
3G E-LEARNING
266 Introduction to Computer Programming and Web Designing
declaration what type of value the variable will hold. The value type of a variable can
change during the execution of a program and JavaScript takes care of it automatically.
3G E-LEARNING
JavaScript Programming 267
7.4 OPERATORS
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and
5 are called operands and ‘+’ is called the operator. JavaScript
supports the following types of operators.
JavaScript has the following types of operators.
Keyword
■■ Assignment operators Binary
■■ Comparison operators describes
a numbering
■■ Arithmetic operators scheme in which
■■ Bitwise operators there are only
two possible
■■ Logical operators values for each
digit: 0 and 1.
■■ String operators
■■ Conditional (ternary) operator
■■ Comma operator
■■ Relational operator
JavaScript has both binary and unary operators, and one
special ternary operator, the conditional operator. A binary
operator requires two operands, one before the operator and
one after the operator:
operand1 operator operand2
For example, 3+4 or x*y.
A unary operator requires a single operand, either before or after
the operator:
operator operand
or
operand operator
For example, x++ or ++x.
3G E-LEARNING
268 Introduction to Computer Programming and Web Designing
There are also compound assignment operators that are shorthand for the operations
listed in the following table:
Destructuring
The destructuring assignment syntax is a JavaScript expression that makes it possible
to extract data from arrays or objects using a syntax that mirrors the construction of
array and object literals.
var foo = [“one”, “two”, “three”];
// without destructuring
var one = foo[0];
var two = foo[1];
var three = foo[2];
// with destructuring
var [one, two, three] = foo;
3G E-LEARNING
JavaScript Programming 269
Comparison operators
Operator Description Examples
returning true
Equal (==) Returns true if the operands are equal. 3 == var1
“3” == var1
3 == ‘3’
Not equal(!=) Returns true if the operands are not equal. var1 != 4
var2 != “3”
Strict equal(===) Returns true if the operands are equal and of the same 3 === var1
type. See also [Link] and sameness in JS.
Strict not Returns true if the operands are of the same type but not var1 !== “3”
equal (!==) equal, or are of different type. 3 !== ‘3’
Greater than(>) Returns true if the left operand is greater than the right var2 > var1
operand. “12” > 2
Greater than or Returns true if the left operand is greater than or equal to var2 >= var1
equal (>=) the right operand. var1 >= 3
Less than (<) Returns true if the left operand is less than the right var1 < var2
operand. “2” < 12
Less than or Returns true if the left operand is less than or equal to the var1 <= var2
equal (<=) right operand. var2 <= 5
3G E-LEARNING
270 Introduction to Computer Programming and Web Designing
1 / 2; // 0.5
1 / 2 == 1.0 / 2.0; // this is true
In addition to the standard arithmetic operations (+, -, *
/), JavaScript provides the arithmetic operators listed in the
following table:
Arithmetic operators
Operator Description Example
Remainder (%) Binary operator. Returns the integer 12 % 5 returns 2.
remainder of dividing the two operands.
Increment (++) Unary operator. Adds one to its operand. If x is 3, then ++xsets x to
If used as a prefix operator (++x), returns 4 and returns 4,
the value of its operand after adding one; whereas x++ returns 3 and,
if used as a postfix operator (x++), returns only then, sets x to 4.
the value of its operand before adding
one.
Decrement (--) Unary operator. Subtracts one from its If x is 3, then --xsets x to
operand. The return value is analogous to 2 and returns 2,
that for the increment operator. whereas x-- returns 3 and,
only then, sets x to 2.
Unary Unary operator. Returns the negation of If x is 3, then -xreturns -3.
negation (-) its operand.
Unary plus (+) Unary operator. Attempts to convert the +”3” returns 3.
operand to a number, if it is not already. +true returns 1.
Exponentiation Calculates the base to 2 ** 3 returns 8.
operator (**) the exponent power, that is, baseexponent 10 ** -1 returns 0.1.
3G E-LEARNING
JavaScript Programming 271
numbers. For example, the decimal number nine has a binary representation of 1001.
Bitwise operators perform their operations on such binary representations, but they
return standard JavaScript numerical values.
The following table summarizes JavaScript’s bitwise operators.
Bitwise operators
Operator Usage Description
Bitwise AND a & b Returns a one in each bit position for which the corresponding
bits of both operands are ones.
Bitwise OR a|b Returns a zero in each bit position for which the corresponding
bits of both operands are zeros.
Bitwise XOR a^b Returns a zero in each bit position for which the corresponding
bits are the same.
[Returns a one in each bit position for which the corresponding
bits are different.]
Bitwise NOT ~a Inverts the bits of its operand.
Left shift a << b Shifts a in binary representation b bits to the left, shifting in zeros
from the right.
Sign-propagating a >> b Shifts a in binary representation b bits to the right, discarding bits
right shift shifted off.
Zero-fill right shift a >>> Shifts a in binary representation b bits to the right, discarding bits
b shifted off, and shifting in zeros from the left.
■■ Each bit in the first operand is paired with the corresponding bit in the second
operand: first bit to first bit, second bit to second bit, and so on.
■■ The operator is applied to each pair of bits, and the result is constructed bitwise.
For example, the binary representation of nine is 1001, and the binary representation
of fifteen is 1111. So, when the bitwise operators are applied to these values, the results
are as follows:
3G E-LEARNING
272 Introduction to Computer Programming and Web Designing
3G E-LEARNING
JavaScript Programming 273
Logical Operators
Operator Usage Description
Logical expr1 Returns expr1 if it can be converted to false; otherwise,
AND(&&) && returns expr2. Thus, when used with Boolean
expr2 values, && returns true if both operands are true; otherwise,
returns false.
Logical expr1 || Returns expr1 if it can be converted to true; otherwise,
OR (||) expr2 returns expr2. Thus, when used with Boolean
values, || returns true if either operand is true; if both are false,
returns false.
Logical !expr Returns false if its single operand can be converted to true;
NOT (!) otherwise, returns true.
Examples of expressions that can be converted to false are those that evaluate to
null, 0, NaN, the empty string (“”), or undefined.
The following code shows examples of the && (logical AND) operator.
var a1 = true && true; // t && t returns true
var a2 = true && false; // t && f returns false
var a3 = false && true; // f && t returns false
var a4 = false && (3 == 4); // f && f returns false
var a5 = “Cat” && “Dog”; // t && t returns Dog
var a6 = false && “Cat”; // f && t returns false
var a7 = “Cat” && false; // t && f returns false
3G E-LEARNING
274 Introduction to Computer Programming and Web Designing
For example,
[Link](“my “ + “string”); // console logs the string “my string”.
The shorthand assignment operator += can also be used to concatenate strings.
For example,
var mystring = “alpha”;
mystring += “bet”; // evaluates to “alphabet” and assigns this value to mystring.
3G E-LEARNING
JavaScript Programming 275
3G E-LEARNING
276 Introduction to Computer Programming and Web Designing
// Arrays
var trees = [“redwood”, “bay”, “cedar”, “oak”, “maple”];
0 in trees; // returns true
3 in trees; // returns true
6 in trees; // returns false
“bay” in trees; // returns false (you must specify the index number,
// not the value at that index)
“length” in trees; // returns true (length is an Array property)
// built-in objects
“PI” in Math; // returns true
var myString = new String(“coral”);
“length” in myString; // returns true
// Custom objects
var mycar = { make: “Honda”, model: “Accord”, year: 1998 };
“make” in mycar; // returns true
“model” in mycar; // returns true
instanceof
The instanceof operator returns true if the specified object is of the specified object
type. The syntax is:
objectName instanceof objectType
where objectName is the name of the object to compare to objectType, and objectType
3G E-LEARNING
JavaScript Programming 277
is an object type, such as Date or Array. Use instanceof when you need to confirm the
type of an object at runtime. For example, when catching exceptions, you can branch to
different exception-handling code depending on the type of exception thrown.
For example, the following code uses instanceof to determine whether theDay is
a Dateobject. Because theDay is a Date object, the statements in the if statement execute.
var theDay = new Date(1995, 12, 17);
if (theDay instanceof Date) {
// statements to execute
}
Operator precedence
Operator type Individual operators
member . []
call / create instance () new
negation/increment ! ~ - + ++ -- typeof void delete
multiply/divide */%
addition/subtraction +-
bitwise shift << >> >>>
relational < <= > >= in instanceof
equality == != === !==
bitwise-and &
bitwise-xor ^
bitwise-or |
logical-and &&
logical-or ||
conditional ?:
assignment = += -= *= /= %= <<= >>= >>>= &=
^= |=
comma ,
3G E-LEARNING
278 Introduction to Computer Programming and Web Designing
7.5 IF-ELSE
JavaScript supports conditional statements which are used to perform different actions
based on different conditions.
The JavaScript if-else statement is used to execute the code whether condition is
true or false. There are three forms of if statement in JavaScript.
■■ If Statement
■■ If else statement
■■ if else if statement
If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given are.
if(expression){
//content to be evaluated
}
Flowchart of JavaScript If statement:
3G E-LEARNING
JavaScript Programming 279
3G E-LEARNING
280 Introduction to Computer Programming and Web Designing
Let’s see the example of if-else statement in JavaScript to find out the even or odd
number.
<script>
var a=20;
if(a%2==0){
[Link](“a is even number”);
}
else{
[Link](“a is odd number”);
}
</script>
3G E-LEARNING
JavaScript Programming 281
a is even number
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
<script>
var a=20;
if(a==10){
[Link](“a is equal to 10”);
}
else if(a==15){
3G E-LEARNING
282 Introduction to Computer Programming and Web Designing
a is equal to 20
3G E-LEARNING
JavaScript Programming 283
default:
code to be executed if above values are not matched;
}
Let’s see the simple example of switch statement in javascript.
<script>
var grade=’B’;
var result;
switch(grade){
case ‘A’:
result=”A Grade”;
break;
case ‘B’:
result=”B Grade”;
break;
case ‘C’:
result=”C Grade”;
break;
default:
result=”No Grade”;
}
[Link](result);
</script>
3G E-LEARNING
284 Introduction to Computer Programming and Web Designing
Remember <script>
The var grade=’B’;
switch
statement is fall- var result;
through i.e. all
the cases will be
evaluated if you
switch(grade){
don’t use break
statement. case ‘A’:
result+=” A Grade”;
case ‘B’:
result+=” B Grade”;
case ‘C’:
result+=” C Grade”;
default:
result+=” No Grade”;
}
[Link](result);
</script>
3G E-LEARNING
JavaScript Programming 285
■■ while loop
■■ do-while loop
■■ for-in loop Remember
Array is
7.6.1 JavaScript For loop a data
structure that
contains a group
The JavaScript for loop iterates the elements for the fixed number of elements.
of times. It should be used if number of iteration is known. The
syntax of for loop is given are.
for (initialization; condition; increment)
{
code to be executed
}
Output:
1
2
3
4
5
3G E-LEARNING
286 Introduction to Computer Programming and Web Designing
while (condition)
{
code to be executed
}
Output:
11
12
13
14
15
3G E-LEARNING
JavaScript Programming 287
Output:
21
22
23
24
25
3G E-LEARNING
288 Introduction to Computer Programming and Web Designing
how objects behave in JavaScript, you will find this loop very useful.
The syntax of ‘for..in’ loop is:
for (variablename in object){
statement or block to execute
}
In each iteration, one property from object is assigned to variablename and this loop
continues till all the properties of the object are exhausted.
Example
Try the following example to implement ‘for-in’ loop. It prints the web browser’s
Navigator object.
<html>
<body>
<script type=”text/javascript”>
<!--
var aProperty;
[Link](“Navigator Object Properties<br /> “);
for (aProperty in navigator)
{
[Link](aProperty);
[Link](“<br />”);
}
[Link] (“Exiting from the loop!”);
//-->
</script>
<p>Set the variable to different object and then try...</p>
3G E-LEARNING
JavaScript Programming 289
</body>
</html>
Output:
Navigator Object Properties
serviceWorker
webkitPersistentStorage
webkitTemporaryStorage
geolocation
doNotTrack
onLine
languages
language
userAgent
product
platform
appVersion
appName
appCodeName
hardwareConcurrency
maxTouchPoints
vendorSub
vendor
productSub
cookieEnabled
mimeTypes
plugins
3G E-LEARNING
290 Introduction to Computer Programming and Web Designing
javaEnabled
getStorageUpdates
getGamepads
webkitGetUserMedia
vibrate
getBattery
sendBeacon
registerProtocolHandler
unregisterProtocolHandler
Exiting from the loop!
Set the variable to different object and then try...
7.7 FUNCTIONS
A function is a group of reusable code which can be called anywhere in your program.
This eliminates the need of writing the same code again and again. It helps programmers
in writing modular codes. Functions allow a programmer to divide a big program into
a number of small and manageable functions. Like any other advanced programming
language, JavaScript also supports all the features necessary to write modular code
using functions. We were using these functions again and again, but they had been
written in core JavaScript only once.
We need to define it. The most common way to define a function in JavaScript is by
using the function keyword, followed by a unique function name, a list of parameters
(that might be empty), and a statement block surrounded by curly braces.
Syntax
The basic syntax is shown here.
<script type=”text/javascript”>
<!--
function functionname(parameter-list)
{
3G E-LEARNING
JavaScript Programming 291
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters:
<script type=”text/javascript”>
<!--
function sayHello()
{
alert(“Hello there”);
}
//-->
</script>
3G E-LEARNING
292 Introduction to Computer Programming and Web Designing
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type=”button” onclick=”sayHello()” value=”Say Hello”>
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Output:
Click the following button to call the function
<html>
<head>
<script type=”text/javascript”>
function sayHello(name, age)
{
3G E-LEARNING
JavaScript Programming 293
Output:
Click the following button to call the function
<html>
3G E-LEARNING
294 Introduction to Computer Programming and Web Designing
<head>
<script type=”text/javascript”>
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate(‘Zara’, ‘Ali’);
[Link] (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type=”button” onclick=”secondFunction()” value=”Call Function”>
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Output:
Click the following button to call the function
3G E-LEARNING
JavaScript Programming 295
Example
The following example to learn how to implement nested functions.
<head>
<script type=”text/javascript”>
<!--
function hypotenuse(a, b) {
function square(x) { return x*x; }
3G E-LEARNING
296 Introduction to Computer Programming and Web Designing
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type=”button” onclick=”secondFunction()” value=”Call Function”>
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Output:
Click the following button to call the function
Syntax
Following is the syntax to create a function using Function() constructor along with the
new operator.
<script type=”text/javascript”>
<!--
var variablename = new Function(Arg1, Arg2..., “Function Body”);
//-->
</script>
3G E-LEARNING
JavaScript Programming 297
The Function() constructor expects any number of string arguments. The last
argument is the body of the function – it can contain arbitrary JavaScript statements,
separated from each other by semicolons. Notice that the Function() constructor is not
passed any argument that specifies a name for the function it creates. The unnamed
functions created with the Function() constructor are called anonymous functions.
Example
The following example.
<html>
<head>
<script type=”text/javascript”>
<!--
var func = new Function(“x”, “y”, “return x*y;”);
function secondFunction(){
var result;
result = func(10,20);
[Link] ( result );
}
//-->
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type=”button” onclick=”secondFunction()” value=”Call Function”>
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
3G E-LEARNING
298 Introduction to Computer Programming and Web Designing
Output:
Click the following button to call the function
object={property1:value1,property2:value2.....propertyN:valueN}
<script>
emp={id:102,name:”Shyam Kumar”,salary:40000}
3G E-LEARNING
JavaScript Programming 299
Output
102 Shyam Kumar 40000
<script>
var emp=new Object();
[Link]=101;
[Link]=”Ravi Malik”;
[Link]=50000;
[Link]([Link]+” “+[Link]+” “+[Link]);
</script>
Output:
101 Ravi 50000
3G E-LEARNING
300 Introduction to Computer Programming and Web Designing
Output:
103 Vimal Jaiswal 30000
<script>
function emp(id,name,salary){
[Link]=id;
[Link]=name;
[Link]=salary;
3G E-LEARNING
JavaScript Programming 301
[Link]=changeSalary;
function changeSalary(otherSalary){
[Link]=otherSalary;
}
}
e=new emp(103,”Sonoo Jaiswal”,30000);
[Link]([Link]+” “+[Link]+” “+[Link]);
[Link](45000);
[Link](“<br>”+[Link]+” “+[Link]+” “+[Link]);
</script>
Keyword
A
Output: constructor is a
special method
of a class or
structure in
103 Sonoo Jaiswal 30000 object-oriented
programming
103 Sonoo Jaiswal 45000 that initializes
an object of that
type.
7.8.3 Arrays
The Array object lets you store multiple values in a single
variable. It stores a fixed-size sequential collection of elements
of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection
of variables of the same type.
There are 3 ways to construct array in JavaScript
■■ By array literal
■■ By creating instance of Array directly (using new
keyword)
■■ By using an Array constructor (using new keyword)
3G E-LEARNING
302 Introduction to Computer Programming and Web Designing
Array literal
The syntax of creating array using array literal is given are:
var arrayname=[value1,value2.....valueN];
<script>
var emp=[“Sonoo”,”Vimal”,”Ratan”];
for (i=0;i<[Link];i++){
[Link](emp[i] + “<br/>”);
}
</script>
Output:
Sonoo
Vimal
Ratan
Array directly
The syntax of creating array directly is given are:
var arrayname=new Array();
new keyword is used to create instance of array.
Let’s see the example of creating array directly.
<script>
var i;
var emp = new Array();
3G E-LEARNING
JavaScript Programming 303
emp[0] = “Arun”;
emp[1] = “Varun”;
emp[2] = “John”;
for (i=0;i<[Link];i++){
[Link](emp[i] + “<br>”);
}
</script>
Output:
Arun
Varun
John
<script>
var emp=new Array(“Jai”,”Vijay”,”Smith”);
for (i=0;i<[Link];i++){
[Link](emp[i] + “<br>”);
}
</script>
Output:
3G E-LEARNING
304 Introduction to Computer Programming and Web Designing
Jai
Vijay
Smith
7.8.4 String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
■■ By string literal
■■ By string object (using new keyword)
By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given are:
var stringname=”string value”;
Output:
This is string literal
3G E-LEARNING
JavaScript Programming 305
<script>
var stringname=new String(“hello javascript string”);
[Link](stringname);
</script>
Output:
hello javascript string
3G E-LEARNING
306 Introduction to Computer Programming and Web Designing
Output:
v
Output:
javascript concat example
<script>
var s1=”javascript from javatpoint indexof”;
var n=[Link](“from”);
[Link](n);
</script>
Output:
11
3G E-LEARNING
JavaScript Programming 307
<script>
var s1=”javascript from javatpoint indexof”;
var n=[Link](“java”);
[Link](n);
</script>
Output:
16
<script>
var s1=”JavaScript toLowerCase Example”;
var s2=[Link]();
[Link](s2);
</script>
Output:
javascript tolowercase example
3G E-LEARNING
308 Introduction to Computer Programming and Web Designing
<script>
var s1=”JavaScript toUpperCase Example”;
var s2=[Link]();
[Link](s2);
</script>
Output:
JAVASCRIPT TOUPPERCASE EXAMPLE
<script>
var s1=”abcdefgh”;
var s2=[Link](2,5);
[Link](s2);
</script>
Output:
cde
3G E-LEARNING
JavaScript Programming 309
var s2=[Link]();
[Link](s2);
</script>
Output:
javascript trim
3G E-LEARNING
310 Introduction to Computer Programming and Web Designing
ROLE MODEL
BRENDAN EICH: CREATOR OF THE
JAVASCRIPT PROGRAMMING LANGUAGE
Early Life
Brendan Eich received his bachelor’s degree in mathematics
and computer science at Santa Clara [Link] received
his master’s degree in 1985 from the University of Illinois at
Urbana-Champaign.
Eich started his career at Silicon Graphics, working for
seven years on operating system and network [Link] then
worked for three years at MicroUnity Systems Engineering
writing microkernel and DSP code, and doing the very first
MIPS R4000 port of GCC.
3G E-LEARNING
JavaScript Programming 311
Mozilla
In early 1998, Eich co-founded the Mozilla project, with a website at [Link], that
was meant to manage open-source contributions to the Netscape source code. He
served as Mozilla’s chief [Link] bought Netscape in 1999. After AOL shut down
the Netscape browser unit in July 2003, Eich helped spin out the Mozilla Foundation.
In August 2005, after serving as Lead Technologist and as a member of the Board
of Directors of the Mozilla Foundation, Eich became CTO of the newly founded Mozilla
Corporation, meant to be the Mozilla Foundation’s for-profit arm.
3G E-LEARNING
312 Introduction to Computer Programming and Web Designing
SUMMARY
■■ Javascript is a dynamic computer programming language. It is lightweight and
most commonly used as a part of web pages, whose implementations allow
client-side script to interact with the user and make dynamic pages. It is an
interpreted programming language with object-oriented capabilities.
■■ Client-side JavaScript is the most common form of the language. The script
should be included in or referenced by an HTML document for the code to
be interpreted by the browser.
■■ The JavaScript code is executed when the user submits the form, and only if
all the entries are valid, they would be submitted to the Web Server.
■■ An assignment operator assigns a value to its left operand based on the value
of its right operand. The simple assignment operator is equal (=), which assigns
the value of its right operand to its left operand. That is, x = y assigns the
value of y to x.
■■ The destructuring assignment syntax is a JavaScript expression that makes it
possible to extract data from arrays or objects using a syntax that mirrors the
construction of array and object literals.
■■ The comma operator (,) simply evaluates both of its operands and returns the
value of the last operand. This operator is primarily used inside a for loop, to
allow multiple variables to be updated each time through the loop.
■■ The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.
■■ A function is a group of reusable code which can be called anywhere in your
program. This eliminates the need of writing the same code again and again.
It helps programmers in writing modular codes.
3G E-LEARNING
JavaScript Programming 313
c. None of These
d. Browser
3. JavaScript is designed for following purpose -
a. To Style HTML Pages
b. To add interactivity to HTML Pages.
c. To Perform Server Side Scripting Opertion
d. To Execute Query Related to DB on Server
4. …………….javaScript is also called client-side JavaScript.
a. Microsoft
b. Navigator
c. LiveWire
d. Native
5. What are variables used for in JavaScript Programs?
a. Storing numbers, dates, or other values
b. Varying randomly
c. Causing high-school algebra flashbacks
d. None of the above
REVIEW QUESTIONS
1. What is JavaScript?
2. What is function hoisting in JavaScript?
3. How to create arrays in JavaScript?
4. What is an object in JavaScript, give an example?
5. How you will add function as a property in a JavaScript object? Give an example.
3G E-LEARNING
314 Introduction to Computer Programming and Web Designing
REFERENCES
1. “Function – JavaScript”. MDN Web Docs. Retrieved 2021-10-30.
2. “Inheritance and the prototype chain”. Mozilla Developer Network. Mozilla.
Archived from the original on April 25, 2013. Retrieved April 6, 2013.
3. “Properties of the Function Object”. [Link]. Archived from the original
on January 28, 2013. Retrieved May 26, 2013.
4. Flanagan 2006, p. 141.
5. Haverbeke, Marijn (2011). Eloquent JavaScript. No Starch Press. pp. 95–97. ISBN
978-1-59327-282-1.
6. Herman, David (2013). Effective JavaScript. Addison-Wesley. p. 83. ISBN 978-0-
321-81218-6.
7. Herman, David (2013). Effective JavaScript. Addison-Wesley. pp. 125–127. ISBN
978-0-321-81218-6.
8. Katz, Yehuda (12 August 2011). “Understanding “Prototypes” in JavaScript”.
Archived from the original on 5 April 2013. Retrieved April 6, 2013.
9. The many talents of JavaScript for generalizing Role-Oriented Programming
approaches like Traits and Mixins Archived 2017-10-05 at the Wayback Machine,
[Link], April 11, 2014.
3G E-LEARNING
INDEX
J S
JavaScript 257, 258, 259, 260, 261, 262, 263, 264, Simple Mail Transport Protocol (SMTP) 171
265, 266, 267, 268, 269, 270, 271, 274, 278, 279, 280, Standard Generalized Markup Language (SGML)
281, 282, 284, 285, 286, 287, 288, 290, 293, 295, 297, 122, 124, 161
298, 300, 301, 302, 304, 305, 306, 307, 308, 310, 312, String Constants 7, 11
313 Strings 211, 237, 238, 239
JavaScript statements 261, 297 Style sheets 167, 175, 195
JavaScript variable 265, 266 switch statement 31, 32
Joint Photographic Experts Group (JPEG) 134, System Programming Language 2, 46
161
T
L
table 139, 141, 143, 144, 145, 147, 162
Logical Operator 13
U
Loops 227
Loop statements 33 unordered list 102, 117
user-defined functions 4, 5
M
V
Mozilla 258, 259, 310, 311
Variables 208, 209, 253
N
W
Numeric Constants 7
Web browser 88, 89, 117
O
Web developers 124, 134, 136, 161
Operating system 2, 46 Web pages 122, 132, 134, 135, 136, 143, 161
Operators 215, 216, 218, 219, 220, 221 Web server 131, 147, 148, 149, 150, 151, 161
website 95, 100, 106, 117
P
while loop 285, 286, 287
pixels 135, 143, 161 while statement 229, 230
World Wide Web Consortium (W3C) 88, 117, 122
R
X
relational operator 275
XHTML document 125, 126, 128, 130, 135, 136,
137, 148, 149, 150, 161
XHTML syntax 121, 125, 126, 161
3G E-LEARNING