0% found this document useful (0 votes)
13 views334 pages

Computer Programming & Web Design Guide

This document is an e-book titled 'Introduction to Computer Programming and Web Designing' published by Bibliotex Digital Library in 2023. It includes contributions from various experts in fields such as psychology, agriculture, health sciences, and engineering, providing a wide array of knowledge. The book is structured into chapters with clear learning objectives, keywords, and review questions to aid in understanding the material.

Uploaded by

Eil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views334 pages

Computer Programming & Web Design Guide

This document is an e-book titled 'Introduction to Computer Programming and Web Designing' published by Bibliotex Digital Library in 2023. It includes contributions from various experts in fields such as psychology, agriculture, health sciences, and engineering, providing a wide array of knowledge. The book is structured into chapters with clear learning objectives, keywords, and review questions to aid in understanding the material.

Uploaded by

Eil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION TO COMPUTER

PROGRAMMING AND
WEB DESIGNING

BIBLIOTEX Digital Library

[Link]
INTRODUCTION TO COMPUTER PROGRAMMING AND WEB DESIGNING

BIBLIOTEX Digital Library

[Link]
email: info@[Link]

e-book Edition 2023


ISBN: 978-1-98468-140-9 (e-book)

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.

© 2023 3G E-learning LLC

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.

LEARNING OBJECTIVES 2 Hotel Engineering and Maintenance

INTRODUCTION
Maintenance is the key for providing better built environment to building customers

See what you are going to cover and what


and users. Maintenance of the hospitality building is significant as its effectiveness
will directly affect the quality of services, which have direct and significant effect on
CHAPTER PREVENTIVE AND satisfying customers’ wants and expectations.
There are two paths to improving your hotel’s profitability: increase revenue and/
1 BREAKDOWN
you should already know at the start of
or cut costs. All things equal, it’s best to focus on increasing revenue because it’s
additive; more revenue means that your business is growing. However, when there’s
MAINTENANCE a downturn, and revenue is harder to come by, controlling costs becomes even more
important for the bottom line.

each chapter “Preventive Maintenance: Don’t start today by doing yesterday’s work.”

- Deniece Schofield

ABOUT THIS CHAPTER


While it’s tempting to reduce budgets and defer maintenance, the shortsightedness
may leave a financial burden in the not-too-distant future. Here’s what you need to
know about preventive maintenance, its role in your hotel’s overall profitability and
how to successfully implement it at your hotel.
LEARNING OBJECTIVES

An introduction is a beginning of section which


After studying this chapter, you will be able to: 1.1 HOTEL MAINTENANCE MANAGEMENT AND ITS IMPACT
1. Understand hotel maintenance management and its impact Hotel maintenance encompasses all maintenance actions that are taken in order to
2. Perform preventive maintenance maintain and repair all systems, components, and equipment that are a part of a

states the purpose and goals of the topics


3. Discuss about breakdown maintenance hotel property. The exact scope of maintenance work greatly varies from one hotel to
4. Identify role & importance of maintenance department in the hotel industry with emphasis another, based on the size of the hotel and the range of services it offers.
on its relation with other departments of the hotel
5. Explain duties and organization of maintenance department Hotel maintenance can be looked at as one type of building maintenance that places
extra focus on issues that concern hotel guests. In other words, hotel maintenance puts

which are discussed in the chapter. It also


more emphasis on things like plumbing, HVAC, lighting, and visual representation
of the whole establishment.

starts the topics in brief.


3G E-LEARNING

REMEMBER 10 Hotel Engineering and Maintenance


50 Hotel Engineering and Maintenance

Besides the lower energy output, firewood with high moisture

This revitalizes a must read information of


stress your maintenance crew out and leave guests disappointed
content is more difficult to light. Moreover, the moisture from
and even angry.
the fuel cools the flames and evaporated steam mixed with the
Thankfully, there are plenty of tools available to property combustible gases act as a fire-extinguisher leading to incomplete
managers today that make putting together and implementing combustion as well as smoke.

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

This section contains some important


This allows your hotel to maximize its budgeting and decrease
unexpected and often incredibly cost expenditures. When regular are contributing to growing demand for wood fuel. Densified
maintenance is being performed on schedule, your engineers wood fuel (wood pellets, briquettes) and chips in particular are
and other maintenance staff will have a much better overview gaining in importance due to the increasing share of heating
of how your equipment is functioning. This gives them more and electricity generation applications that utilize woodfuel.

definitions that are discussed in the chapter.


accurate estimates regarding every piece of equipment and Consequently, Europe’s wood production increased from 125
when they can expect to have to fix it or, eventually, replace it. million m³ in 2001 to nearly 160 million m³ in 2011.
This foresight allows hoteliers to plan their future expenses

A keyword is an index entry that identifies a


appropriately and accurately. The better your budgeting is during How is Firewood Used for Cooking?
the course of the year, the easier it will be to cope with the
inevitable event of a surprise malfunction that will need to be For households in developing countries, particularly in Sub-
repaired on the fly. Saharan Africa, it is common for rural households to use firewood

specific record or document. It also gives the


as their main source of cooking energy. The use of firewood in
Proper preventative maintenance helps you to reduce the rural areas is still predominant since it is often the only available,
chances of these types of malfunctions occurring and also makes accessible and affordable fuel in the region.
them much easier to deal with when they do occur.

extra information to the reader and an easy


Preventive maintenance management doesn’t have to only
deal with your equipment, it can also extend to keeping track

way to remember the word definition.


3G E-LEARNING

3G E-LEARNING

v
DID YOU KNOW? Start with Your Business Name 35 Start with Your Business Name 19

This section equip readers the interesting facts


Patent too. If your service is based on a certain area, you might
extend to other cities. So, select a broad name that can
Trademark and copyright differences can get murky, so let’s first
encompass your future growth.
review the purpose and use of a patent. When you hear the
word “patent,” you should think invention – everything from 7. Make sure you have a related domain:- Once you have

and figures of the topic.


Post-it notes to animal ear protectors. narrowed down your name options, you have to make
sure the name you want to use is available. Check if the
name is already registered as a trademark or acquired
Copyright by another business. If you are planning on having an
Artists, authors, and other creative seek out copyrights for their online presence, which you definitely should, you’ll
work. A copyright covers physical works of art, music recordings want to make sure the desired domain is available by
of any kind, written works, and performance arts. The length of a doing a domain name check.
copyright lasts for the lifetime of the author plus 70 [Link] A domain name can impact your online visibility and
a copyright technically is created as soon as you create a piece of influences your marketing efforts as well. That said, you should
intellectual property, without some form of proof, it’s very difficult not necessarily abandon a good business name just because an
enforce that protection in federal court. You also do not need to have exact domain is not available.
Did You

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,

The book cabinets’ examples to illustrate


■ Add modifiers to the name. on your success.
and symbols that identify commercial goods or services. While The wrong
■ Be creative with domain selection. Nowadays, businesses name can do
they protect the brand name of the goods, they do not protect
use different top-level domains to make their URLs worse than fail
the actual good or service from being replicated and sold under to connect with
more memorable.

specific ideas in each chapter.


a different name. customers; it can
Choosing a name can be challenging when you are setting also result in
out to start a business, but not something to agonize over! insurmountable
business and
McDonald’s might trademark the name “Egg McMuffin,” but it will not stop other fast Remember to get opinions and ideas from friends, family or legal hurdles. In
food restaurants from serving a ham, egg, and cheese sandwich on an English muffin even potential customers. It’s always a good idea to get a few contrast, a clear,
and calling it something else. different points of view. powerful name
can be extremely
A business name is only your first step towards building a helpful in your
marketing and
brand. Though it’ll give your business a good first impression, branding efforts.
This is where branding and marketing comes in. Your competitors it’s up to you to meet the customer expectations and bring your
might offer similar products, but your customers choose yours business to success.
because of your recognizable brand and iconography.

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

A biography of someone who has/had acquired ROLE MODEL CASE STUDY

remarkable success in their respective field as


PAUL V. MOCKAPETRIS: AMERICAN COMPUTER GLOBAL BUSINESS SERVICES COMPANY
SCIENTIST AND INTERNET PIONEER, INVENTED Company owns a corporate domain portfolio of several hundred domains. A large,
THE INTERNET DOMAIN incumbent corporate registrar provided their domain management and registry services.

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

us the ability to imagine our future selves.


Computer Science from the University of California, Irvine in Business Challenges
1982.
In 2016, Company domain management stakeholders in IT and marketing experienced
Paul’s earliest professional work was while he was an MIT
a number of challenges managing their domain assets. With multiple service vendors,
student: an early multiprocessor operating system for the Architecture Machine Group;
their domain management costs were excessive and several vendors presented control
virtual machine operating systems for IBM; and simulation work at Draper Labs.
and management problems. Internal processes for ordering, managing and tracking
At UC Irvine for his PhD, Paul worked on the Distributed Computer System domains were inefficient, requiring manual steps and administrative workarounds.
where he built one of the earliest ring LAN hardware systems and matching network Domain asset management and support was dependent upon time-consuming staff
operating system. processes combined with external professional services.

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

This reveals what students need to create and


deployment of early root servers and DNS operations. The DNS is an essential part were impeding business objectives such as brand innovation and customer digital
of all web and email addresses and essentially every application on the internet. experience.
Paul has been active in internet community service, spending 3 years as program They determined to find a solution that would offer:

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.)

working and problem solving.


Solution and Outcomes
At present, he is Chairman and Chief Scientist at Nominum, where he has returned
to his interest in DNS, advancing naming and directory systems for the internet. He Company’s brand and IT management decided to consolidate their domain portfolio
also serves and advisor and board member for various other startups. Paul continues on a single, integrated digital asset management platform that would meet the needs
to believe that the internet’s future is ahead of it. of internal stakeholders: digital marketing, brand management, IT, finance, and IP
legal (intellectual property) teams. Company selected Authentic Web Inc. including
Paul is a member of the ACM and IEEE.
turnkey project management service to consolidate disparate domain name services
to a single platform.

MULTIPLE CHOICE QUESTIONS


86 Digital Skills for Small Business 88 Digital Skills for Small Business

MULTIPLE CHOICE QUESTIONS REVIEW QUESTIONS


1. A full domain name is a sequence of labels separated by ________. 1. What exactly is a domain name?
2. How to choose a domain name for business? Explain.

This is given to the students for progress check


a. semicolons
b. dots 3. Discuss how to register a domain name? What will it cost?
4. What’s the difference between my domain name and web hosting?
c. colons

at the end of each chapter.


5. What is the best way to secure a domain name?
d. none of the above
6. Which domain is best for business?
2. A ________ server loads all information from the primary server.
a. primary Answer to Multiple Choice Questions
b. secondary
1. (b) 2. (b) 3. (d) 4. (a) 5. (c)
c. zone
d. none of the above 6. (c) 7. (a) 8. (c) 9. (b) 10. (c)
3. The first level in the generic domains section allows ______ possible labels.

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.”

This section is to analyze the knowledge and


4. If a label is not terminated by a null string, it is called a __________.
Accessed Dec. 20, 2019.
a. PQDN
2. Domain Name Wire podcast. “Frank Schilling Explains Price Hike – DNW Podcast
b. FQDN #127.” Accessed Dec. 20, 2019.

ability of the reader. c. SQDN


d. none of the above
3. Domain Name Wire. “ICANN Shuts Down Alpnames Domain Name Registrar.”
Accessed Dec. 20, 2019.
5. What a server is responsible for or has authority over is called a _________. 4. [Link]. “Domain Registration Agreement.” Accessed Dec. 20, 2019.
a. domain 5. ICANN. “FAQs: How Long Does a Registration Last? Can It be Renewed?”
Accessed Dec. 20, 2019.
b. label
6. No-IP Knowledge Base. “How Long Until the Domain I just Registered is Active?”
c. zone
Accessed Dec. 20, 2019.
d. none of the above
7. PR Newswire. “GoDaddy Acquires Worldwide Media Inc. Domain Name Portfolio.”

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.

References refer those books which discuss


d. none of the above

the topics given in the chapters in almost


same man­ner.

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

Chapter 4 XHTML 121


Introduction 122
4.1 Overview of XHTML 122
4.1.1 Basic Understanding 124
4.2 XHTML Syntax 125
4.3 Headers 130
4.4 Linking 131
4.5 Images 133
4.5.1 Special Characters and More Line Breaks 137
4.6 Unordered Lists 139
4.6.1 Nested and Ordered Lists 139
4.7 Basic XHTML Tables 141
4.7.1 Intermediate XHTML Tables and Formatting 145
4.8 XHTML Forms 147
4.8.1 Complex XHTML Forms 150
Summary 161
Multiple Choice Questions 161
Review Questions 162
References 163

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

Chapter 6 PHP 199


Introduction 200
6.1 Overview of PHP 200
6.1.1 Common Uses of PHP 201
6.1.2 Advantages of PHP over Other Languages 201
6.1.3 PHP in the Web Environment 202
6.2 PHP Syntax 204
6.2.1 Commenting PHP Code 205
6.2.2 PHP is Whitespace Insensitive 206
6.2.3 PHP is case sensitive 207
6.3 Variables in PHP 208
6.3.1 Naming Conventions for PHP Variables 209
6.3.2 Constants in PHP 209
6.3.3 Naming Conventions for PHP Constants 210
6.4 Data Types in PHP 210
6.5 Operator Types 215
6.5.1 Arithmetic Operators 216
6.5.2 Assignment Operators 216
6.5.3 Comparison Operators 218
6.5.4 Incrementing and Decrementing Operators 219
6.5.5 Logical Operators 220
6.5.6 String Operators 221
x
6.5.7 Array Operators 221
6.6 Decision Making 222
6.7 Loop Types 227
6.8 Arrays 232
6.9 String in PHP 237
6.10 Web Concepts 241
6.10.1 Identifying Browser & Platform 241
6.10.2 GET and POST Methods 247
Summary 252
Multiple Choice Questions 252
Review Questions 253
References 255

Chapter 7 JavaScript Programming 257


Introduction 258
7.1 What is JavaScript? 258
7.1.1 History of JavaScript 258
7.1.2 Client-Side JavaScript 260
7.2 JavaScript Syntax 261
7.3 JavaScript Data types 264
7.3.1 JavaScript Variables 264
7.3.2 JavaScript Variable Names 266
7.3.3 JavaScript Reserved Words 266
7.4 Operators 267
7.4.1 Assignment operators 267
7.4.2 Comparison Operators 269
7.4.3 Arithmetic operators 270
7.4.4 Bitwise Operators 270
7.4.5 Logical Operators 273
7.4.6 String Operators 274
7.4.7 Conditional (ternary) Operator 274
7.4.8 Comma Operator 275
7.4.9 Relational Operators 275
7.4.10 Operator Precedence 277
7.5 If-Else 278
7.5.1 JavaScript If...else Statement 279
7.5.2 JavaScript If...else if statement 281
7.5.3 JavaScript Switch 282
7.6 JavaScript Loops 284
7.6.1 JavaScript For loop 285
7.6.2 JavaScript while loop 286
7.6.3 JavaScript do while loop 287

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

After studying this chapter, you will be able to:

1. Describe the character set


2. Understand the data types in ‘C’
3. Explain the operators and expressions
4. Describe the structure for looping statements
2 Introduction to Computer Programming and Web Designing

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

1.1 CHARACTER SET


The character set is the fundamental raw-material for any language. Like natural
languages, computer languages will also have well defined character-set, which is

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.

1.1.1 Structure of a ‘C’ Program


The Complete structure of C program is
The basic components of a C program are:
■■ main()
■■ pair of braces { }
■■ declarations and statements
■■ user defined functions

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.

1.2 DATA TYPES IN ‘C’ Remember


Every
variable
which is used
in the program
must be declared
as what data-
type it is.

Derived data types such as arrays, structures, union and


pointers and user defined data types such as typedef and enum.

3G E-LEARNING
6 Introduction to Computer Programming and Web Designing

1.2.1 Basic Data Types


There are four basic data types in C language. They are Integer
data, character data, floating point data and double data types.

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

double - Double – precision floating point number value.

1.2.2 Data Kinds in C


Various data kinds that can be included in any C program can
fall in to the following.
■■ Constants/Literals
■■ Reserve Words Keywords
■■ Delimeters
■■ Variables/Identifiers
a. Constans/Literals: Constants are those, which do not
change, during the execution of the program. Constants may
be categorized in to:
■■ Numeric Constants
■■ Character Constants
■■ String Constants

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

■■ It may have an optional + or – sign. In the absence of sign, the constant is


assumed to be positive.
■■ Commas and blank spaces are not permitted.
■■ It should not have a period as part of it.
Some examples of valid decimal integer constants:
456
-123
Some examples of invalid decimal integer constants:
4.56 - Decimal point is not permissible
1,23 - Commas are not permitted
ii. An octal integer constant is characterized by the following properties
o It is a sequence of one or more digits ([0…7], symbols of octal number system).
o It may have an optional + or – sign. In the absence of sign, the constant is assumed
to be positive.
o It should start with the digit 0.
o Commas and blank spaces are not permitted.
o It should not have a period as part of it.
Some examples of valid octal integer constants:
0456
-0123
+0123
Some examples of invalid octal integer constants:
04.56 - Decimal point is not permissible
04,56 - Commas are not permitted
x34 - x is not permissible symbol
568 - 8 is not a permissible symbol
iii. An hexadecimal integer constant is characterized by the following properties
■■ It is a sequence of one or more symbols ([0…9][A….Z], the symbols of
Hexadecimal number system).

3G E-LEARNING
Programming in C 9

■■ It may have an optional + or - sign. In the absence of sign, the constant is


assumed to be positive.
■■ It should start with the symbols 0X or 0x.
■■ Commas and blank spaces are not permitted.
■■ It should not have a period as part of it.
Some examples of valid hexadecimal integer constants:
0x456
-0x123
0x56A
0XB78
Some examples of invalid hexadecimal integer constants:
0x4.56 - Decimal point is not permissible
0x4,56 - Commas are not permitted.

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

4,56 - Commas are not permitted


456 - Decimal point missing
ii. Exponential Form
The exponential form offers a convenient way for writing very large and small
real constant. For example, 56000000.00, which can be written as 0.56 *, 10 8 is written
as 0.56E8 or 0.56e8 in exponential form. 0.000000234, which can be written as 0.234 *
10-6 is written as 0.234E-6 or 0.234e-6 in exponential form. The letter E or e stand for
exponential form.
A real constant expressed in exponential form has two parts: (i) Mantissa part, (ii)
Exponent part. Mantissa is the part of the real constant to the left of E or e, and the
Exponent of a real constant is to the right of E or e. Mantissa and Exponent of the
above two number are shown are:

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

23,4e5 - Commas are not allowed


256*e8- * not allowed

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

Rules for naming a variable:-


■■ It can be of letters, digits and underscore( _ )
■■ First letter should be a letter or an underscore, but it should not be a digit.
■■ Reserve words cannot be used as variable names.
Example: basic, root, rate, roll-no etc are valid names.
Declaration of variables:

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”

The Relational Operators are represented in the following manner:


Expression-1 Relational Operator Expression-2
The Expression-1 will be compared with Expression -2 and depending on the
relation the result will be either “TRUE” OR “FALSE”.

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

False && False False


False && True False
Example: a = 5; b = 10; c = 15;

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

Example: a = 5; b = 10; c = 15;

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 >

Where identifier represent a variable and expression Keyword


represents a constant, a variable or a Complex expression. If Data
type or
the two operands in an assignment expression are of different simply type is a
data types, then the value of the expression on the right will classification of
automatically be converted to the type of the identifier on the left. data which tells
the compiler or
Example: Suppose that I is an Integer type Variable then interpreter how
the programmer
1. I = 3.3 3 (Value of I) intends to use the
data.
2. I = 3.9 3 (Value of I)
3. I = 5.74 5 (Value of I)
Multiple assignment
< identifier-1 > = < identifier-2 > = - - - = < identifier-n > =
<exp>;
Example: a,b,c are integers; j is float variable
1. a = b = c = 3;
2. a = j = 5.6; then a = 5 and j value will be 5.6
C contains the following five additional assignment operators
1. += 2.-= 3. += 4. *= 5. /=
The assignment expression is: - Exp1 < Operator> Exp-2
Ex: I = 10 (assume that)
Expression Equivalent to Final Value of ‘I’
1. I + = 5 I = I + 5 15

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

Increment & Decrement Operator


The increment/decrement operator act upon a Single operand and produce a new value
is also called as “unary operator”. The increment operator ++ adds 1 to the operand
and the Decrement operator – subtracts 1 from the operand.
Syntax: < operator >< variable name >;
The ++ or – operator can be used in the two ways.

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

a and a- will be act on operand by decrement value like increment operator.

3G E-LEARNING
Programming in C 19

Conditional operator (or) Ternary operator (? :)


It is called ternary because it uses three expression. The ternary operator acts like
If- Else construction.

Expression-1 is evaluated first. If Exp-1 is true then Exp-2 is evaluated otherwise


it evaluate Exp-3 will be evaluated
Flow Chart:
Exp-1
Exp-2 Exp-3
Exit
Example:
1. a = 5 ; b = 3;
( a> b ? printf (“a is larger”) : printf (“b is larger”));
Output is :a is larger

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

variable value Binary patter


x 23 0001 0111
~x 132 1110 1000

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 ) ;

The first expression is j = 3 and second is j + 2. These expressions are evaluated


from left to right. From the above example I = 5.

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

Example: int i; float x; double d; char c; OUTPUT

Printf (“integer : %d\n”, sizeof(i)); Integer : 2


Printf (“float : %d\n”, sizeof(i)); Float : 4
Printf (“double : %d\n”, sizeof(i)); double : 8
Printf (“char : %d\n”,sizeof(i)); character : 1

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

Data Input & Output


An input/output function can be accessed from anywhere within
a program simply by writing the function name followed by
a list of arguments enclosed in parentheses. The arguments
represent data items that are sent to the function.
Some input/output Functions do not require arguments
though the empty parentheses must still appear. They are:

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);

Where s is a string that was real with gets();


Example:
main()
{
char line[80];
gets(line);
puts(line);
}

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.)

1.4.2 Assignment Statement


Assignment statement can be defined as the statement through which the value obtained
from an expression can be stored in a variable.
The general form of assignment statement is
< variable name> = < arithmetic expression> ;
Example:
sum = a + b + c;
tot = s1 + s2 + s3;
area = ½ * b* h;

1.4.3 Conditional Statements


The conditional expressions are mainly used for decision making. The following
statements are used to perform the task of the conditional operations.
■■ if statement.
■■ If-else statement. Or 2 way if statement
■■ Nested else-if statement.
■■ Nested if –else statement.
■■ Switch statement.

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;
}

SET - I Statements will be executed if the exp is true.


SET – II Statements will be executed if the exp is false.

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;
}

Where constant1, constanat2 — — — are either integer constants or character


constants. When the switch statement is executed the exp is evaluated and control
is transferred directly to the group of statement whose case label value matches the
value of the exp. If none of the case label values matches to the value of the exp then
the default part statements will be executed. If none of the case labels matches to the
value of the exp and the default group is not present then no action will be taken
by the switch statement and control will be transferred out of the switch statement.

3G E-LEARNING
32 Introduction to Computer Programming and Web Designing

A simple switch statement is illustrated are.

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

———
———
}

1.5 STRUCTURE FOR LOOPING


STATEMENTS Did You
Loop statements are used to execute the statements repeatedly Know?
as long as an expression is true. When the expression becomes LOOP is
a programming
false then the control transferred out of the loop. There are three language
kinds of loops in C. designed by Uwe
Schöning, along
■■ while with GOTO and
WHILE.
■■ do-while
■■ for

While Statement
while loop will be executed as long as the exp is true.
Syntax: while (exp)
{
statements;
}

The statements will be executed repeatedly as long as the


exp is true. If the exp is false then the control is transferred out
of the while loop.

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

The statement with in the do-while loop will be executed at


least once. So the do-while loop is called a bottom tested loop.

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

Where expression-1 is used to initialize the control variable.


This expression is executed this expression is executed is only
once at the time of beginning of loop.
Where expression-2 is a logical expression. If expression-2
is true, the statements will be executed, other wise the loop
will be terminated. This expression is evaluated before every

3G E-LEARNING
36 Introduction to Computer Programming and Web Designing

execution of the statement. Where expression-3 is an increment or decrement expression


after executing the statements, the control is transferred back to the expression-3 and
updated. There are different formats available in for loop. Some of the expression of
loop can be omit.

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

1.5.1 Nested Looping Statements


Many applications require nesting of the loop statements,
allowing on loop statement to be embedded with in another
loop statement.
Nesting can be defined as the method of embedding one
control structure with in another control structure.
Keyword
While making control structure s to be reside one with in
Control
structure another, the inner and outer control structures may be of the
is a block of same type or may not be of same type. But, it is essential for
programming us to ensure that one control structure is completely embedded
that analyzes
variables and within another.
chooses a
direction in /*program to implement nesting*/
which to go
based on given #include <stdio.h>
parameters.
main()
{
int a,b,c,
for (a=1,a< 2, a++)
{
printf (“%d”,a)
for (b=1,b<=2,b++)
{
print f(%d”,b)
for (c=1,c<=2,c++)
{
print f( “ My Name is Sunny \n”);
}
}
}
}

3G E-LEARNING
Programming in C 39

1.5.2 Multi Branching Statement (switch), Break, and Continue


For effective handling of the loop structures, C allows the following types of control
break statements.
■■ Break Statement
■■ Continue Statement

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;
}

The Continue Statement


The continue statement is used to bypass the remainder of the current pass through a
loop. The loop does not terminate when a continue statement is encountered. Rather,
the remaining loop statements are skipped and the proceeds directly to the next pass

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.3 Differences between Break and Continue

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.

Early Fascination with Harvard’s Univac I


Ritchie was born on September 9, 1941, in Bronx-ville, New York.
He was born to Alistair Ritchie, a switching systems engineer for
Bell Laboratories, and Jean McGee Ritchie, a homemaker. Ritchie
grew up in New Jersey, and after a childhood in which he did
very well academically, he went on to attend Harvard University.
There he studied science and graduated with a bachelor’s degree
in physics. While he was still going to school, Ritchie happened to
go to a lecture about how Harvard’s computer system, a Univac
I, worked. He was fascinated by what he heard and wanted to
find out more. Outside of his Harvard studies, Ritchie began to
explore computers more thoroughly, and was especially interested
in how they were programmed.
While still at Harvard, Ritchie got a job working at the
Massachusetts Institute of Technology (MIT). At that time
computer programming was not a degree, and computer labs
were looking for anyone with potential to help on their computers.
Ritchie, with his unflagging curiosity, seemed perfect for the job.
Ritchie worked at MIT for many years helping develop, alongside
other scientists, more advanced computer systems and software.

3G E-LEARNING
44 Introduction to Computer Programming and Web Designing

Began Work on Operating Systems


He also began work on developing an operating system for more portable computers.
Most computers at the time took up entire rooms and had limited dial-in access, but
smaller desktop computers were being developed, and these did not have easy to
use operating systems. Ritchie decided that one was needed. MIT, Honeywell, and
General Electric agreed, and administered his project. Other scientists from colleges
and private companies came to help build the system, one that was able to handle
up to a thousand users at once and could be run 24 hours a day. Ritchie never saw
programming as a problem but rather as a puzzle to be solved.
After the project was finished, just about the time that he graduated, Ritchie
determined that computers, rather than physics, would be his career. He got a job at Bell
Labs, where his father had worked for years. At the time, in 1967, it was the nation’s
primary phone provider, and it had one of the best labs in the world, one that was
responsible for developing a multiplicity of technical advances, from new switching
devices to transistors, as well as new computer advances. Ritchie told Investor’s Business
Daily , “Instead of focusing on specific projects, I wanted to be around people with a
lot of experience and ideas. So I started working on various projects to learn my way
around the profession.”

Built Unix to Fulfill Computer Needs


Ritchie began working with Kenneth Thompson, who had joined Bell Labs in 1966.
Both men had been watching how the minicomputer was becoming more and more
popular in the early 1970s. What was needed, they thought, was a simpler and more
feasable interaction between various computers. It took them months to come up with
a solution, but when they were finished they had written the Unix operating system.
An operating system is necessary for a user to copy, delete, edit, and print data files.
It allows a person to move data around from disk to screen to printer and back to
disk for storage. Without an operating system computers would not be accessible to
anyone but an expert few. Before the creation of Unix, operating systems had been
complex and expensive. Unix was comparatively cheap and simple, and it could
be used on just about any machine, which meant buyers were not stuck with the
cumbersome software that came with their computers. They could buy and install a
variety of software systems, because Unix was compatible with all of them. This had
not been possible before.
Ritchie and his team released Unix to the public at a symposium on Operating
Systems Principles that was hosted by IBM, and it was an immediate success. Ritchie
and Thompson then set out to improve the system.

3G E-LEARNING
Programming in C 45

Development of C Programming Language


Unix was written in machine language, which had a small vocabulary and did not
deal well with multiple computers and their memories. So Ritchie combined some
aspects of the older systems with aspects of the new one, and came up with the “C”
programming language. In the early twenty-first century, “C” is still the dominant
language of computer programming. It was such a simple, concise language that almost
every single computer maker at the time switched to it.
“C” uses very little syntax and few instructions, but it is extremely structured
and modular. Because of this it was easy to use in different computers. There were
large blocks of “C” functions that were already written that programmers could copy
whole into their own programs without having to start from scratch, making it faster
and easier to implement. These blocks were easily accessible, available in libraries so
programmers could access them. By the middle of the 1980s “C” had become one of
the most popular programming languages in the world. Because of the speed with
which “C” could be used to write programs and run them, companies began using
“C” to develop their own software.

Continued Drive to Improve Computer Functionality


By 1973 Ritchie and Thompson had re-written the Unix operating system, using “C”
instead of machine language, and had done massive testing on it. It was so simple
to use that programmers all over were switching to smaller machines to do their
programming, giving up the larger computers they thought they would never want to
leave. Bell Labs became Lucent Technologies Inc., and began to sell Unix to developers,
creating a whole new division for the company. Ritchie has credited his success in part
to the fact that he did not have a computer background and therefore had an open
mind to possibilities that others might not have thought existed.
Ritchie became the leader of the Computing Techniques Research Department
at Lucent Technologies in 1990. In that role he wrote applications and managed the
growth of already released operating systems. Over the years Ritchie has received
numerous awards, including the ACM award for the outstanding paper of 1974 in
systems and languages, the IEEE Emmanuel Piore Award in 1982, a Bell Laboratories
Fellow in 1983, an Association for Computing Machinery Turing Award in 1983, an
ACM Software Systems Award in 1983, and an IEEE Hamming Medal in 1990. He was
also elected to the United States National Academy of Engineering in 1988. In April
of 1999 he was the recipient of the United States National Medal of Technology. All
of the awards Ritchie received were in conjunction with Thompson. Ritchie is now
the head of Lucent Technologies’ Systems Software Research Department, and is still
striving to make computers work better and more easily for users.

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.

MULTIPLE CHOICE QUESTIONS


1. Who is father of C Language?
a. Bjarne Stroustrup
b. James A. Gosling
c. Dennis Ritchie
d. Dr. E.F. Codd
2. For 16-bit compiler allowable range for integer constants is …………?
a. -3.4e38 to 3.4e38
b. -32767 to 32768

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.

Answer to Multiple Choice Questions


1. (c) 2. (d) 3. (b) 4. (b) 5. (d)

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

After studying this chapter, you will be able to:

1. Understand the need to object-oriented programming


2. Describe the characteristics of object-oriented languages
3. Focus on C++ and C
4. Understand the C++ programming basics
5. Discuss about basic data types in c++
6. Understand the operators in c++
50 Introduction to Computer Programming and Web Designing

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.

2.1 NEED TO OBJECT-ORIENTED PROGRAMMING


Object-oriented programming was developed because limitations were discovered
in earlier approaches to programming. To appreciate what OOP does, we need to
understand what these limitations are and how they arose from traditional programming
languages.

3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 51

2.1.1 Procedural Languages


C, Pascal, FORTRAN, and similar languages are procedural
languages. That is, each statement in the language tells the
computer to do something: Get some input, add these numbers,
divide by six, display that output. A program in a procedural
language is a list of instructions. For very small programs, no
other organizing principle (often called a paradigm) is needed.
The programmer creates the list of instructions, and the computer
carries them out.

2.1.2 Division into Functions


When programs become larger, a single list of instructions
becomes unwieldy. Few programmers can comprehend a
program of more than a few hundred statements unless it is
broken down into smaller units. For this reason the function
was adopted as a way to make programs more comprehensible Keyword
to their human creators. (The term function is used in C++ and Object-
Oriented
C. In other languages the same concept may be referred to as Programming
a subroutine, a subprogram, or a procedure.) A procedural (OOP) is a
program is divided into functions, and (ideally, at least) each programming
paradigm based
function has a clearly defined purpose and a clearly defined on the concept
interface to the other functions in the program. of “objects”,
which are data
The idea of breaking a program into functions can be further structures that
extended by grouping a number of functions together into a contain data, in
the form of fields,
larger entity called a module (which is often a file), but the
principle is similar: a grouping of components that execute
lists of instructions. 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.

2.1.3 Unrestricted Access


In a procedural program, one written in C for example, there
are two kinds of data. Local data is hidden inside a function, and
is used exclusively by the function. In the inventory program a
display function might use local data to remember which item it
was displaying. Local data is closely related to its function and

3G E-LEARNING
52 Introduction to Computer Programming and Web Designing

is safe from modification by other functions. However, when


two or more functions must access the same data—and this is
true of the most important data in a program—then the data
must be made global, as our collection of inventory items is.
Global data can be accessed by any function in the program.
(We ignore the issue of grouping functions into modules, which
does not materially affect our argument.) The arrangement of
local and global variables in a procedural program is shown
in Figure 1.

Keyword
Variable
is
named memory
locations whose
contents can
change

Figure 1. Global and local variables.

In a large program, there are many functions and many


global data items. The problem with the procedural paradigm is
that this leads to an even larger number of potential connections
between functions and data, as shown in Figure 2.

Figure 2. The procedural paradigm.

This large number of connections causes problems in


several ways. First, it makes a program’s structure difficult to

3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 53

conceptualize. Second, it makes the program difficult to modify. A change made in


a global data item may necessitate rewriting all the functions that access that item.

2.1.4 The Object-Oriented Approach


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.
An object’s functions, called member functions in C++, typically provide the only way to
access its data. If you want to read a data item in an object, you call a member function in
the object. It will access the data and return the value to you. You cannot access the data
directly. The data is hidden, so it is safe from accidental alteration. Data and its functions
are said to be encapsulated into a single entity. Data encapsulation and data hiding are key
terms in the description of object-oriented languages.
If you want to modify the data in an object, you know exactly what functions interact
with it: the member functions in the object. No other functions can access the data. This
simplifies writing, debugging, and maintaining the program.
A C++ program typically consists of a number of objects, which communicate with each
other by calling one another’s member functions. The organization of a C++ program is
shown in Figure 3.

Figure 3. The object-oriented paradigm.

3G E-LEARNING
54 Introduction to Computer Programming and Web Designing

We should mention that what are called member functions


in C++ are called methods in some other object-oriented (OO)
languages (such as Smalltalk, one of the first OO languages).
Also, data items are referred to as attributes or instance
Keyword variables. Calling an object’s member function is referred to as
Object- sending a message to the object. These terms are not official
Oriented
Design is
C++ terminology, but they are used with increasing frequency,
the process especially in object-oriented design.
of planning
a system of
interacting 2.1.5 OOP: An Approach to Organization
objects for
the purpose
of solving Keep in mind that object-oriented programming is not primarily
a software concerned with the details of program operation. Instead, it deals
problem. with the overall organization of the program. Most individual
program statements in C++ are similar to statements in procedural
languages, and many are identical to statements in C. Indeed, an
entire member function in a C++ program may be very similar
to a procedural function in C. It is only when you look at the
larger context that you can determine whether a statement or a
function is part of a procedural C program or an object-oriented
C++ program.
Keyword
Program
Statement
is instructions
that are similar to
English-language
sentences.

Figure 4. The corporate paradigm.

3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 55

2.2 CHARACTERISTICS OF OBJECT-ORIENTED LANGUAGES


Let us briefly examine a few of the major elements of object-oriented languages in
general, and C++ in particular.

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

Elements of the computer-user environment


■■ Windows
■■ Menus
■■ Graphics objects (lines, rectangles, circles)
■■ The mouse, keyboard, disk drives, printer

2.2.2 Data-Storage Constructs


■■ Customized arrays
■■ Stacks
■■ Linked lists
■■ Binary trees

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

User-Defined Data Types


■■ Time
■■ Angles
■■ Complex numbers
■■ Points on the plane

Components in Computer Games


■■ Cars in an auto race
■■ Positions in a board game (chess, checkers)
■■ Animals in an ecological simulation
■■ Opponents and friends in adventure games

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

2.2.6 Creating New Data Types


One of the benefits of objects is that they give the programmer a convenient way to
construct new data types. Suppose you work with two-dimensional positions (such as
x and y coordinates, or latitude and longitude) in your program. You would like to
express operations on these positional values with normal arithmetic operations, such as
position1 = position2 + origin

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.

2.2.7 Polymorphism and Overloading


Note that the = (equal) and + (plus) operators, used in the position arithmetic do
not act the same way they do in operations on built-in types such as int. The objects
position1 and so on are not predefined in C++, but are programmer-defined objects
of class Position. How do the = and + operators know how to operate on objects? The
answer is that we can define new behaviors for these operators. These operations will
be member functions of the Position class.
Using operators or functions in different ways, depending on what they are
operating on, is called polymorphism (one thing with several distinct forms). When
an existing operator, such as + or =, is given the capability to operate on a new data
type, it is said to be overloaded. Overloading is a kind of polymorphism; it is also an
important feature of OOP.

2.3 C++ AND C


C++ is derived from the C language. Strictly speaking, it is a superset of C: Almost
every correct statement in C is also a correct statement in C++, although the reverse
is not true. The most important elements added to C to create C++ concern classes,
objects, and object-oriented programming. (C++ was originally called “C with classes.”)
However, C++ has many other new features as well, including an improved approach to
input/output (I/O) and a new way to write comments. Figure 6 shows the relationship
of C and C++.

3G E-LEARNING
60 Introduction to Computer Programming and Web Designing

Figure 6. The relationship between C and C++.

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.

2.3.1 Laying the Groundwork


Our goal is to help you begin writing OOP programs as soon as possible. However,
as we noted, much of C++ is inherited from C, so while the overall structure of a C++
program may be OOP, down in the trenches you need to know some old-fashioned
procedural fundamentals. You will learn about variables and I/O, about control structures
such as loops and decisions, and about functions themselves. You will also learn about
structures, since the same syntax that is used for structures is used for classes.

2.3.2 The Unified Modeling Language (UML)


The UML is a graphical “language” for modeling computer programs. “Modeling”
means to create a simplified representation of something, as a blueprint models a
house. The UML provides a way to visualize the higher-level organization of programs
without getting mired down in the details of actual code. The UML began as three
separate modeling languages, one created by Grady Booch at Rational Software, one by
James Rumbaugh at General Electric, and one by Ivar Jacobson at Ericson. Eventually
Rumbaugh and Jacobson joined Booch at Rational, where they became known as the
three amigos. During the late 1990s they unified (hence the name) their modeling
languages into the Unified Modeling Language. The result was adopted by the Object
Management Group (OMG), a consortium of companies devoted to industry standards.

3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 61

2.4 C++ PROGRAMMING BASICS


In any language there are some fundamentals you need to know before you can
write even the most elementary programs. A C++ program may remind you more of
a mathematics formula than a computer program. Do not worry about this. You will
find that as you gain familiarity with C++, it starts to look less forbidding, while other
languages begin to seem unnecessarily fancy and verbose.

2.4.1 Basic Program Construction


Let us look at a very simple C++ program. This program is called FIRST, so its source
file is [Link]. It simply prints a sentence on the screen. Here it is:
#include <iostream>
using namespace std;
int main()
{
cout << “Every age has a language of its own\n”;
return 0;
}
Despite its small size, this program demonstrates a great deal about the construction
of C++ programs. Let us examine it in detail.

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.

Braces and the Function Body


The body of a function is surrounded by braces (sometimes called curly brackets).
These braces play the same role as the BEGIN and END keywords in some other
languages: They surround or delimit a block of program statements. Every function
must use this pair of braces around the function body. In this example there are only
two statements in the function body: the line starting with cout, and the line starting
with return. However, a function body can consist of many statements.

Always Start with Main()


When you run a C++ program, the first statement executed will be at the beginning
of a function called main().The program may consist of many functions, classes, and
other program elements, but on startup, control always goes to main(). If there is no
function called main() in your program, an error will be reported when you run the
program.
In most C++ programs, main() calls member functions in various objects to carry
out the program’s real work. The main() function may also contain calls to other
standalone functions. This is shown in Figure 7.

Figure 7. Objects, functions, and main().

3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 63

2.4.3 Program Statements


The program statement is the fundamental unit of C++ programming. There are two
statements in the FIRST program: the line
cout << “Every age has a language of its own\n”;
and the return statement
return 0;
The first statement tells the computer to display the quoted phrase. Most statements
tell the computer to do something. In this respect, statements in C++ are similar to
statements in other languages. In fact, as we have noted, the majority of statements
in C++ are identical to statements in C.
A semicolon signals the end of the statement. This is a crucial part of the syntax
but easy to forget. In some languages (like BASIC), the end of a statement is signaled
by the end of the line, but that is not true in C++. If you leave out the semicolon, the
compiler will often (although not always) signal an error.
The last statement in the function body is return 0;. This tells main() to return
the value 0 to whoever called it, the operating system or compiler. In older versions
of C++ you could give main() the return type of void and dispense with the return
statement, but this is not considered correct in Standard C++.

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

“Every age has a language of its own\n”


; return
0;}

We do not recommend this syntax—it is nonstandard and hard


to read—but it does compile correctly.
There are several exceptions to the rule that whitespace is
invisible to the compiler. The first line of the program, starting
with #include, is a preprocessor directive, which must be written
on one line. Also, string constants, such as “Every age has a
language of its own”, cannot be broken into separate lines. (If
you need a long string constant, you can insert a backslash (\)
at the line break or divide the string into two separate strings,
each surrounded by quotes.)

2.4.5 Output Using cout


The statement
Keyword
cout << “Every age has a language of its own\n”;
Abstraction is
the process of The identifier cout (pronounced “C out”) is actually an object.
paying attention It is predefined in C++ to correspond to the standard output
to important stream. A stream is an abstraction that refers to a flow of
properties while
ignoring details. data. The standard output stream normally flows to the screen
display—although it can be redirected to other output devices.
The operator << is called the insertion or put to operator. It
directs the contents of the variable on its right to the object on
its left. In FIRST it directs the string constant “Every age has a
language of its own\n” to cout, which sends it to the display.
(If you know C, you will recognize << as the left-shift bit-
wise operator and wonder how it can also be used to direct
output. In C++, operators can be overloaded. That is, they can
perform different activities, depending on the context.
Although the concepts behind the use of cout and << may
be obscure at this point, using them is easy. They will appear
in almost every example program. Figure 8 shows the result of
using cout and the insertion operator <<.

3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 65

Figure 8. Output with cout.

2.5 BASIC DATA TYPES IN C++


There are three data types in C++ which are primitive data types, abstract data types,
and derived data types. Primitive data types include integer, floating-point, character,
boolean, double floating-point, valueless or void, and wide character.

Figure 9. Data Types.

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.

Void – void is used


i) To specify the return type of a function when it is not returning any value.
ii) To indicate an empty argument list to a function.

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.5.2 Derived Data types


1) Arrays
An array in c++ is similar to that in c, the only difference is the way character arrays
are initialized. In c++, the size should be one larger than the number of character in
the string where in c, it is exact same as the length of string constant.
char string1[3] = “ab”; // in c++
char string1[2] = “ab”; // in c.

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:

2.5.3 Variables in C++

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;

By default, if we do not specify either signed or unsigned most compiler settings


will assume the type to be signed, therefore instead of the second declaration we
could have written:
int MyAccountBalance;

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;

2.6 OPERATORS IN C++


Assignment (=):
The assignment operator assigns a value to a variable. a=5;
This statement assigns the integer value 5 to the variable a. The part at the left of
the assignment operator (=) is known as the lvalue (left value) and the right one as
the rvalue (right value). The lvalue has to be a variable whereas the rvalue can be a
constant, a variable, the result of an operation or any combination of these. The most
important rule when assigning is the right-to-left rule: The assignment operation always
takes place from right to left, and never the other way:
a= b
This statement assigns to variable a (the lvalue) the value contained in variable b (the
rvalue). The value that was stored until this moment in a is not considered at all in
this operation, and in fact that value is lost.
Arithmetic Operators ( +, -, *, /, % )
The five arithmetical operations supported by the C++ language are:

3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 71

Operations of addition, subtraction, multiplication and division literally correspond


with their respective mathematical operators. The only one that you might not be so
used to see may be modulo; whose operator is the percentage sign (%). Modulo is the
operation that gives the remainder of a division of two values.
For example:
a = 11 %3
The variable a will contain the value 2, since 2 is the remainder from dividing 11
between 3.
Compound Assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
When we want to modify the value of a variable by performing an operation on the value
currently stored in that variable we can use compound assignment operators:

Increase and Decrease (++, --)


Shortening even more some expressions, the increase operator (++) and the decrease
operator (--) increase or reduce by one the value stored in a variable. They are equivalent to
+=1 and to -=1, respectively. Thus:

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

In Example 1, B is increased before its value is copied to A. While in Example 2,


the value of B is copied to A and then B is increased.

Relational and Equality Operators ( ==, !=, >, =, <= ):


In order to evaluate a comparison between two expressions we can use the relational
and equality operators. The result of a relational operation is a Boolean value that can
only be true or false, according to its Boolean result.
We may want to compare two expressions, for example, to know if they are equal
or if one is greater than the other is. Here is a list of the relational and equality
operators that can be used in C++:

Here there are some examples:


(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.

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.

Logical Operators ( !, &&, || ):


The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only
one operand, located at its right, and the only thing that it does is to inverse the value
of it, producing false if its operand is true and true if its operand is false. Basically,
it returns the opposite Boolean value of evaluating its operand.
For Example:
!(5 == 5) // evaluates to false because the expression at its right
(5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to 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:

condition ? result1 : result2

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

Scope Resolution Operator


1) C++ is a block - structured language. The scope of the variable extends from
the point of its declaration till the end of the block containing the declaration.
2) Consider following program.
...
....
{ int x = 1;
===
}
=====
{ int x = 2;
} =====
The two declaration of x refer to two different memory locations containing different
values. Blocks in c++ are often nested. Declaration in a inner block hides a declaration
of the same variable in an outer block.
3) In C, the global version of a variable cannot be accessed from within the inner
block. C++ resolves this problem by using scope resolution operator (::), because this
operator allows access to the global version of a variable.
4) Consider following program.
# include<iostream.h >
int m = 10;
int main ( )
{
int m = 20;
{
int k = m;
int m = 30;
cout << .K = . <<k;
cout << .m = .<<m;

3G E-LEARNING
An Overview of Object-Oriented Programming in C++ 77

cout << : : m = . << : : m;


}
cout << .m. = .<< m;
cout << .::m = <<::m;
return 0;
}
The output of program is
k = 20
m = 30
:: m = 10
m = 20
:: m =10
In the program m is declared at three places. And::m will always refer to global m.

5) A major application of the scope resolution operator is in the classes to identify the
class to which a member functions belongs.

Member Dereferencing Operators


C++ permits us to define a class containing various types of data & functions as members.
C++ also permits us to access the class members through pointers. C++ provides a set
of three pointer. C++ provides a set of three pointers to member operators.
1) ::* - To access a pointer to a member of a class.
2) .* - To access a member using object name & a pointer to that member.
3) → * - To access a member using a pointer in the object & a pointer to the member.

Memory Management Operators


1) We use dynamic allocation techniques when it is not known in advance how
much of memory space is needed. C++ supports two unary operators new and
delete that perform the task of allocating & freeing the memory.
2) An object can be created by using new and destroyed by using delete. A data

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:

1 template <typename T>

2 void test(T& encoder, span<byte> buffer)

3 {

4   auto state = [Link]();

5   // do something with state

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:

1 template <typename E>

2 concept Encoder = requires(E& e, span<byte> b)

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

A solution to this problem employed in the STL is to additionally require in the


concept that a constrained type provides a nested type alias that names the type in
question: even if no algorithm actually uses this type.

1 template <typename E>

2 concept Encoder = requires(E& e,

3                            typename E::state_t& s,

4                            span<byte> b)

5 {

6   { [Link]() } -> std::convertible_to<typename E::state_t>;

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.

1 template <typename E>

2 concept Encoder = requires(E& e)

3 {

4   typename E::state_t;

5   { [Link]() } -> std::convertible_to<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

I would have to resort to solutions that look quite complicated:


This perfectly illustrates that requires-expression is just an expression, so you can
combine it with other expressions. Token && is a conjunction operator — rather than
a logical-or — and has the special compile-time short-circuiting properties. Another
alternative:

1 template <typename E>

2 concept Encoder = requires(E& e)

3 {

4   typename E::state_t;

5   { [Link]() } -> std::convertible_to<typename E::state_t>;

7   requires requires(typename E::state_t& s,

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:

1 template <typename E>

2 concept Encoder = requires(E& e, span<byte> b)

3 {

4   typename E::state_t;

5   { [Link]() } -> std::convertible_to<typename E::state_t>;

6   [Link](std::declval<typename E::state_t&>(), b);

7 };

Which illustrates that arguments in requires-expression is just a syntactic


sugar over what you can already do with std::declval. Similarly, we could

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:

1 template <typename E, typename B>

2 concept Encoder =

3   Buffer<B> &&

4   requires(E& e, typename E::state_t& s, B b)

5 {

6   { [Link]() } -> std::convertible_to<typename E::state_t>;

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 {

3   using state_t = std::size_t;

4   state_t init();

5   void encode(state_t& s, span<byte> buf);

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

4. The operator >> is called


a. an extraction operator
b. put to operator
c. either a or b
d. None of these
5. State the objective oriented languages
a. C++
b. Jave
c. Eiffel
d. All of the above

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++.

Answer to Multiple Choice Questions


1. (c) 2. (c) 3. (c) 4. (c) 5. (d)

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

After studying this chapter, you will be able to:

1. Understand the HTML Overview


2. Explain the HTML Tag, Fonts and Color
3. Discuss the HTML Lists, Links and Images
4. Define HTML Tables
88 Introduction to Computer Programming and Web Designing

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.

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.
The current version of HTML is HTML 4.0. However, both Internet Explorer and
Netscape implement some features differently and provide non-standard extensions.
Web developers using the more advanced features of HTML 4 may have to design
pages for both browsers and send out the appropriate version to a user. Significant
features in HTML 4 are sometimes described in general as dynamic HTML. What is
sometimes referred to as HTML 5 is an extensible form of HTML called Extensible
Hypertext Markup Language (XHTML).

3.1 HTML OVERVIEW


HTML stands for Hypertext Markup Language, and it is the most widely used language
to write Web Pages.
■■ Hypertext refers to the way in which Web pages (HTML documents) are linked
together. Thus the link available on a webpage are called Hypertext.

3G E-LEARNING
HTML 89

■■ As its name suggests, HTML is a Markup Language


which means you use HTML to simply “markup” a
text document with tags that tell a Web browser how
to structure it to display.
Originally, HTML was developed with the intent of defining
the structure of documents like headings, paragraphs, lists,
and so forth to facilitate the sharing of scientific information
between researchers.
Now, HTML is being widely used to format web pages with
the help of different tags available in HTML language.

Basic HTML Document


In its simplest form, following is an example of an HTML
document:
<!DOCTYPE html>
<html>
<head>
<title>This is document title</title>
</head> Keyword
Internet
<body> Explorer
(IE) is a
<h1>This is a heading</h1> World Wide
Web browser
<p>Document content goes here.....</p> that comes
bundled with
the Microsoft
</body> Windows
operating system
</html> (OS).
Either you can use Try it option available at the top right
corner of the code box to check the result of this HTML code,
or let’s save it in an HTML file [Link] using your favorite
text editor. Finally open it using a web browser like Internet
Explorer or Google Chrome, or Firefox etc. It must show the
following output:

3G E-LEARNING
90 Introduction to Computer Programming and Web Designing

Did You 3.2 HTML TAG


Know? HTML tags are the hidden keywords within a web page that
The first
publicly available
define how the browser must format and display the content.
description of
HTML was a ■■ HTML tags are used to mark-up HTML elements
document called ■■ HTML tags are surrounded by the two characters < and >
“HTML Tags”,
first mentioned ■■ The surrounding characters are called angle brackets
on the Internet by
Tim Berners-Lee
■■ HTML tags normally come in pairs like <b> and </b>
in late 1991. ■■ The first tag in a pair is the start tag, the second tag
is the end tag
■■ The text between the start and end tags is the element
content
■■ HTML tags are not case sensitive, <b> means the same
as <B>

3.2.1 Logical vs. Physical Tags


Keyword In HTML there are both logical tags and physical tags. Logical
A tags are designed to describe (to the browser) the enclosed text’s
browser is meaning. An example of a logical tag is the tag. By placing text
an application in between these tags you are telling the browser that the text
program that
provides a way
has some greater importance. By default all browsers make the
to look at and text appear bold when in between the and tags.
interact with all
the information Physical tags on the other hand provide specific instructions
on the World on how to display the text they enclose.
Wide Web.
Examples of physical tags include:
■■ <b>: Makes the text bold.
■■ <big>: Makes the text usually one size bigger than
what’s around it.

3G E-LEARNING
HTML 91

■■ <i>: Makes text italic.


Physical tags were invented to add style to HTML pages
because style sheets were not around, though the original
intention of HTML was to not have physical tags. Rather than Keyword
use physical tags to style your HTML pages, you should use Physical
style sheets. tags
are used to
indicate exactly
how specific
3.2.2 Basic HTML Tags characters are to
be formatted.
The most important tags in HTML are tags that define headings,
paragraphs and line breaks.

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

HTML automatically adds an extra blank line before and


after a heading. A useful heading attribute is align.

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 -->.

HTML automatically adds an extra blank line before and


after some elements, like before and after a paragraph, and
before and after a heading. If you want to insert blank lines
into your document, use the tag.

3.2.3 Other HTML Tags


There are logical styles that describe what the text should be
and physical styles which actually provide physical formatting.
It is recommended to use the logical tags and use style sheets
to style the text in those tags.

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.

3.2.4 HTML Character Entities


Some characters have a special meaning in HTML, like the less than sign (<) that
defines the start of an HTML tag. If we want the browser to actually display these
characters we must insert character entities in place of the actual characters themselves.
The Most Common Character Entities:

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 &nbsp;..
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.

This Code Would Display


<p> This code would appear as this.</p> This code would appear as this.
<p> This code &nbsp;&nbsp;&nbsp; would This code would appear with three extra
appear with three extra spaces.</p> spaces.

3.3 HTML FONTS


An HTML font or web font is the type of text displayed, designated using CSS. In the
past, aspects of the font could be changed using attribute and value pairs within the
<font> tag. However, in this tag was deprecated in HTML 4.1, and will soon be obsolete.
The following method contain examples of both methods, as well as information on
how to get more web fonts.

HTML fonts in CSS


For HTML5 and website design in general, it is recommended that CSS be used to
specify the font. In the following example, the font is specified in the body, which
tells the browser to use Verdana if it’s available, Arial as a fallback and the color code
#333. With CSS, the font-family and color can be applied directly to any specific HTML
element, or added to a certain HTML tag using a class or id.

body {
font-family: verdana, arial;
color: #333;
}

3G E-LEARNING
96 Introduction to Computer Programming and Web Designing

Example of HTML text font

<!DOCTYPE html>

<html>

<body>

<h1 style=”font-family:verdana;”>This is a heading</h1>

<p style=”font-family:courier;”>This is a paragraph.</p>

</body>

</html>

Result

HTML fonts With Font Tag


Example Code:
<font face=”verdana” color=”green” size=”+2”>Example
Verdana font in a green color</font>
Example Result:

3.3.1 HTML Backgrounds


By default, your webpage background is white in color. You
may not like it, but no worries. HTML provides you following
two good ways to decorate your webpage background.
■■ Html Background with Colors
■■ Html Background with Images

3G E-LEARNING
HTML 97

Html Background with Colors


The bgcolor attribute is used to control the background of an
HTML element, specifically page body and table backgrounds.
Following is the syntax to use bgcolor attribute with any HTML Keyword
tag. HTML
element
<tagname bgcolor=”color_value”...> is an individual
component of an
HTML document
or web page,
This color_value can be given in any of the following formats: once this has
been parsed into
the Document
Object Model.
<!-- Format 1 - Use color name -->
<table bgcolor=”lime” >

<!-- Format 2 - Use hex value -->


<table bgcolor=”#f1f1f1” >

<!-- Format 3 - Use color value in RGB terms -->


<table bgcolor=”rgb(0,0,120)” >

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

<!-- Format 1 - Use color name -->


<table bgcolor=”yellow” width=”100%”>
<tr><td>
This background is yellow
</td></tr>
</table>

<!-- Format 2 - Use hex value -->


<table bgcolor=”#6666FF” width=”100%”>
<tr><td>
This background is sky blue
</td></tr>
</table>

<!-- Format 3 - Use color value in RGB terms -->


<table bgcolor=”rgb(255,0,255)” width=”100%”>
<tr><td>
This background is green
</td></tr>
</table>

</body>
</html>

This will produce following result:

3G E-LEARNING
HTML 99

Html Background with Images Remember

The background attribute can also be used to control the The


background of an HTML elmement, specifically page body and background
table backgrounds. You can specify an image to set background attribute is
deprecated and it
of your HTML page or table. Following is the syntax to use is recommended
background attribute with any HTML tag. to use Style Sheet
for background
<tagname background=”Image URL”...> setting.

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>

<!-- Set table background -->


<table background=”/images/[Link]” width=”100%”
height=”100”>
<tr><td>
This background is filled up with HTML image.
</td></tr>
</table>

3G E-LEARNING
100 Introduction to Computer Programming and Web Designing

</body>
</html>
This will produce following result:

3.4 HTML COLOR


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.
The <body> tag has following attributes which can be used to set different colors:
■■ bgcolor - sets a color for the background of the page.
■■ text - sets a color for the body text.
■■ alink - sets a color for active links or selected links.
■■ link - sets a color for linked text.
■■ vlink - sets a color for visited links - that is, for linked text that you have
already clicked on.

HTML Color Coding Methods


There are following three different methods to set colors in your web page:
■■ Color names - You can specify color names directly like green, blue or red.
■■ Hex codes - A six-digit code representing the amount of red, green, and blue
that makes up the color.
■■ Color decimal or percentage values - This value is specified using the rgb(
) property.

HTML Colors - Color Names


You can sepecify direct a color name to set text or background color. W3C has listed
16 basic color names that will validate with an HTML validator but there are over 200
different color names supported by major browsers.

3G E-LEARNING
HTML 101

W3C Standard 16 Colors


Here is the list of W3C Standard 16 Colors names and it is recommended to use them.

HTML Colors - Hex Codes


A hexadecimal is a 6 digit representation of a color. The first two digits(RR) represent
a red value, the next two are a green value(GG), and the last are the blue value(BB).
A hexadecimal value can be taken from any graphics software like Adobe Photoshop,
Paintshop Pro or MS Paint.
Each hexadecimal code will be preceded by a pound or hash sign #. Following is
a list of few colors using hexadecimal notation.

HTML Colors - RGB Values


This color value is specified using the rgb( ) property. This property takes three values,
one each for red, green, and blue. The value can be an integer between 0 and 255 or
a percentage.

3G E-LEARNING
102 Introduction to Computer Programming and Web Designing

Following is a list to show few colors using RGB values.

Remember
All the
browsers
does not support
rgb() property
of color so it is
recommended
not to use it.

3.5 HTML LISTS


HTML lists are used to present list of information in well-
formed and semantic way. There are three different types of
list in HTML and each one has a specific purpose and meaning:
■■ Unordered list — Used to group a set of related items,
in no particular order.
■■ Ordered list — Used to group a set of related items,
in a specific order.
■■ Description list — Used to display a list of terms and
their descriptions.

HTML Unordered Lists


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.
Example
<ul>
<li>Chocolate Cake</li>
<li>Black Forest Cake</li>

3G E-LEARNING
HTML 103

<li>Pineapple Cake</li>
</ul>

The output of the above example will look something like this:

HTML Ordered Lists


An ordered list, created using the <ol> tag, and each list item starts with the <li> tag.
Ordered list contain information where order should be emphasized.
The list items in ordered lists are marked with numbers.
Example
<ol>
<li>Mix ingredients</li>
<li>Bake in oven for an hour</li>
<li>Allow to stand for ten minutes</li>
</ol>

The output of the above example will look something like this:

HTML Definition Lists


A definition list is a list of items, with a description of each item.
The definition list created using <dl> tag. The <dl> tag is used in conjunction with <dt> -
defines the item in the list, and <dd> describes the item in the list:

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:

3.6 HTML LINKS


Links are used to “link” a visitor from one area to another. There area many types
of links:
■■ Local: A page on the same server or directory
■■ Internal: A section on the current page or document
■■ External: A page or site on a different server or directory
■■ Download: A file for the visitor to download
■■ E-mail: Opens the visitor’s e-mail program

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>

second step: add the link anywhere in ur page

<A HREF=”#top “> click here to go to the top of this page </A></P>

and this is my link:


click here to go to the top of this page

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.

<a href = “URL for the website“> text to click on </a>


i want to link to my blog home page, so i will use this code
<a href = “http”//[Link]“> Click here to visit my blog, enjoy! </a>
and this is my link
Click here to visit my blog, enjoy!

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.

<a href= “mailto: mail_address@[Link]“>

click here ti send me e-mail </a>

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.

3.7 HTML IMAGES


Images are very important to beautify as well as to depict many complex concepts in
simple way on your web page.

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

Set Image Location


Usually we keep our all the images in a separate directory. So let’s keep HTML file
[Link] in our home directory and create a subdirectory images inside the home
directory where we will keep our image [Link].

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>

Set Image Width/Height


You can set image width and height based on your requirement using width and height
attributes. You can specify width and height of the image in terms of either pixels or
percentage of its actual size.
Example
<!DOCTYPE html>
<html>
<head>
<title>Set Image Width and Height</title>
</head>
<body>

3G E-LEARNING
HTML 109

<p>Setting image width and height</p>


<img src=”/html/images/[Link]” alt=”Test Image” width=”150” height=”100”/>
</body>
</html>

Set Image Border


By default image will have a border around it, you can specify border thickness in
terms of pixels using border attribute. A thickness of 0 means, no border around the
picture.
Example

<!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>

Set Image Alignment


By default image will align at the left side of the page, but you can use align attribute
to set it in the center or right.
Example
<!DOCTYPE html>
<html>
<head>
<title>Set Image Alignment</title>

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>

3.8 HTML TABLES


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
Keyword (with the <td> tag). The letters td stands for table data, which is
the content of a data cell. A data cell can contain text, images,
A
horizontal rule
lists, paragraphs, forms, horizontal rules, tables, etc.
(<hr>) is a line
that goes across a
webpage.

Tables and the Border Attribute


To display a table with borders, you will use the border attribute.

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>&nbsp; <img src=”[Link] &nbsp;
</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

Cell Padding and Spacing

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>

This will produce following result:

3G E-LEARNING
114 Introduction to Computer Programming and Web Designing

Here is an example of using background attribute. Here we will use an image


available in /images directory.

<!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

Table Height and Width


You can set a table width and height using width and height attrubutes. You can
specify table width or height in terms of pixels or in terms of percentage of available
screen area.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Width/Height</title>
</head>
<body>
<table border=”1” width=”400” height=”150”>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
</body>

3G E-LEARNING
116 Introduction to Computer Programming and Web Designing

</html>

This will produce following result:

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.

MULTIPLE CHOICE QUESTIONS


1. HTML is what type of language?
a. Scripting Language
b. Markup Language
c. Programming Language
d. Network Protocol
2. HTML uses
a. User defined tags
b. Pre-specified tags

3G E-LEARNING
118 Introduction to Computer Programming and Web Designing

c. Fixed tags defined by the language


d. Tags only for linking
3. Fundamental HTML Block is known as …………….
a. HTML Body
b. HTML Tag
c. HTML Attribute
d. HTML Element
4. Apart from <b> tag, what other tag makes text bold ?
a. <fat>
b. <strong>
c. <black>
d. <emp>
5. What should be the first tag in any HTML document?
a. <head>
b. <title>
c. <html>
d. <document>

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.

Answer to Multiple choice Questions


1. (b) 2. (c) 3. (b) 4. (b) 5. (c)

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

After studying this chapter, you will be able to:

1. Understand the overview of XHTML


2. Define the XHTML syntax
3. Explain the headers, linking and images
4. Discuss the unordered lists
5. Explain the basic XHTML tables and forms
122 Introduction to Computer Programming and Web Designing

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.

Keyword 4.1 OVERVIEW OF XHTML


XHTML (Extensible Hypertext Markup Language) is a
Standard reformulation of HTML 4.0 as an application of the Extensible
Generalized
Markup
Markup Language (XML). For readers unacquainted with either
Language term, HTML is the set of codes (that’s the “markup language”)
(SGML) is a that a writer puts into a document to make it displayable on
standard for the World Wide Web. HTML 4 is the current version of it. XML
how to specify
a document is a structured set of rules for how one might define any kind
markup language of data to be shared on the Web. It’s called an “extensible”
or tag set. Such markup language because anyone can invent a particular set of
a specification is
itself a document markup for a particular purpose and as long as everyone uses
type definition it (the writer and an application program at the receiver’s end),
(DTD). it can be adapted and used for many purposes - including,
as it happens, describing the appearance of a Web page. That
being the case, it seemed desirable to reframe HTML in terms
of XML. The result is XHTML, a particular application of XML
for “expressing” Web pages.
HTML began as a simple markup language similar in
appearance and usage to other Standard Generalized Markup
Language (SGML)-based markup languages. In its early years,
little effort was put into making HTML perfectly SGML compliant.
As a result, odd features and a lax attitude toward enforcing the
rules became standard parts of both HTML and the browsers

3G E-LEARNING
XHTML 123

that processed HTML documents.


As the Web grew from an experiment into an industry, the
desire for a standard version of HTML led to the creation of
several official versions, culminating most recently with version
4.01. As HTML has stabilized into this latest version, browsers
have become more alike in their support of various HTML
features. In general, the world of HTML has settled into a
familiar set of constructs and usage rules. Unfortunately, HTML
offers only a limited set of document-creation primitives, is
incapable of handling nontraditional content such as chemical
formulae, musical notation, or mathematical expressions, and
fails to adequately support alternative display media such as
handheld computers or intelligent cellular phones. We need
new ways to deliver information that can be parsed, processed,
displayed, sliced, and diced by the many different communication
technologies that have emerged since the Web sparked the digital
communication revolution a decade ago.
Instead of trying to rein in another herd of maverick,
nonstandard markup languages, the W3C introduced XML as
a standard way to create new markup languages. XML is the
framework upon which organizations can develop their own
markup languages to suit the needs of their users. XML is an Keyword
updated version of SGML, streamlined and enhanced for today’s
dynamic systems. And while the W3C originally intended it as a Extensible
tool to create document markup languages, XML is also becoming Markup
quite useful as a standard way to define small languages that Language (XML)
is a markup
different applications use as data-exchange protocols. language
that defines
We don’t want to abandon the plethora of documents already a set of rules
marked up with HTML, or the infrastructure of knowledge, for encoding
tools, and technologies that currently support HTML and the documents
in a format
Web. Yet, we do not want to miss the opportunities of XML, that is both
either. XHTML is the bridge. It uses the features of XML to human-readable
define a markup language that is nearly identical to standard and machine-
readable.
HTML 4.01 and gets us all started down the XML road.

Why Use XHTML?


Developers who migrate their content to XHTML 1.0 get the
following benefits:

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.

4.1.1 Basic Understanding


Before we proceed further, let us have a quick view on what are HTML, XML, and
SGML.

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.

4.2 XHTML SYNTAX


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. The
important points to remember while writing a new XHTML document or converting
existing HTML document into XHTML document:
■■ Write a DOCTYPE declaration at the start of the XHTML document.
■■ Write all XHTML tags and attributes in lower case only.
■■ Close all XHTML tags properly.
■■ Nest all the tags properly.
■■ Quote all the attribute values.
■■ Forbid Attribute minimization.
■■ Replace the name attribute with the id attribute.
■■ Deprecate the language attribute of the script tag.

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

<!-- This is invalid in XHTML -->


<A Href=”/xhtml/xhtml_tutorial.html”>XHTML Tutorial</A>
<!-- Correct XHTML way of writing this is as follows -->
<a href=”/xhtml/xhtml_tutorial.html”>XHTML Tutorial</a>
In the example, Href and anchor tag A are not in lower case, so it is incorrect.

Closing the Tags


Each and every XHTML tag should have an equivalent closing tag, even empty elements
should also have closing tags. Here is an example showing valid and invalid ways of
using tags:

<!-- This is invalid in XHTML -->


<p>This paragraph is not written according to XHTML syntax.
<!-- This is also invalid in XHTML -->
<img src=”/images/[Link]” >

The following syntax shows the correct way of writing above tags in XHTML.
Difference is that, here we have closed both the tags properly.

<!-- This is valid in XHTML -->


<p>This paragraph is not written according to XHTML syntax.</p>
<!-- This is also valid now -->
<img src=”/images/[Link]” />

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:

<!-- This is invalid in XHTML -->

3G E-LEARNING
XHTML 127

<img src=”/images/[Link]” width=250 height=50 />


<!-- Correct XHTML way of writing this is as follows -->
<img src=”/images/[Link]” width=”250” height=”50” />

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:

<!-- This is invalid in XHTML -->


<option selected>
<!-- Correct XHTML way of writing this is as follows -->
<option selected=”selected”>
Here is a list of the minimized attributes in HTML and the way you need to write
them in XHTML:

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

<!-- This is invalid in XHTML -->


<img src=”/images/[Link]” name=”xhtml_logo” />
<!-- Correct XHTML way of writing this is as follows -->
<img src=”/images/[Link]” id=”xhtml_logo” />

The language Attribute


The language attribute of the script tag is deprecated. The
following example shows this difference:
<!-- This is invalid in XHTML -->
<script language=”JavaScript” type=”text/JavaScript”>
[Link](“Hello XHTML!”);
</script>
<!-- Correct XHTML way of writing this is as follows -->
<script type=”text/JavaScript”>
Remember
You [Link](“Hello XHTML!”);
should be
able to write your </script>
HTML document
into a well-
formed XHTML Nested Tags
document and
get a cleaner You must nest all the XHTML tags properly. Otherwise your
version of your document is assumed as an incorrect XHTML document. The
website.
following example shows the syntax:
<!-- This is invalid in XHTML -->
<b><i> This text is bold and italic</b></i>
<!-- Correct XHTML way of writing this is as follows -->
<b><i> This text is bold and italic</i></b>

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).

Figure 1: Header elements h1 through h6.

3G E-LEARNING
XHTML 131

Header element h1 (line 15) is considered the most significant


header and is rendered in a larger font than the other five
headers (lines 16–20). Each successive header element (i.e., h2,
h3, etc.) is rendered in a smaller font. Remember

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

Figure 2. Linking to other Web pages.

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

Figure 3. Linking to an e-mail address.

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

Group (JPEG) images. Users can create images, using specialized


pieces of software, such as Adobe PhotoShop Elements and Jasc
Remember Paint Shop Pro ([Link]). Images may also be acquired
All from various Web sites, such as [Link]. Figure 4
XHTML demonstrates how to incorporate images into Web pages.
elements must be
nested within the
root element. All
other elements
can have sub
elements which
must be in pairs
and correctly
nested within
their parent
element.

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.

Lines 16–17 use an img element to insert an image in the


document. The image file’s location is specified with the img
element’s src attribute. The image is located in the same directory
as this XHTML document, so only the image’s file name is
required. Optional attributes width and height specify the image’s
width and height, respectively. The document author can scale

3G E-LEARNING
XHTML 135

an image by increasing or decreasing the values of the image


width and height attributes. If these attributes are omitted, the
browser uses the image’s actual width and height. Images are
measured in pixels (“picture elements”), which represent dots
of color on the screen. The image in Figure 4 is 181 pixels wide
and 238 pixels high.
Every img element in an XHTML document has an alt
attribute. If a browser cannot render an image, the browser
displays the alt attribute’s value. A browser might not be able
to render an image for several reasons. It might not support
images—as is the case with a text-based browser (i.e., a browser
that can display only text)—or the client may have disabled
image viewing to reduce download time. Figure 4 shows Internet Did You
Explorer rendering the alt attribute’s value when a document
references a nonexistent image file ([Link]).
Know?
The
Graphics
The alt attribute is important for creating accessible Web Interchange
pages for users with disabilities, especially those with vision Format is a
impairments and text-based browsers. Specialized software called bitmap image
a speech synthesizer often is used by people with disabilities. format that
was developed
Such software applications “speak” the alt attribute’s value so by US-based
that the user knows what the browser is displaying. software writer
Steve Wilhite
Some XHTML elements (called empty elements) contain while working
only attributes and do not markup text (i.e., text is not placed at the internet
service provider
between the start and end tags). Empty elements (e.g., img) must CompuServe in
be terminated, either by using the forward slash character (/) 1987.
inside the closing right angle bracket (>) of the start tag or by
explicitly including the end tag. When using the forward slash
character, we add a space before the forward slash to improve
readability (as shown at the ends of lines 17 and 20). Rather
than using the forward slash character, lines 19–20 could be
written with a closing tag as follows:
<img src = “[Link]” height = “238” width = “181” alt =
“An imaginary landscape.”></img>
By using images as hyperlinks, Web developers can create
graphical Web pages that link to other resources. In Figure 5,
we create six different image hyperlinks.
Lines 16–19 create an image hyperlink by nesting an img
element within an anchor (a) element. The value of the img

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

Figure 5. Using images as link anchors.

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.

4.5.1 Special Characters and More Line Breaks


When marking up text, certain characters or symbols (e.g., <) might be difficult to embed
directly into an XHTML document. Some keyboards do not provide these symbols,
or the presence of these symbols could cause syntax errors. For example, the markup
<p>if x < 10 then increment x by 1</p>
results in a syntax error, because it uses the less-than character (<), which is reserved
for start tags and end tags such as <p> and </p>. XHTML provides special characters
or entity references (in the form &code;) for representing these characters. We could
correct the previous line by writing
<p>if x &lt; 10 then increment x by 1</p>
which uses the special character &lt; for the less-than symbol.
Figure 6 demonstrates how to use special characters in an XHTML document. Lines
26–27 contain other special characters, which are expressed either as word abbreviations
(e.g., &amp for ampersand and &copy for copyright) or as hexadecimal (hex) values
(e.g., &#38; is the hexadecimal representation of &amp;). Hexadecimal numbers are

3G E-LEARNING
138 Introduction to Computer Programming and Web Designing

base-16 numbers—digits in a hexadecimal number have values from 0 to 15 (a total of


16 different values). The letters A–F represent the hexadecimal digits corresponding to
decimal values 10–15. Thus, in hexadecimal notation, we can have numbers like 876
consisting solely of decimal-like digits, numbers like DA19F consisting of digits and
letters, and numbers like DCB consisting solely of letters.
In lines 33–35, we introduce three new elements. Most browsers render the del
element as strike-through text. With this format, users can easily indicate document
revisions. To superscript text (i.e., raise text on a line with a decreased font size) or
subscript text (i.e., lower text on a line with a decreased font size), use the sup and
sub elements, respectively. We also use special characters &lt; for a less-than sign and
&frac14; for the fraction 1/4 (line 37).

3G E-LEARNING
XHTML 139

Figure 6. Inserting special characters into XHTML.

In addition to special characters, this document introduces a horizontal rule, indicated


by the <hr /> tag in line 24. Most browsers render a horizontal rule as a horizontal
line. The <hr /> tag also inserts a line break above and below the horizontal line.

4.6 UNORDERED LISTS


We have presented basic XHTML elements and attributes for linking to resources,
creating headers, using special characters and incorporating images. We introduce
another feature for organizing information, called a table. Figure 7 displays text in
an unordered list (i.e., a list that does not order its items by letter or number). The
unordered list element ul creates a list in which each item begins with a bullet (called
a disc).
Each entry in an unordered list (element ul in line 20) is an li (list item) element
(lines 23, 25, 27 and 29). Most Web browsers render these elements with a line break
and a bullet symbol indented from the beginning of the new line.

4.6.1 Nested and Ordered Lists


Lists may be nested to represent hierarchical relationships, as in an outline format.
Figure 8 demonstrates nested lists and ordered lists (i.e., list that order their items by
letter or number).

3G E-LEARNING
140 Introduction to Computer Programming and Web Designing

Figure 7. Unordered lists in XHTML.

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

4.7 BASIC XHTML TABLES


The XHTML table—a frequently used feature that organizes data into rows and columns.
Our first example (Figure 9) uses a table with six rows and two columns to display
price information for fruit.

3G E-LEARNING
142 Introduction to Computer Programming and Web Designing

Figure 8. Nested and ordered lists in XHTML.

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

Figure 9. XHTML table.

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.

4.7.1 Intermediate XHTML Tables and Formatting


We explored the structure of a basic table. In Figure 10, we enhance our discussion
of tables by introducing elements and attributes that allow the document author to
build more complex tables.
The table begins on line 17. Element colgroup (lines 22–27) groups and formats
columns. The col element (line 26) specifies two attributes in this example. The align
attribute determines the alignment of text in the column. The span attribute determines
how many columns the col element formats. We set align’s value to “right” and span’s
value to “1” to right-align text in the first column (the column containing the picture
of the camel in the sample screen capture).
Table cells are sized to fit the data they contain. Document authors can create
larger data cells by using attributes rowspan and colspan. The values assigned to these
attributes specify the number of rows or columns occupied by a cell. The th element
at lines 36–39 uses the attribute rowspan = “2” to allow the cell containing the picture
of the camel to use two vertically adjacent cells (thus the cell spans two rows). The
th element at lines 42–45 uses the attribute colspan = “4” to widen the header cell to
span four cells.
Line 42 introduces attribute valign, which aligns data vertically and may be assigned
one of four values—”top” aligns data with the top of the cell, “middle” vertically
centers data (the default for all data and header cells), “bottom” aligns data with the
bottom of the cell and “baseline” ignores the fonts used for the row data and sets the
bottom of all text in the row on a common baseline (i.e., the horizontal line to which
each character in a word is aligned).

3G E-LEARNING
146 Introduction to Computer Programming and Web Designing

3G E-LEARNING
XHTML 147

Figure 10. Complex XHTML table.

4.8 XHTML FORMS


When browsing Web sites, users often need to provide information such as e-mail
addresses, search keywords and zip codes. XHTML provides a mechanism, called a
form, for collecting such user information.
Data that users enter on a Web page normally is sent to a Web server that provides
access to a site’s resources (e.g., XHTML documents or images). These resources are
located either on the same machine as the Web server or on a machine that the Web

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).

4.8.1 Complex XHTML Forms


We introduce elements and attributes for creating more complex forms. Figure 12
contains a form that solicits user feedback about a Web site. The textarea element (lines
42–44) inserts a multiline text box, called a textarea, into the form. The number of
rows is specified with the rows attribute and the number of columns (i.e., characters)
is specified with the cols attribute. In this example, the textarea is four rows high and
36 characters wide. To display default text in the text area, place the text between the
<textarea> and </textarea> tags. Default text can be specified in other input types, such
as text boxes, by using the value attribute.

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

Figure 12. Form with textareas, password boxes and checkboxes.

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

Figure 13. Form including radio buttons and drop-down lists.

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.

The Early Life of Tim Berners-Lee


Timothy John Berners-Lee was born in London on June 8, 1955.
His parents were Mary Lee Woods and Conway Berners-Lee;
he had three siblings. The Berners-Lee couple worked with the
very first ever commercial computer, the Ferranti Mark 1 so you
could say that computers were his legacy.
He attended Sheen Mount Primary school then spent four
years at Emanuel School in south west London. As a child, he
was a very keen train-spotter and learned all about electronics
through playing with his model railway.
After his school years, Berners-Lee enrolled at the University
of Oxford at Queen’s College for three years and received a first
class degree in physics in 1976.

The Career of Tim Berners-Lee


After graduating Berners-Lee found employment as an engineer
for Plessey Telecom located in Poole, Dorset and he worked on
distributed transaction systems, message relays, and bar code
technology. In 1978 he moved to D.G. Nash in Ferndown, Dorset

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.

Personal and Awards


Berners-Lee married Nancy Carlson, a programmer analyst, in 1990 and they had two
children before they were divorced in 2011. He married Rosemary Leith, director of
the World Wide Web Foundation, in 2014.
In 2001 he became a Fellow of the Royal Society and in 2004 he was knighted. He
was appointed to the Order of Merit in 2007.
In April of 2009, the US National Academy of Sciences elected him as a foreign
associate.
In 2016 he was awarded The ACM A.M. Turing Award “For inventing the World
Wide Web, the first web browser, and the fundamental protocols and algorithms
allowing the Web to scale.”

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.

MULTIPLE CHOICE QUESTIONS


1. What does XHTML stand for
a. Extensive Hypertext Makeup Language
b. Extensible Hypertext Markup Language
c. Expansive Hyperlink Markup Language
d. None of the above
2. What does the “p” element mean?
a. Page
b. Picture

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.

Answer to Multiple choice Questions


1. (b) 2. (c) 3. (b) 4. (c) 5. (b)

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)

“We don’t just build websites, we build websites that SELLS”


-Dr. Christopher Dayagdag

LEARNING OBJECTIVES

After studying this chapter, you will be able to:

1. Understand the overview of CSS


2. Discuss the inline styles and embedded style sheets
3. Explain the conflicting styles and linking external style sheets
4. Describe the positioning elements
5. Define backgrounds, element dimensions and text flow and the box model
6. Discuss the user style sheets
166 Introduction to Computer Programming and Web Designing

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

5.1.1 Advantages of CSS


■■ CSS saves time - You can write CSS once and then
reuse the same sheet in multiple HTML pages. You can
define a style for each HTML element and apply it to
as many web pages as you want.
■■ Pages load faster - If you are using CSS, you do not
need to write HTML tag attributes every time. Just write
one CSS rule of a tag and apply it to all the occurrences
of that tag. So, less code means faster download times.
■■ Easy maintenance - To make a global change, simply
change the style, and all the elements in all the web
pages will be updated automatically.
■■ Superior styles to HTML - CSS has a much wider array of
attributes than HTML, so you can give a far better look
to your HTML page in comparison to HTML attributes.
■■ Multiple Device Compatibility - Style sheets allow
content to be optimized for more than one type of
device. By using the same HTML document, different
versions of a website can be presented for handheld
devices such as PDAs and cellphones or for printing.
■■ Global web standards – Now HTML attributes are being
deprecated and it is being recommended to use CSS.
So it’s a good idea to start using CSS in all the HTML Remember
pages to make them compatible with future browsers. The
World
Wide Web
5.1.2 Who Creates and Maintains CSS? Consortium or
W3C is a group
that makes
CSS is created and maintained through a group of people within recommendations
the W3C called the CSS Working Group. The CSS Working Group about how the
creates documents called specifications. When a specification Internet works
and how it should
has been discussed and officially ratified by the W3C members, evolve.
it becomes a recommendation. These ratified specifications are
called recommendations because the W3C has no control over the
actual implementation of the language. Independent companies
and organizations create that software.

3G E-LEARNING
168 Introduction to Computer Programming and Web Designing

5.2 INLINE STYLES


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. Figure 1
applies inline styles to p elements to alter their font size and
Keyword color.
Inline
style
has the highest
priority, which
means that it will
override a style
defined inside
the <head> tag,
or in an external
style sheet, or a
browser default
value.

3G E-LEARNING
Cascading Style Sheets (CSS) 169

Figure 1. Inline styles.

The first inline style declaration appears in line 20. Attribute


style specifies the style for an element. Each CSS property (the
font-size property in this case) is followed by a colon and a
value. In line 20, we declare this particular p element to use
20-point font size. Line 21 uses element em to “emphasize” text,
which most browsers do by making the font italic.
Line 24 specifies the two properties, font-size and color,
separated by a semicolon. In this line, we set the given paragraph’s
color to blue, using the hexadecimal code #0000ff. Color names
may be used in place of hexadecimal codes.

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>

5.2.1 Embedded Style Sheets


A second technique for using style sheets is embedded style
sheets. Embedded style sheets enable a Web-page author to
embed an entire CSS document in an XHTML document’s head
section. Figure 2 creates an embedded style sheet containing
four styles.

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

Line 22 declares a style class named special. Style classes


define styles that can be applied to any type of element. In this
example, we declare class special, which sets color to blue. We
can apply this style to elements of any type, whereas the other
rules in this style sheet apply only to specific element types
(i.e., em, h1 or p). Style class declarations are preceded by a
period. We will discuss how to apply a style class momentarily.
CSS rules in embedded style sheets use the same syntax as inline
styles; the property name is followed by a colon (:) and the value
of the property. Multiple properties are separated by semicolons
Remember (;). In the rule for em elements, the color property specifies the
All the color of the text, and property background-color specifies the
browsers background color of the element.
does not support
rgb() property
of color, so it is The font-family property (line 18) specifies the name of the
recommended font to use. In this case, we use the arial font. The second value,
not to use it. sans-serif, is a generic font family. Not all users have the same
fonts installed on their computers, so Web-page authors often
specify a comma-separated list of fonts to use for a particular
style. The browser attempts to use the fonts in the order they
appear in the list. Many Web-page authors end a font list with a
generic font family name in case the other fonts are not installed
on the user’s computer. In this example, if the arial font is not
found on the system, the browser instead will display a generic
sans-serif font, such as helvetica or verdana. Other generic font
families include serif (e.g., times new roman, Georgia), cursive
(e.g., script), fantasy (e.g., critter) and monospace (e.g., courier,
fixedsys).
The font-size property (line 20) specifies a 14-point font. Other
possible measurements in addition to pt (point) are introduced
later in the chapter. Relative values— xxsmall, x-small, small,
smaller, medium, large, larger, x-large and xx-large— also can
be used. Generally, relative values for font-size are preferred
over point sizes because an author does not know the specific
measurements of the display for each client. Relative font-size
values permit moreflexible viewing of Web pages. For example,
a user may wish to view a Web page on a handheld device
with a small screen. Specifying an 18- point font size in a style
sheet will prevent such a user from seeing more than one or
two characters at a time. However, if a relative font size is
specified, such as large or larger, the actual size is determined
by the browser that displays the font. Using relative sizes also

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.

5.3 CONFLICTING STYLES


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. Styles defined by the user take precedence over styles defined by the
user agent, and styles defined by authors take precedence over styles defined by the
user. Styles defined for parent elements are also inherited by child (nested) elements.
In this section, we discuss the rules for resolving conflicts between styles defined for
elements and styles inherited from parent and ancestor elements
Figure 2 presented an example of inheritance in which a child em element inherited
the font-size property from its parent p element. However, in Figure 2, the child em
element had a color property that conflicted with (i.e., had a different value than) the
color property of its parent p element. Properties defined for child and descendant
elements have a greater specificity than properties defined for parent and ancestor
elements.

3G E-LEARNING
174 Introduction to Computer Programming and Web Designing

3G E-LEARNING
Cascading Style Sheets (CSS) 175

Figure 3. Inheritance in style sheets.

Line 14 applies property text-decoration to all a elements whose class attribute


is set to nodec. The text-decoration property applies decorations to text within an
element. By default, browsers underline the text of an a (anchor) element. Here, we set
the text-decoration property to none to indicate that the browser should not underline
hyperlinks. Other possible values for text-decoration include overline, linethrough,
underline and blink. [Note: blink is not supported by Internet Explorer.] The .nodec
appended to a is an extension of class styles; this style will apply only to an elements
that specify nodec in their class attribute.

5.4 LINKING EXTERNAL STYLE SHEETS


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. Different pages
on a site can all use the same style sheet. When changes to the styles are required,
the Web-page author needs to modify only a single CSS file to make style changes
across the entire Web site. Figure 4 presents an external style sheet. Lines 1–2 are
CSS comments. Like XHTML comments, CSS comments describe the content of a
CSS document. Comments may be placed in any type of CSS code (i.e., inline styles,
embedded style sheets and external style sheets) and always start with /* and end
with */. Text between these delimiters is ignored by the browser.

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

Figure 5. Linking an external style sheet.

5.4.1 W3C CSS Validation Service


The W3C provides a validation service ([Link]/css-validator) that validates
external CSS documents to ensure that they conform to the W3C CSS Recommendation.
Like XHTML validation, CSS validation ensures that style sheets are syntactically
correct. The validator provides the option of either entering the CSS document’s URL,
pasting the CSS document’s contents into a text area or uploading a CSS document.
Figure 6 illustrates uploading a CSS document, using the file upload feature
available at [Link]/css-validator/[Link].
To validate the document, click the Browse… button to locate the file on your
computer. Like many W3C Recommendations, the CSS Recommendation is being
developed in stages (or versions). The current version under development is Version 3,
so select CSS version 3 in the Profile drop-down list. This field indicates to the validator
the CSS Recommendation against which the uploaded file should be validated. Click

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).

Figure 6. Validating a CSS document.

Figure 7. CSS validation results.

5.5 POSITIONING ELEMENTS


Before CSS, controlling the positioning of elements in an XHTML document was
difficult—the browser determined positioning. CSS introduced the position property

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.

Figure 8. Absolute positioning of elements with CSS.

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

Figure 9. Relative positioning of elements with CSS.

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

Figure 10. Background image added with CSS.

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).

5.7 ELEMENT DIMENSIONS


In addition to positioning elements, CSS rules can specify the actual dimensions of
each page element. Figure 11 demonstrates how to set the dimensions of elements.

3G E-LEARNING
Cascading Style Sheets (CSS) 185

Figure 11. Element dimensions and text alignment.

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.

5.8 TEXT FLOW AND THE BOX MODEL


A browser normally places text and elements on screen in the order in which they
appear in the XHTML document. However, as we have seen with absolute positioning,
it is possible to remove elements from the normal flow of text. Floating allows you
to move an element to one side of the screen; other content in the document then
flows around the floated element. In addition, each block-level element has a virtual
box drawn around it, based on what is known as the box model. The properties of
this box can be adjusted to control the amount of padding inside the element and the
margins outside the element (Figure 12).

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

Figure 13. Box model for block-level elements.

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

Figure 14. Borders of block-level elements.

We set three properties—border-width, border-color and


border-style. The border-width property may be set to any valid Remember
CSS length or to the predefined value of thin, medium or thick. The
The border-color property sets the color. border-
style specifies
As with padding and margins, each of the border properties whether a border
should be solid,
may be set for an individual side of the box (e.g., border-top- dashed line,
style or border-left-color). A developer can assign more than double line, or
one class to an XHTML element by using the class attribute, one of the other
as shown in line 41. possible values.

The border-styles are none, hidden, dotted, dashed, solid,


double, groove, ridge, inset and outset. Borders groove and
ridge have opposite effects, as do inset and outset. Figure 15
illustrates these border styles.

3G E-LEARNING
190 Introduction to Computer Programming and Web Designing

Figure 15. border-style property of the box model.

3G E-LEARNING
Cascading Style Sheets (CSS) 191

5.9 USER STYLE SHEETS


Users can define their own user style sheets to format pages
based on their preferences. For example, people with visual
impairments may want to increase the page’s text size. Webpage Did You
authors need to be careful not to inadvertently override user
Know?
preferences with defined styles. This section discusses possible CSS was
conflicts between author styles and user styles. first proposed by
Håkon Wium Lie
Figure 16 contains an author style. The font-size is set to on October 10,
9pt for all tags that have class note applied to them. 1994.

Figure 16. pt measurement for text size.

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.

Figure 17. User style sheet.

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.

Figure 18. User style sheet in Internet Explorer 6.

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

Figure 19. User style sheet applied with pt measurement.

In this example, if users define their own font-size in a


user style sheet, the author style has a higher precedence and
overrides the user style. The 9pt font specified in the author style Keyword
sheet overrides the 20pt font specified in the user style sheet. Style
sheet is a
This small font may make pages difficult to read, especially for file or form that
individuals with visual impairments. A developer can avoid this defines the layout
problem by using relative measurements (e.g., em or ex) instead of a document.
of absolute measurements, such as pt. Figure 20 changes the
font-size property to use a relative measurement (line 14) that
does not override the user style set in Figure 17. Instead, the
font size displayed is relative to the one specified in the user
style sheet. In this case, text enclosed in the tag displays as
20pt ,and tags that have class note applied to them are displayed
in 15pt (.75 times 20pt).

3G E-LEARNING
194 Introduction to Computer Programming and Web Designing

Figure 20. em measurement for text size.

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.

Figure 21: User style sheet applied with em measurement.

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.

MULTIPLE CHOICE QUESTIONS


1. The CSS links properties are
a. :link, :visited, :hover, :active
b. :link, :visit, :hover, :active
c. :link, :visited, :over, :active
d. :link, :visited, :hover, :active, :inactive

3G E-LEARNING
196 Introduction to Computer Programming and Web Designing

2. Which of the following are the background properties in CSS?


i) background-color ii) background-image iii) background-repeat iv) background-
position v) background
a. i, ii, iii and iv only
b. i, ii, iii and v only
c. i, ii, iv and v only
d. All i, ii, iii, iv and v
3. The different ways to associate styles with a HTML document is/are
a. Embedded CSS with <style> element
b. Inline CSS with style attribute.
c. External CSS with <link> element.
d. All of the above
4. Which of the following is correct CSS syntex for using font property?
a. <p style=”font: italic, bold, 15px;”> ................ </p>
b. <p style=”font-style: italic font-weight: bold font-size: 15px;”> ................... </p>
c. <p style=”font: italic bold 15px;”> ....................... </p>
d. None of the above
5. In CSS tables, the possible values for the caption-side property can have the
following values.
a. top, bottom, left or right
b. top, bottom, center, left or right
c. top or bottom
d. left or right

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.

Answer to Multiple choice Questions


1. (a) 2. (d) 3. (d) 4. (c) 5. (a)

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

After studying this chapter, you will be able to:

1. Understand the overview of PHP


2. Define PHP syntax
3. Discuss the variables and data types in PHP
4. Explain the operator, decision making, loop, arrays. string in PHP
5. Describe the web concepts
200 Introduction to Computer Programming and Web Designing

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!

6.1 OVERVIEW OF PHP


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.
Example
<!DOCTYPE HTML>
<html>

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.”

6.1.1 Common Uses of PHP


PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them. The other uses of PHP are:
■■ PHP can handle forms, i.e. gather data from files, save data to a file, thru
email you can send data, return data to the user.
■■ You add, delete, modify elements within your database thru PHP.
■■ Access cookies variables and set cookies.
■■ Using PHP, you can restrict users to access some pages of your website.
■■ It can encrypt data.

6.1.2 Advantages of PHP over Other Languages


If you’re familiar with other server-side languages like [Link] or JSP, you might be
wondering what makes PHP so special. There are several advantages why one should
choose PHP over other languages. Here are some of them:

3G E-LEARNING
202 Introduction to Computer Programming and Web Designing

■■ Easy to learn: PHP is easy to learn and use. For beginner


programmers who just started out in web development,
PHP is often considered as the best and preferable choice
of scripting language to learn.
■■ Open source: PHP is an open-source project — the
language is developed and maintained by a worldwide
community of developers who make its source code
freely available to download and use. There are no costs
associated with using PHP for individual or commercial
Keyword projects, including future updates.
Microsoft ■■ Portability: PHP runs on various platforms such as
Windows Microsoft Windows, Linux, Mac OS, etc. and it is
(or simply compatible with almost all servers used today such
Windows) is Apache, IIS, etc.
a metafamily
of graphical ■■ Fast Performance: Scripts written in PHP usually execute
operating faster than those written in other scripting languages
systems like [Link] or JSP.
developed,
marketed, ■■ Vast Community: Since PHP is supported by the
and sold by worldwide community, finding help or documentation
Microsoft. for PHP online is extremely easy.

6.1.3 PHP in the Web Environment


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. In PHP,
on the fly method is adopted to publish the document. Hence,
the PHP developer can generate not only web pages, but also
other web embedding documents like PDF, PNG, GIF, etc. The
PHP web environment is usually set with AMP (Apache, MySQL,
and PHP/Perl/Python), which are linked together.

How PHP Fits with HTML


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.

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.

How PHP Fits with MySQL


MySQL easily fits into server-side programming languages, through a domain. Before
your MySQL functions will be recognizable, make sure to enable MySQL in your php.
ini file. You can use MySQL commands within PHP code almost as seamlessly as you
do with HTML. Numerous PHP functions work specifically with MySQL to make your
life easier.
Some of the more commonly used functions are:
■■ mysql_connect([$host[, $username[, $password]]]): Connects to the MySQL
server and returns a resource which is used to reference the connection.
■■ mysql_select_db($database[, $resource]): Equivalent to the MySQL command
USE and sets the active database.
■■ mysql_query($query[, $resource]): Used to send any MySQL command to the
database server. In the case of SELECT queries, a reference to the result set
will be returned.
■■ mysql_fetch_array($result): Return a row of data from the query’s result set
as an associative array, numeric array or both.
■■ mysql_fetch_assoc($result): Return a row of data from the query’s result set
as an associative array.
■■ mysql_error([$resource]): Shows the error message generated by the previous
query.
In order to develop and run PHP Web pages, three vital components need to be
installed on your computer system.
■■ Web Server - PHP will work with virtually all Web Server software, including
Microsoft’s Internet Information Server (IIS) but then most often used is freely
available Apache Server.
■■ Database - PHP will work with virtually all database software, including Oracle
and Sybase but most commonly used is freely available MySQL database.

3G E-LEARNING
204 Introduction to Computer Programming and Web Designing

■■ PHP Parser - In order to process PHP script instructions,


a parser must be installed to generate HTML output
that can be sent to the Web Browser. This tutorial will
guide you how to install PHP parser on your computer.
Keyword
6.2 PHP SYNTAX
Internet
Information The PHP parsing engine needs a way to differentiate PHP code
Services is an from other elements in the page. The mechanism for doing so
extensible web
server created by is known as ‘escaping to PHP.’ There are four ways to do this:
Microsoft for use
with Windows
NT family. Canonical PHP tags
The most universally effective PHP tag style is:
<?php...?>
If you use this style, you can be positive that your tags will
always be correctly interpreted.

Short-open (SGML-style) tags


Short or short-open tags look like this:
<?...?>

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:
<%...%>

To use ASP-style tags, you will need to set the configuration


option in your [Link] file.

3G E-LEARNING
PHP 205

HTML Script Tags


HTML script tags look like this:
<script language=”PHP”>...</script>

6.2.1 Commenting PHP Code


A comment is the portion of a program that exists only for the human reader and
stripped out before displaying the programs result. There are two commenting formats
in PHP:
Single-line comments: They are generally used for short explanations or notes
relevant to the local code. Here are the examples of single line comments.
<?
# This is a comment, and
# This is the second line of the comment
// This is a comment too. Each style comments only
print “An example with single line comments”;
?>

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

multiple lines. The newlines will be


output as well”;
?>

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”;
?>

6.2.2 PHP is Whitespace Insensitive


Whitespace is the stuff you type that is typically invisible on the screen, including
spaces, tabs, and carriage returns (end-of-line characters).
PHP whitespace insensitive means that it almost never matters how many whitespace
characters you have in a [Link] whitespace character is the same as many such
characters.
For example, each of the following PHP statements that assigns the sum of 2 + 2
to the variable $four is equivalent:
$four = 2 + 2; // single spaces
$four <tab>=<tab2<tab>+<tab>2 ; // spaces and tabs
$four =
2+

3G E-LEARNING
PHP 207

2; // multiple lines

6.2.3 PHP is case sensitive


Yeah it is true that PHP is a case sensitive language. Try out the following example:
<html>
<body>
<?
$capital = 67;
print(“Variable capital is $capital<br>”);
print(“Variable CaPiTaL is $CaPiTaL<br>”);
?>
</body>
</html>

This will produce the following result:


Variable capital is 67
Variable CaPiTaL is

Statements are expressions terminated by semicolons


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.
Here is a typical statement in PHP, which in this case assigns a string of characters
to a variable called $greeting:
$greeting = “Welcome to PHP!”;

Braces make blocks


Although statements cannot be combined like expressions, you can always put a
sequence of statements anywhere a statement can go by enclosing them in a set of
curly braces. Here both statements are equivalent:
if (3 == 2 + 1)

3G E-LEARNING
208 Introduction to Computer Programming and Web Designing

print(“Good - I haven’t totally lost my mind.<br>”);


if (3 == 2 + 1)
{
print(“Good - I haven’t totally”);
print(“lost my mind.<br>”);
}

Running PHP Script from Command Prompt


Yes you can run your PHP script on your command prompt. Assuming you have the
following content in [Link] file

<?php
echo “Hello PHP!!!!!”;
?>
Now run this script as command prompt as follows:

$ php [Link]

It will produce the following result

Hello PHP!!!!!

6.3 VARIABLES IN PHP


Variables are used to store data, like text strings, numbers or arrays.
Important things to know about variables in PHP:
■■ In PHP, a variable does not need to be declared before adding a value to it.
PHP automatically converts the variable to the correct data type, depending
on its value.
■■ After declaring a variable it can be reused throughout the code.

3G E-LEARNING
PHP 209

■■ The assignment operator (=) used to assign value to a


variable.
In PHP variable can be declared as: $var_name = value;
<?php
$txt = “Hello World!”;
$number = 10;
?>
Remember
6.3.1 Naming Conventions for PHP Variables Variable
names
These are the following rules for naming a PHP variable: in PHP are case
sensitive, it
■■ All variables in PHP start with a $ sign, followed by means $x and $X
are two different
the name of the variable. variables. So be
■■ A variable name must start with a letter or the underscore careful while
defining variable
character “_”. names.
■■ A variable name cannot start with a number.
■■ A variable name in PHP can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _).
■■ A variable name cannot contain spaces.

6.3.2 Constants in PHP


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. Common examples
of such data include configuration settings (such as database
usernames and passwords).
Constants are defined using define() function, which accepts
two arguments: the name of the constant, and its value. Here
is an example of defining and using a constant in a script:
Example
<?php
// Defining constants

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;
?>

The output of the above code will be:


Current PHP version is: 5.5.14

6.3.3 Naming Conventions for PHP Constants


Name of constants must follow the same rules as variable names,
Keyword which means a valid constant name must starts with a letter
A data or underscore, followed by any number of letters, numbers, or
type in underscores, with one exception: the $ prefix is not required
a programming for constant names.
language is a
set of data with
values having
predefined 6.4 DATA TYPES IN PHP
characteristics.
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. PHP supports total
eight data types which are used to construct variables.

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>”;

$b = -123; // a negative number


var_dump($b);
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>”;

$c = ‘Stay here, I\’ll be back.’;


echo $c;
?>

PHP Floating Point Numbers or Doubles


Floating point numbers (also known as “floats”, “doubles”, or “real numbers”) are
decimal or fractional numbers, like demonstrated in the example below.
<?php
$a = 1.234;
var_dump($a);
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;
}
}

// Create object from class


$message = new greeting;
var_dump($message);
?>

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>”;

// Connect to MySQL database server with default setting


$link = mysql_connect(“localhost”, “root”, “”);
var_dump($link);
?>

6.5 OPERATOR TYPES


Operators are symbols that tell the PHP processor to perform certain actions. For
example, the addition (+) symbol is an operator that tells PHP to add two variables
or values, while the greater-than (>) symbol is an operator that tells PHP to compare
two values.

3G E-LEARNING
216 Introduction to Computer Programming and Web Designing

The following lists describe the different operators used in PHP.

6.5.1 Arithmetic Operators


The arithmetic operators are used to perform common arithmetical operations, such
as addition, subtraction, multiplication etc. Here’s a complete list of PHP’s arithmetic
operators:
Operator Description Example Result
+ Addition $x + $y Sum of $x and $y
– Subtraction $x – $y Difference of $x and $y.
* Multiplication $x * $y Product of $x and $y.
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y

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
?>

6.5.2 Assignment Operators


The assignment operators are used to assign values to variables.

3G E-LEARNING
PHP 217

Operator Description Example Is The Same As


= Assign $x = $y $x = $y
+= Add and assign $x += $y $x = $x + $y
-= Subtract and assign $x -= $y $x = $x – $y.
*= Multiply and assign $x *= $y $x = $x * $y
/= Divide and assign quotient $x /= $y $x = $x / $y
%= Divide and assign modulus $x %= $y $x = $x % $y

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
?>

6.5.3 Comparison Operators


The comparison operators are used to compare two values in a Boolean fashion.

Operator Description Example Result


== Equal $x == $y True if $x is equal to $y
=== Identical $x === $y True if $x is equal to $y, and they are of the
same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
!== Not identical $x !== $y True if $x is not equal to $y, or they are not of
the same type
< Less than $x < $y True if $x is less than $y
> Greater than $x > $y True if $x is greater than $y
>= Greater than or equal to $x >= $y True if $x is greater than or equal to $y
<= Less than or equal to $x <= $y True if $x is less than or equal to $y
The following example will show you these comparison operators in action:
<?php
$x = 25;
$y = 35;
$z = “25”;
var_dump($x == $z); // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true

3G E-LEARNING
PHP 219

var_dump($x < $y); // Outputs: boolean true


var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>

6.5.4 Incrementing and Decrementing Operators


The increment/decrement operators are used to increment/decrement a variable’s value.
Operator Name Effect
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
–$x Pre-decrement Decrements $x by one then returns $x
$x– Post-decrement Returns $x, then decrements $x by one
The following example will show you these increment and decrement operators
in action:
Example
<?php
$x = 10;
echo ++$x; // Outputs: 11
echo $x; // Outputs: 11

$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

echo $x; // Outputs: 9

$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>

6.5.5 Logical Operators


The logical operators are typically used to combine conditional statements.

Operator Name Example Result

and And $x and $y True if both $x and $y are true

or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $$x or $y is true

! Not !$x True if $x is not true


The following example will show you these logical operators in action:
Exampe
<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0))){

3G E-LEARNING
PHP 221

echo “$year is a leap year.”;


} else{
echo “$year is not a leap year.”;
}
?>

6.5.6 String Operators


There are two operators which are specifically designed for strings.

Operator Description Example Result


. Concatenation $str1 . $str2 Concatenation of $str1 and $str2
.= Concatenation assignment $str1 .= $str2 Appends the $str2 to the $str1

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!
?>

6.5.7 Array Operators


The array operators are used to compare arrays:

3G E-LEARNING
222 Introduction to Computer Programming and Web Designing

True if $x is Name Example Result


not equal to
$yOperator
+ Union $x + $y Union of $x and $y
== Equality $x == $y True if $x and $y have the same key/value pairs
=== Identity $x === $y True if $x and $y have the same key/value pairs
in the same order and of the same types
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
!== Non- $x !== $y True if $x is not identical to $y
identity

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
?>

6.6 DECISION MAKING


The if, elseif ...else and switch statements are used to take decision based on the
different condition. You can use conditional statements in your code to make your
decisions. PHP supports the following three decision making statements:
■■ if...else statement - use this statement if you want to execute a set of code
when a condition is true and another if the condition is not true
■■ elseif statement - is used with the if...else statement to execute a set of code

3G E-LEARNING
PHP 223

if one of several condition are true


■■ switch statement - is used if you want to select one of many blocks of code to
be executed, use the Switch statement. The switch statement is used to avoid
long blocks of if..elseif..else code.

The If...Else Statement


If you want to execute some code if a condition is true and another code if a condition
is false, use the if....else statement.

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

It will produce the following result:


Have a nice weekend!

The ElseIf Statement


If you want to execute some code if one of the several conditions is true, then use the
elseif statement.

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

echo “Have a nice day!”;


?>
</body>
</html>

It will produce the following result:

Have a nice weekend!

The Switch Statement


If you want to select one of many blocks of code to be executed, use the Switch
statement. The switch statement is used to avoid long blocks of if..elseif..else code.

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

echo “Today is Saturday”;


break;
case “Sun”:
echo “Today is Sunday”;
break;
default:
echo “Wonder which day is this ?”;
}
?>
</body>
</html>

It will produce the following result:


Today is Friday

6.7 LOOP TYPES


Loops in PHP are used to execute the same block of code a specified number of times.
PHP supports following four loop types.
■■ for - loops through a block of code a specified number of times.
■■ while - loops through a block of code if and as long as a specified condition
is true.
■■ do...while - loops through a block of code once, and then repeats the loop as
long as a special condition is true.
■■ foreach - loops through a block of code for each element in an array.

The For Loop Statement

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>

This will produce the following result:

3G E-LEARNING
PHP 229

The While Loop Statement


The while statement will execute a block of code if and as long as a test expression is
true. If the test expression is true, then the code block will be executed. After the code
has executed the test expression will again be evaluated and the loop will continue
until the test expression is found to be false.
Syntax
while (condition)
{
code to be executed;
}

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>

This will produce the following result:


Loop stopped at i = 10 and num = 40

The do...while loop statement


The do...while statement will execute a block of code at least once - it will then repeat
the loop as long as a condition is true.

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>

This will produce the following result:

Loop stopped at i = 10

The foreach loop statement


The foreach statement is used to loop through arrays. For each pass the value of the
current array element is assigned to $value and the array pointer is moved by one
and in the next pass next element will be processed.

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>

This will produce the following result:


Value is 1
Remember
Value is 2
In an
indexed Value is 3
or numeric array,
the indexes are
automatically
Value is 4
assigned and
start with 0, and Value is 5
the values can be
any data type.
6.8 ARRAYS
An array is a data structure that stores one or more similar
type of values in a single value. For example, if you want to
store 100 numbers, then instead of defining 100 variables, it is
easy to define an array of 100 length. There are three different
kind of arrays and each array value is accessed using an ID c
which is called array index.
■■ Numeric array - An array with a numeric index. Values
are stored and accessed in linear fashion
■■ Associative array - An array with strings as index. This
stores element values in association with key values
rather than in a strict linear index order.
■■ Multidimensional array - An array containing one or
more arrays and values are accessed using multiple
indices

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

This will produce the following result:


Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

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>

This will produce the following result:


Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

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

/* Accessing multi-dimensional array values */


echo “Marks for mohammad in physics : “ ;
echo $marks[‘mohammad’][‘physics’] . “<br />”;
echo “Marks for qadir in maths : “;
echo $marks[‘qadir’][‘maths’] . “<br />”;
echo “Marks for zara in chemistry : “ ;
echo $marks[‘zara’][‘chemistry’] . “<br />”;
?>
</body>
</html>

This will produce the following result:


Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

6.9 STRING IN PHP


A string is a sequence of letters, numbers, special characters and arithmetic values or
combination of all. The simplest way to create a string is to enclose the string literal
(i.e. string characters) in single quotation marks (‘), like this:
$my_string = ‘Hello World’;

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

■■ \t is replaced by the tab character


■■ \$ is replaced by the dollar sign itself ($)
■■ \” is replaced by a single double-quote (“)
■■ \\ is replaced by a single backslash (\)
Example
<?php
$my_str = ‘World’;
echo “Hello, $my_str!<br>”; // Displays: Hello World!
echo ‘Hello, $my_str!<br>’; // Displays: Hello, $my_str!

echo ‘<pre>Hello\tWorld!</pre>’; // Displays: Hello\tWorld!


echo “<pre>Hello\tWorld!</pre>”; // Displays: Hello World!
echo ‘I\’ll be back’; // Displays: I’ll be back
?>

Manipulating PHP Strings


PHP provides many built-in functions for manipulating strings like calculating the
length of a string, find substrings or characters, replacing part of a string with different
characters, take a string apart, and many others. Here are the examples of some of
these functions.

Calculating the Length of a String


The strlen() function is used to calculate the number of characters inside a string. It
also includes the blank spaces inside the string.
<?php
$my_str = ‘Welcome to Tutorial Republic’;

// Outputs: 28
echo strlen($my_str);
?>

3G E-LEARNING
PHP 239

Counting Number of Words in a String


The str_word_count() function counts the number of words in a string.

Example
<?php
$my_str = ‘The quick brown fox jumps over the lazy dog.’;

// Outputs: 9
echo str_word_count($my_str);
?>

Replacing Text within Strings


The str_replace() replaces all occurrences of the search text within the target string.

Example
<?php
$my_str = ‘If the facts do not fit the theory, change the facts.’;

// Display replaced string


echo str_replace(“facts”, “truth”, $my_str);
?>

The output of the above code will be:


If the truth do not fit the theory, change the truth.

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.’;

// Perform string replacement


str_replace(“facts”, “truth”, $my_str, $count);

// Display number of replacements performed


echo “The text was replaced $count times.”;
?>

Reversing a String
The strrev() function reverses a string.

Example
<?php
$my_str = ‘You can do anything, but not everything.’;

// Display reversed string


echo strrev($my_str);
?>

The output of the above code will be:


.gnihtyreve ton tub ,gnihtyna od nac uoY

3G E-LEARNING
PHP 241

6.10 WEB CONCEPTS


This session demonstrates how PHP can provide dynamic content
according to browser type, randomly generated numbers or
User Input. It also demonstrated how the client browser can
be redirected.

6.10.1 Identifying Browser & Platform


PHP creates some useful environment variables that can be
seen in the [Link] page that was used to setup the PHP
environment. One of the environment variables set by PHP is
HTTP_USER_AGENT which identifies the user’s browser and
operating system. PHP provides a function getenv() to access
the value of all the environment variables. The information Keyword
contained in the HTTP_USER_AGENT environment variable can
be used to create dynamic content appropriate to the browser. Operating
The following example demonstrates how you can identify a system (OS) is
system software
client browser and operating system. that manages
computer
<html> hardware
and software
<body> resources
and provides
<?php common services
for computer
$viewer = getenv( “HTTP_USER_AGENT” ); programs.

$browser = “An unidentified browser”;


if( preg_match( “/MSIE/i”, “$viewer” ) )
{
$browser = “Internet Explorer”;
}
else if( preg_match( “/Netscape/i”, “$viewer” ) )
{
$browser = “Netscape”;
}
else if( preg_match( “/Mozilla/i”, “$viewer” ) )

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.

Display Images Randomly


The PHP rand() function is used to generate a random number. This function can
generate numbers with-in a given range. The random number generator should be seeded
to prevent a regular pattern of numbers being generated. This is achieved using the
srand()function that specifies the seed number as its argument. The following example
demonstrates how you can display different image each time out of four images:

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>

It will produce the following result:

3G E-LEARNING
244 Introduction to Computer Programming and Web Designing

Using HTML Forms


The most important thing to notice when dealing with HTML forms and PHP is that any
form element in an HTML page will automatically be available to your PHP scripts. Try
out the following example by putting the source code in [Link] script.
<?php
if( $_POST[“name”] || $_POST[“age”] )
{
echo “Welcome “. $_POST[‘name’]. “<br />”;
echo “You are “. $_POST[‘age’]. “ years old.”;
exit();
}
?>
<html>
<body>
<form action=”<?php $_PHP_SELF ?>” method=”POST”>
Name: <input type=”text” name=”name” />
Age: <input type=”text” name=”age” />
<input type=”submit” />
</form>
</body>
</html>

3G E-LEARNING
PHP 245

It will produce the following result:

■■ The PHP default variable $_PHP_SELF is used for the


PHP script name and when you click “submit” button,
the same PHP script will be called and will produce
following result:
■■ The method = “POST” is used to post user data to the
server script.

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

<form action=”<?php $_PHP_SELF ?>” method=”POST”>


<select name=”location”>
<option value=”[Link]
World Wise Web Consortium
</option>
<option value=”[Link]
Google Search Page
</option>
</select>
<input type=”submit” />
</form>
</body>
</html>

It will produce the following output:

Displaying “File Download” Dialog Box


Sometime it is desired that you want to give option where a use will click a link and
it will pop up a “File Download” box to the user instead of displaying actual content.
This is very easy and will be achieved through HTTP header. The HTTP header will
be different from the actual header where we send Content-Type as text/html\n\n.
In this case content type will be application/octet-stream and actual file name will be
concatenated along with it.
For example, if you want make a FileName file downloadable from a given link,
then its syntax will be as follows.
#!/usr/bin/perl

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”);
}

6.10.2 GET and POST Methods


There are two ways the browser client can send information to the web server.
■■ The GET Method
■■ The POST Method
Before the browser sends the information, it encodes it using a scheme called URL
encoding. In this scheme, name/value pairs are joined with equal signs and different
pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3

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


The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? character.

■■ 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>

It will produce the following result:

3G E-LEARNING
PHP 249

The POST Method


The POST method transfers information via HTTP headers. The
information is encoded as described in case of GET method and
put into a header called QUERY_STRING.
■■ The POST method does not have any restriction on
data size to be sent.
■■ The POST method can be used to send ASCII as well
as binary data.
■■ The data sent by POST method goes through HTTP
header so security depends on HTTP protocol. By using
Secure HTTP you can make sure that your information
is secure.
■■ The PHP provides $_POST associative array to access
all the sent information using POST method.
The following example by putting the source code in test.
php script.

<?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.

<form action=”<?php $_PHP_SELF ?>” method=”POST”>


Name: <input type=”text” name=”name” />

3G E-LEARNING
250 Introduction to Computer Programming and Web Designing

Age: <input type=”text” name=”age” />


<input type=”submit” />
</form>
</body>
</html>
It will produce the following result:

3G E-LEARNING
PHP 251

ROLE MODEL
RASMUS LERDORF: FATHER OF PHP

Rasmus Lerdorf (born 22 November 1968),who created the PHP


scripting language, is a Greenlandic programmer with Canadian
citizenship, authoring the first two versions of the language
and participated in the development of later versions led by a
group of developers including Jim Winstead (who later created
blogs), Stig Bakken, Shane Caraveo, Andi Gutmans and Zeev
Suraski. He continues to contribute to the project.

Beginning of Life and his Studies


His family moved to Canada from his native Greenland, in 1980,
and later moved to King City, Ontario in [Link] graduated from
King City Secondary School in 1988, and in 1993 he graduated
from the University of Waterloo with a Bachelor of Applied
Science in Systems Design Engineering. He contributed to the
Apache HTTP Server and he added the LIMIT clause to the MSQL
DBMS. A variant of this LIMIT clause had already been around
for a decade in mainframe relational database management
systems (like Oracle Rdb running on VAX/VMS, formerly from
Digital Equipment Corporation), but apparently it had not yet
been picked up by the emerging PC-based databases. It was
later adapted by several other SQL-compatible DBMS.

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.

MULTIPLE CHOICE QUESTIONS


1. What PHP stands for?
a. Hypertext Preprocessor
b. Pre Hypertext Processor
c. Pre Hyper Processor
d. Pre Hypertext Process

3G E-LEARNING
PHP 253

2. What will the following script output?


<?php
$array = array (1, 2, 3, 5, 8, 13, 21, 34, 55);
$sum = 0;
for ($i = 0; $i < 5; $i++) {
$sum += $array[$array[$i]];
}
echo $sum;
?>

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

3. Write a Program to swap two numbers in PHP.


4. Write a program to print Factorial of any number
5. What are the differences between Get and post methods.

Answer to Multiple Choice Questions


1. (d) 2. (a) 3. (c) 4. (c) 5. (a)

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

“Java is to JavaScript as ham is to hamster.”


-Jeremy Keith

LEARNING OBJECTIVES

After studying this chapter, you will be able to:

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.

7.1 WHAT IS JAVASCRIPT?


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. JavaScript was first known as LiveScript,
but Netscape changed its name to JavaScript, possibly because of the excitement being
generated by Java. The general-purpose core of the language has been embedded in
Netscape, Internet Explorer, and other web browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript
language.
■■ JavaScript is a lightweight, interpreted programming language.
■■ Designed for creating network-centric applications.
■■ Complementary to and integrated with Java.
■■ Complementary to and integrated with HTML.
■■ Open and cross-platform.

7.1.1 History of JavaScript


JavaScript, not to be confused with Java, was created in 10 days in May 1995 by Brendan
Eich, then working at Netscape and now of Mozilla. JavaScript was not always known
as JavaScript: the original name was Mocha, a name chosen by Marc Andreessen,

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

backbone, used to create web applications where data can be


loaded in the background, avoiding the need for full page reloads
and resulting in more dynamic applications. This resulted in
a renaissance period of JavaScript usage spearheaded by open
source libraries and the communities that formed around them,
with libraries such as Prototype, jQuery, Dojo and Mootools and
others being released.
In July of 2008 the disparate parties on either side came
together in Oslo. This led to the eventual agreement in early
Keyword 2009 to rename ECMAScript 3.1 to ECMAScript 5 and drive the
Javascript language forward using an agenda that is known as Harmony.
(JS)
is a scripting All of this then brings us to today, with JavaScript entering
languages, a completely new and exciting cycle of evolution, innovation
primarily used
on the Web. It is and standardisation, with new developments such as the Nodejs
used to enhance platform, allowing us to use JavaScript on the server-side, and
HTML pages HTML5 APIs to control user media, open up web sockets for
and is commonly
found embedded
always-on communication, get data on geographical location
in HTML code. and device features such as accelerometer, and more. It is an
exciting time to learn JavaScript.

7.1.2 Client-Side JavaScript


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.
It means that a web page need not be a static HTML, but
can include programs that interact with the user, control the
browser, and dynamically create HTML content. The JavaScript
client-side mechanism provides many advantages over traditional
CGI server-side scripts. For example, you might use JavaScript
to check if the user has entered a valid e-mail address in a
form field.
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. JavaScript can be used to trap
user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.

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.

7.2 JAVASCRIPT SYNTAX


JavaScript can be implemented using JavaScript statements
that are placed within the <script>... </script> HTML tags in
a web page. You can place the <script> tags, containing your
JavaScript, anywhere within you web page, but it is normally
recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting
all the text between these tags as a script. A simple syntax of
your JavaScript will appear as follows.

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>

First JavaScript Code


Let us take a sample example to print out “Hello World”. We added an optional
HTML comment that surrounds our JavaScript code. This is to save our code from a
browser that does not support JavaScript. The comment ends with a “//-- >”. Here “//”
signifies a comment in JavaScript, so we add that to prevent a browser from reading
the end of the HTML comment as a piece of JavaScript code. Next, we call a function
[Link] which writes a string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following
code.

<html>
<body>
<script language=”javascript” type=”text/javascript”>
<!--
[Link] (“Hello World!”)
//-->
</script>

3G E-LEARNING
JavaScript Programming 263

</body>
</html>

This code will produce the following result:

Hello World!

Whitespace and Line Breaks


JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You
can use spaces, tabs, and newlines freely in your program and you are free to format
and indent your programs in a neat and consistent way that makes the code easy to
read and understand.

Semicolons are Optional


Simple statements in JavaScript are generally followed by a semicolon character, just
as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon
if each of your statements are placed on a separate line. For example, the following
code could be written without semicolons.
<script language=”javascript” type=”text/javascript”>
<!--
var1 = 10
var2 = 20
//-->
</script>

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:

■■ Numbers, e.g., 123, 120.50 etc.


■■ Strings of text, e.g. “This text string” etc.
■■ Boolean, e.g. true or false.
JavaScript also defines two trivial data types, null and
undefined, each of which defines only a single value. In addition
to these primitive data types, JavaScript supports a composite
data type known as object.

7.3.1 JavaScript Variables


Like many other programming languages, JavaScript has
variables. Variables can be thought of as named containers. You
can place data into these containers and then refer to the data
simply by naming the container. Before you use a variable in a
JavaScript program, you must declare it. Variables are declared
with the var keyword as follows.
<script type=”text/javascript”>
<!--
var money;
var name;

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>

JavaScript is untyped language. This means that a JavaScript


variable can hold a value of any data type. Unlike many other
languages, you don’t have to tell JavaScript during variable

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.

7.3.2 JavaScript Variable Names


While naming your variables in JavaScript, keep the following rules in mind.
■■ You should not use any of the JavaScript reserved keywords as a variable
name. For example, break or boolean variable names are not valid.
■■ JavaScript variable names should not start with a numeral (0-9). They must
begin with a letter or an underscore character. For example, 123test is an
invalid variable name but _123test is a valid one.
■■ JavaScript variable names are case-sensitive. For example, Name and name
are two different variables.

7.3.3 JavaScript Reserved Words


A list of all the reserved words in JavaScript are given in the following table. They
cannot be used as JavaScript variables, functions, methods, loop labels, or any object
names.

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.

7.4.1 Assignment operators


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.

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:

Compound assignment operators


Name Shorthand Meaning
operator
Assignment x=y x=y
Addition assignment x += y x=x+y
Subtraction assignment x -= y x=x-y
Multiplication assignment x *= y x=x*y
Division assignment x /= y x=x/y
Remainder assignment x %= y x=x%y
Exponentiation assignment x **= y x = x ** y
Left shift assignment x <<= y x = x << y
Right shift assignment x >>= y x = x >> y
Unsigned right shift x >>>= y x = x >>>
assignment y
Bitwise AND assignment x &= y x=x&y
Bitwise XOR assignment x ^= y x=x^y
Bitwise OR assignment x |= y x=x|y

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

7.4.2 Comparison Operators


A comparison operator compares its operands and returns a logical value based on
whether the comparison is true. The operands can be numerical, string, logical, or
object values. Strings are compared based on standard lexicographical ordering, using
Unicode values. In most cases, if the two operands are not of the same type, JavaScript
attempts to convert them to an appropriate type for the comparison. This behavior
generally results in comparing the operands numerically. The sole exceptions to type
conversion within comparisons involve the === and !== operators, which perform strict
equality and inequality comparisons. These operators do not attempt to convert the
operands to compatible types before checking equality. The following table describes
the comparison operators in terms of this sample code:
var var1 = 3;
var var2 = 4;

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

7.4.3 Arithmetic operators


An arithmetic operator takes numerical values (either literals or
Remember variables) as their operands and returns a single numerical value.
(=>) is The standard arithmetic operators are addition (+), subtraction
not an (-), multiplication (*), and division (/). These operators work
operator, but as they do in most other programming languages when used
the notation for
Arrow functions. with floating point numbers (in particular, note that division
by zero produces Infinity). For example:

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.

7.4.4 Bitwise Operators


A bitwise operator treats their operands as a set of 32 bits
(zeros and ones), rather than as decimal, hexadecimal, or octal

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.

Bitwise Logical Operators


Conceptually, the bitwise logical operators work as follows:
■■ The operands are converted to thirty-two-bit integers and expressed by a
series of bits (zeros and ones). Numbers with more than 32 bits get their most
significant bits discarded. For example, the following integer with more than
32 bits will be converted to a 32 bit integer:
Before: 11100110111110100000000000000110000000000001
After: 10100000000000000110000000000001

■■ 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

Bitwise operator examples

Expression Result Binary Description


15 & 9 9 1111 & 1001 = 1001
15 | 9 15 1111 | 1001 = 1111
15 ^ 9 6 1111 ^ 1001 = 0110
~15 -16 ~00000000...00001111
= 11111111...11110000
~9 -10 ~00000000...00001001
= 11111111...11110110

Bitwise Shift Operators


The bitwise shift operators take two operands: the first is a quantity to be shifted, and
the second specifies the number of bit positions by which the first operand is to be
shifted. The direction of the shift operation is controlled by the operator used.
Shift operators convert their operands to thirty-two-bit integers and return a result
of the same type as the left operand.
The shift operators are listed in the following table.

Bitwise shift operators


Operator Description Example
Left shift This operator shifts the first 9<<2 yields 36, because 1001 shifted
(<<) operand the specified number of 2 bits to the left becomes 100100,
bits to the left. Excess bits shifted which is 36.
off to the left are discarded. Zero
bits are shifted in from the right.
Sign- This operator shifts the first 9>>2 yields 2, because 1001 shifted
propagating operand the specified number of 2 bits to the right becomes 10,
right shift(>>) bits to the right. Excess bits shifted which is 2. Likewise, -9>>2 yields -3,
off to the right are discarded. because the sign is preserved.
Copies of the leftmost bit are
shifted in from the left.
Zero-fill right This operator shifts the first 19>>>2 yields 4, because 10011
shift(>>>) operand the specified number of shifted 2 bits to the right becomes
bits to the right. Excess bits shifted 100, which is 4. For non-negative
off to the right are discarded. Zero numbers, zero-fill right shift and
bits are shifted in from the left. sign-propagating right shift yield
the same result.

3G E-LEARNING
JavaScript Programming 273

7.4.5 Logical Operators


Logical operators are typically used with Boolean (logical) values; when they are, they
return a Boolean value. However, the && and || operators actually return the value
of one of the specified operands, so if these operators are used with non-Boolean
values, they may return a non-Boolean value. The logical operators are described in
the following table.

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

The following code shows examples of the || (logical OR) operator.


var o1 = true || true; // t || t returns true
var o2 = false || true; // f || t returns true

3G E-LEARNING
274 Introduction to Computer Programming and Web Designing

var o3 = true || false; // t || f returns true


var o4 = false || (3 == 4); // f || f returns false
var o5 = “Cat” || “Dog”; // t || t returns Cat
var o6 = false || “Cat”; // f || t returns Cat
var o7 = “Cat” || false; // t || f returns Cat

The following code shows examples of the ! (logical NOT) operator.


var n1 = !true; // !t returns false
var n2 = !false; // !f returns true
var n3 = !”Cat”; // !t returns false

7.4.6 String Operators


In addition to the comparison operators, which can be used on string values, the
concatenation operator (+) concatenates two string values together, returning another
string that is the union of the two operand strings.

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.

7.4.7 Conditional (ternary) Operator


The conditional operator is the only JavaScript operator that takes three operands. The
operator can have one of two values based on a condition. The syntax is:
condition ? val1 : val2

3G E-LEARNING
JavaScript Programming 275

If condition is true, the operator has the value of val1.


Otherwise it has the value of val2. You can use the conditional
operator anywhere you would use a standard operator.
For example,
var status = (age >= 18) ? “adult” : “minor”;

This statement assigns the value “adult” to the


variable status if age is eighteen or more. Otherwise, it assigns
the value “minor” to status.

7.4.8 Comma Operator


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.
For example, if a is a 2-dimensional array with 10 elements Keyword
on a side, the following code uses the comma operator to Variable
is a value
update two variables at once. The code prints the values of the that can change,
diagonal elements in the array: depending on
conditions or
for (var i = 0, j = 9; i <= j; i++, j--) on information
passed to the
[Link](“a[“ + i + “][“ + j + “]= “ + a[i][j]); program.

7.4.9 Relational Operators


A relational operator compares its operands and returns
a Boolean value based on whether the comparison is true.
in
The in operator returns true if the specified property is in the
specified object. The syntax is:
propNameOrNumber in objectName

where propNameOrNumber is a string or numeric expression


representing a property name or array index, and objectName is
the name of an object.

3G E-LEARNING
276 Introduction to Computer Programming and Web Designing

The following examples show some uses of the in operator.

// 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
}

7.4.10 Operator Precedence


The precedence of operators determines the order they are applied when evaluating an
expression. You can override operator precedence by using parentheses.
The following table describes the precedence of operators, from highest to lowest.

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

Let’s see the simple example of if statement in javascript.


<script>
var a=20;
if(a>10){
[Link](“value of a is greater than 10”);
}
</script>

Output of the example:

value of a is greater than 10

7.5.1 JavaScript If...else Statement


It evaluates the content whether condition is true of false. The syntax of JavaScript
if-else statement is given are.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

Flowchart of JavaScript If...else statement:

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>

Output of the example:

3G E-LEARNING
JavaScript Programming 281

a is even number

7.5.2 JavaScript If...else if statement


It evaluates the content only if expression is true from several expressions. The signature
of JavaScript if else if statement is given are.

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
}

Let’s see the simple example of if else if statement in javascript.

<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

[Link](“a is equal to 15”);


}
else if(a==20){
[Link](“a is equal to 20”);
}
else{
[Link](“a is not equal to 10, 15 or 20”);
}
</script>

Output of the example

a is equal to 20

7.5.3 JavaScript Switch


The JavaScript switch statement is used to execute one code from multiple expressions.
But it is convenient than if..else..if because it can be used with numbers, characters etc.
The signature of JavaScript switch statement is given are.
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

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>

Output of the example:


B Grade

3G E-LEARNING
284 Introduction to Computer Programming and Web Designing

Let’s understand the behavior of switch statement in


JavaScript.

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>

Output of the example:

B Grade B Grade C Grade No Grade

7.6 JAVASCRIPT LOOPS


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.
There are four types of loops in JavaScript.
■■ for loop

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
}

Let’s see the simple example of for loop in javascript.


<script>
for (i=1; i<=5; i++)
{
[Link](i + “<br/>”)
}
</script>

Output:
1
2
3
4
5

3G E-LEARNING
286 Introduction to Computer Programming and Web Designing

7.6.2 JavaScript while loop


The JavaScript while loop iterates the elements for the infinite number of times. It should
be used if number of iteration is not known. The syntax of while loop is given are:

while (condition)
{
code to be executed
}

Let’s see the simple example of while loop in javascript.


<script>
var i=11;
while (i<=15)
{
[Link](i + “<br/>”);
i++;
}
</script>

Output:
11
12
13
14
15

3G E-LEARNING
JavaScript Programming 287

7.6.3 JavaScript do while loop


The JavaScript do while loop iterates the elements for the infinite number of times like
while loop. But, code is executed at least once whether condition is true or false. The
syntax of do while loop is given are:
do{
code to be executed
}while (condition);

Let’s see the simple example of do while loop in javascript.


<script>
var i=21;
do{
[Link](i + “<br/>”);
i++;
}while (i<=25);
</script>

Output:
21
22
23
24
25

7.6.4 JavaScript For-In Loop


The for...in loop is used to loop through an object’s properties. As we have not discussed
Objects yet, you may not feel comfortable with this loop. But once you understand

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>

7.7.1 Calling a Function


To invoke a function somewhere later in the script, you would simply need to write
the name of that function as shown in the following code.
<html>
<head>
<script type=”text/javascript”>
function sayHello()
{
[Link] (“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

7.7.2 Function Parameters


We have seen functions without parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside
the function and any manipulation can be done over those parameters. A function can
take multiple parameters separated by comma.
Example
The following example. We have modified our sayHello function here. Now it takes two
parameters.

<html>
<head>
<script type=”text/javascript”>
function sayHello(name, age)
{

3G E-LEARNING
JavaScript Programming 293

[Link] (name + “ is “ + age + “ years old.”);


}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type=”button” onclick=”sayHello(‘Zara’, 7)” value=”Say Hello”>
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

Output:
Click the following button to call the function

Use different parameters inside the function and then try...

7.7.3 The Return Statement


A JavaScript function can have an optional return statement. This is required if you
want to return a value from a function. This statement should be the last statement
in a function. For example, you can pass two numbers in a function and then you can
expect the function to return their multiplication in your calling program.
Example
The following example. It defines a function that takes two parameters and concatenates
them before returning the resultant in the calling program.

<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

Use different parameters inside the function and then try...

7.7.4 Nested Functions


Prior to JavaScript 1.2, function definition was allowed only in top level global code,
but JavaScript 1.2 allows function definitions to be nested within other functions as
well. Still there is a restriction that function definitions may not appear within loops
or conditionals. These restrictions on function definitions apply only to function
declarations with the function statement.

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; }

return [Link](square(a) + square(b));


}
function secondFunction(){
var result;
result = hypotenuse(1,2);
[Link] ( result );
}
//-->
</script>

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

Use different parameters inside the function and then try...

7.7.5 Function () Constructor


The function statement is not the only way to define a new function; you can define
your function dynamically using Function() constructor along with the new operator.

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

Use different parameters inside the function and then try...

7.8 JAVASCRIPT OBJECTS


A javaScript object is an entity having state and behavior (properties and method).
For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don’t create class to get the
object. But, we direct create objects.

7.8.1 Creating Objects in JavaScript


There are 3 ways to create objects.
■■ By object literal
■■ By creating instance of Object directly (using new keyword)
■■ By using an object constructor (using new keyword)

JavaScript Object by object literal


The syntax of creating object using object literal is given are:

object={property1:value1,property2:value2.....propertyN:valueN}

Property and value is separated by : (colon).


Let’s see the simple example of creating object in JavaScript.

<script>
emp={id:102,name:”Shyam Kumar”,salary:40000}

3G E-LEARNING
JavaScript Programming 299

[Link]([Link]+” “+[Link]+” “+[Link]);


</script>

Output
102 Shyam Kumar 40000

By creating instance of Object


The syntax of creating object directly is given are:

var objectname=new Object();

New keyword is used to create object.


Let’s see the example of creating object directly.

<script>
var emp=new Object();
[Link]=101;
[Link]=”Ravi Malik”;
[Link]=50000;
[Link]([Link]+” “+[Link]+” “+[Link]);
</script>

Output:
101 Ravi 50000

By using an Object constructor


You need to create function with arguments. Each argument value can be assigned in
the current object by using this keyword.

3G E-LEARNING
300 Introduction to Computer Programming and Web Designing

The this keyword refers to the current object.


The example of creating object by object constructor is given are:
<script>
function emp(id,name,salary){
[Link]=id;
[Link]=name;
[Link]=salary;
}
e=new emp(103,”Vimal Jaiswal”,30000);

[Link]([Link]+” “+[Link]+” “+[Link]);


</script>

Output:
103 Vimal Jaiswal 30000

7.8.2 Method in JavaScript Object


We can define method in JavaScript object. But before defining method, we need to
add property in the function with same name as method.
The example of defining method in object is given are:

<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];

values are contained inside [ ] and separated by , (comma).


Let’s see the simple example of creating and using array in JavaScript.

<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

Array constructor (new keyword)


You need to create instance of array by passing arguments in constructor so that we
don’t have to provide value explicitly.
The example of creating object by array constructor is given are.

<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”;

Let’s see the simple example of creating string literal.


<script>
var str=”This is string literal”;
[Link](str);
</script>

Output:
This is string literal

By string object (using new keyword)


The syntax of creating string object using new keyword is given are:
var stringname=new String(“string literal”);

3G E-LEARNING
JavaScript Programming 305

Here, new keyword is used to create instance of string.


Let’s see the example of creating string in JavaScript by new keyword.

<script>
var stringname=new String(“hello javascript string”);
[Link](stringname);
</script>

Output:
hello javascript string

7.8.5 String Methods


The list of JavaScript string methods with examples.
■■ charAt(index)
■■ concat(str)
■■ indexOf(str)
■■ lastIndexOf(str)
■■ toLowerCase()
■■ toUpperCase()
■■ slice(beginIndex, endIndex)
■■ trim()

JavaScript string charAt(index) Method


The JavaScript String charAt() method returns the character at the given index.
<script>
var str=”javascript”;
[Link]([Link](2));
</script>

3G E-LEARNING
306 Introduction to Computer Programming and Web Designing

Output:
v

JavaScript string concat(str) Method


The JavaScript String concat(str) method concatenates or joins two strings.
<script>
var s1=”javascript “;
var s2=”concat example”;
var s3=[Link](s2);
[Link](s3);
</script>

Output:
javascript concat example

JavaScript string indexOf(str) Method


The JavaScript String indexOf(str) method returns the index position of the given string.

<script>
var s1=”javascript from javatpoint indexof”;
var n=[Link](“from”);
[Link](n);
</script>

Output:
11

3G E-LEARNING
JavaScript Programming 307

JavaScript string lastIndexOf(str) Method


The JavaScript String lastIndexOf(str) method returns the last index position of the given
string.

<script>
var s1=”javascript from javatpoint indexof”;
var n=[Link](“java”);
[Link](n);
</script>

Output:
16

JavaScript string toLowerCase() Method


The JavaScript String toLowerCase() method returns the given string in lowercase letters.

<script>
var s1=”JavaScript toLowerCase Example”;
var s2=[Link]();
[Link](s2);
</script>

Output:
javascript tolowercase example

JavaScript string toUpperCase() Method


The JavaScript String toUpperCase() method returns the given string in uppercase letters.

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

JavaScript String slice(beginIndex, endIndex) Method


The JavaScript String slice(beginIndex, endIndex) method returns the parts of string
from given beginIndex to endIndex. In slice() method, beginIndex is inclusive and
endIndex is exclusive.

<script>
var s1=”abcdefgh”;
var s2=[Link](2,5);
[Link](s2);
</script>

Output:
cde

JavaScript String trim() Method


The JavaScript String trim() method removes leading and trailing whitespaces from
the string.
<script>
var s1=” javascript trim “;

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

Brendan Eich is an American technologist and creator of the


JavaScript programming language. He co-founded the Mozilla
project,the Mozilla Foundation and the Mozilla Corporation,
and served as the Mozilla Corporation’s chief technical officer
and briefly its chief executive officer.

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.

Netscape and JavaScript


He started work at Netscape Communications Corporation in
April 1995. Having originally joined intending to put Scheme
“in the browser”,Eich was instead commissioned to create a
new language that resembled Java, JavaScript for the Netscape
Navigator Web browser. The first version was completed in
ten days in order to accommodate the Navigator 2.0 Beta
release schedule,and was called Mocha, which was later
renamed LiveScript in September 1995 and later JavaScript in
the same [Link] continued to oversee the development
of SpiderMonkey, the specific implementation of JavaScript in
Navigator, until 2011.

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.

CEO appointment and resignation


On March 24, 2014, Eich was promoted to CEO of Mozilla [Link] appointment
sparked controversy over a $1,000 political donation Eich had made in 2008 to the
successful campaign for California Proposition 8, which sought to establish that, “Only
marriage between a man and a woman is valid or recognized in California.”This was
criticized by gay rights activists on [Link] the ensuing public debate, OKCupid
and two gay application developers called for a boycott of the [Link] at the
Mozilla Corporation spoke out on their blogs in his [Link] members wanted him
to stay in the company with a different role.
On April 3, 2014, Eich stepped down as CEO and resigned from working at Mozilla.
In his personal blog, Eich posted that “under the present circumstances, I cannot be
an effective leader.”
Following Eich’s resignation, the National Organization for Marriage called for its
own boycott of Mozilla, due to “gay activists who have forced him out of the company
he has helped lead for years”.

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.

MULTIPLE CHOICE QUESTIONS


1. Javascript is _________ language.
a. Programming
b. Applicatio
c. None of These
d. Scripting
2. JavaScript is ______ Side Scripting Language.
a. Server
b. ISP

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.

Answer to Multiple Choice Questions


1. (d) 2. (d) 3. (b) 4. (b) 5. (a)

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

A destructuring assignment 268, 312


Arithmetic Operators 13, 14 E
array 203, 213, 221, 222, 227, 231, 232, 233, 234,
element backgrounds 181
235, 236, 237, 248, 249, 252, 253
e-mail link 106
Assignment Operator 13, 17
embedded style sheet 169, 171, 195
associative arrays 234
Extensible Hypertext Markup Language (XHT-
B ML) 88
Extensible Markup Language (XML) 122, 123
background color 100, 113
external style sheet 166, 168, 175, 176, 177
bgcolor 97, 98, 100, 113, 117
Bitwise Operator 13, 19, 20 F
blue value(BB) 101
Firefox 89
box model 165, 185, 187, 190
floating point 6, 7, 9
browsers 88, 90, 94, 100, 102, 117
C H
horizontal length 183
cascading style sheet (CSS) 166, 195
HTML 4.01 122, 123
Cascading Style Sheet, level 1 (CSS1) 166, 195
HTML language 89
Character Constants 7, 11
HTML pages 258, 260, 261
character set 1, 2, 3, 6
HTML syntax 125, 161
C language 2, 3, 6, 11, 12, 46
Hypertext Preprocessor 200, 252
Comma Operator 13, 22
comparison operator 269 I
computer programming language 258, 312
conditional expressions 27 inline styles 165, 168, 172, 175, 195
Integer Constants 7
D integer data 6
Internal links 105
data types 1, 4, 6, 17, 47, 257, 264
interpreted programming language 258, 261, 312
316 Introduction to Computer Programming and Web Designing

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

You might also like