PROGRAMMING
PROGRAMMING
principles of programming
and web technologies
STUDY MATERIAL
Version 1
©
Centre for Development of Imaging Technology (C-DIT)
This edition is authorised for Private Circulation Only
All rights reserved. This publication may not be reproduced in any way.
Preface
6 Abbreviation 256
kn Unäv
Module I
Basics of Programming
Algorithm and its Characteristics
An Algorithm is a step-by-step process that specifies a set of instructions to be carried out in
a specific order in order to get the desired outcome. In other words, an algorithm is a collection of
instructions that a computer must follow in in order to perform calculations or other problem-solving
tasks. An algorithm is formally defined as a finite set of instructions that are followed in a specified
order to accomplish a specific task. It is not the whole programme or code; rather, it is the informal
explanation of a problem in the form of a flowchart or pseudocode, which represents the problem's
simple logic.
An algorithm can be implemented in more than one programming language because algorithms
are usually developed independently of the underlying languages. The dataflow of the algorithm is
depicted in Figure 1.1:
Characteristics of Algorithm
As one would merely follow the typical recipe for preparing a lemon juice rather than any
written instructions. Similar to this, not every set of computer instructions is an algorithm. Some
instructions must satisfy the following criteria in order to be considered as an algorithm:
• Clear and Unambiguous: The algorithm should be unambiguous and clear. A perfect algorithm
is defined as unambiguous, which means that it should have simple, clear instructions. Each
of its steps must have a distinct meaning and be transparent from beginning to end.
• Well Defined Inputs: A algorithm needs some input values. A value other than 0 may be
provided as input to an algorithm.
• Well Defined Outputs: The output that will be generated by the algorithm must be specified
in depth and be well-defined. It must produce at least single output.
• Finiteness: An algorithm needs to be finite. In this context, "finiteness" refers to the requirement
that an algorithm have a finite number of instructions, or instructions that can be counted.
• Feasible: The algorithm must be straightforward, general, and functional such that it may be
executed using the currently available resources. It must be devoid of all future technology.
• Language Independent: The algorithm must be language-independent, meaning it must
consist of just simple instructions that may be used to build it in any language and still produce
the desired results.
Algorithms have the following benefits:
• They are simple to grasp.
• They are a step-by-step depiction of a solution to a given problem.
• Because the problem is broken down into smaller bits or steps, it is simpler for the programmer
to turn an algorithm into a working programme.
Algorithm disadvantages include the following:
• It takes a lot of time to write an algorithm, hence it is time-consuming.
• It can be quite challenging to understand complex reasoning using algorithms.
• It is challenging to demonstrate branching and looping statements in algorithms.
Design an Algorithm
The algorithm is written with the help of the following parameters: problem, constraints,
input, output and solution. These parameters helps to solve the given problem.
Let’s consider an example: multiply any 3 numbers and find its product.
Step 1: Fulfilling the pre-requisites.
• The problem statement is: Multiply 3 numbers and print their product.
• The constraints of the problem that must be considered while solving the problem: The
numbers must contain only digits/numerals and no other characters.
• The input to be taken to solve the problem: The three numbers to be multiplied.
• The output to be expected when the problem is solved: The product of the three numbers taken
as the input i.e. a single integer value.
• The solution to this problem, in the given constraints: The solution consists of multiplying the
3 numbers. It can be carried out in any method of the user's choice.
Step 2: Designing the algorithm
Now let’s design the algorithm with the help of the above pre-requisites:
Algorithm to multiply 3 numbers and print their product:
1. START
2. Declare 3 integer variables num1, num2 and num3.
3. Take 3 numbers num1, num2, and num3 respectively , to be multiplied, as inputs.
4. Declare an integer variable prod to store the resultant product of the 3 given numbers.
5. Multiply the 3 numbers and store the result in the variable prod.
6. Print the value of the variable prod
7. END
The algorithm can also be written as follows
Step 1 − Start
Step 2 − get values of num1, num2, num3 & prod
Step 3 − prod ← num1 * num2 * num3
Step 4 − display prod
Step 5 − Stop
Step 3: Testing the algorithm by implementing it.
In order to test the algorithm, it can be implemented using any programming language.
When creating an algorithm, the following factors should be considered:
• Modularity: This feature was perfectly designed for the algorithm if you are given a problem
and divide it into small precise modules or steps, which is a basic definition of an algorithm.
• Correctness: When the given inputs result in the expected output, an algorithm is said to
be correct, proving that it was properly developed. The analysis of an algorithm has been
successfully performed.
• Maintainability: This refers to the idea that the algorithm should be created in a simple,
organised manner so that when it is redefined, it does not undergo significant changes.
• Functionality: It considers several logical procedures in order to resolve a practical issue.
• Robustness: The term robustness refers to an algorithm's capacity to precisely address your
issue.
• User-friendly: The designer won't describe the method to the coder if it is hard to understand.
• Simplicity: An algorithm is easy to grasp if it is simple.
• Extensibility: If another algorithm designer or programmer wants to utilise your algorithm, it
should be expandable.
Real-world problems must be divided into smaller modules when they are presented to you.
You must first comprehend all of the problem's theoretical facets in order to dismantle it. ou are all
aware that theory is incomplete without application in the real world. Algorithm importance can
therefore be seen from a theoretical and practical perspective. The amount of Space and Time that an
algorithm uses determines how complex it is. As a result, an algorithm's complexity is determined by
how much time and space it will require to store all the data and execute the algorithm to produce the
desired result. Therefore, these two elements determine how effective an algorithm is.
Pseudocode describes the distinct steps of an algorithm in a way that’s easy for anyone with
to understand. The rules of Pseudocode are reasonably straightforward. It enables the algorithm's
logic to be concentrated on by the designer rather than being sidetracked by language specifics.
The pseudocode must be finished at the same time. It explains the entire algorithm's logic, making
it so that writing it into source code becomes a mechanical, rote operation. Statements that show
"dependency" must all be indented. Some of these are while, do, for, if, and switch.
Advantage of Pseudocode
• Enhances the readability of any strategy. It's one of the greatest methods for beginning the
implementation of an algorithm.
• Serves as a link between the algorithm or flowchart and the programs. Additionally serves as
a rudimentary form of documentation, making it simple to understand a developer's software
when written out as pseudocode. Documentation methods are crucial in industries. A pseudo-
code becomes crucial in such situation.
• Pseudocode's major objective is to precisely describe what each line of a programme should
accomplish, making the programming process much easier for the programmer.
Flow Chart
The flowchart is a diagram or illustration which visually presents the flow of data through
processing systems. This means that one can learn about the processes carried out and their order in
a system by looking at a flow chart. Algorithms are simply a series or sequence of steps used to solve
issues. So an algorithm can be represented using a flowchart. A flowchart is the graphical or pictorial
representation of an algorithm with the help of different symbols, shapes, and arrows to demonstrate a
process or a program. With algorithms, we can easily understand a program. A flowchart will outline
the steps necessary to solve a particular problem. A flow chart can be thought of as a blueprint for
a solution you have come up with to an issue. The main purpose of using a flowchart is to analyze
different methods.
Flowcharts are typically used in the following situations:
• When programmers create projects, they use it the most. Many people choose flowcharts since
they are a fundamental part of creating projects pictorially.
• When a process' flowcharts are developed, the programmer can identify its ineffective
components. Therefore, flowcharts are utilised to distinguish useful logic from undesirable
components.
• A flowchart can be used as a communication tool for those working on the same project
because the rules and process for constructing one are universal.
• With flowcharts, process optimization is made simpler. The drawing of flowcharts increases
the efficiency of code.
• To develop understanding of how a process is done and to study a process of the project for
improvement
Table 1.1: Symbols used to draw any flowchart
• To develop understanding of how a process is done and to study a process of the project for
improvement
Table 1.1: Symbols used to draw any flowchart
Process Terminator
Decision
Represent a step in a process. Indicates the starting or ending
most common component of a of the program,
flowchart. Used to ask a question that can
be answered inYes/No,
True/False
A preparation step
Off-page
Manual Input Connector Display
Merge
Delay
Data Storage
Describes a waiting period that Point where sperate orocesses Data stored in any format
occurs while data flow join together
14
General flowcharting guidelines Principles of Programming and Web Technologies
Disadvantages of Flowchart
• Difficult to draw for large and complex programs.
• It does not contain the proper amount of details.
• Very difficult to reproduce.
• Flowcharts are very difficult to modify.
Algorithms Flowcharts
Diagram that depicts the flow of data using vari-
Step by step procedure to solve any problems
ous shapes.
Complex to understand Easier to understand
Challenging to demonstrate branching and
Simple to illustrate branching and looping.
looping
Plain, straightforward text is used. Represented using symbols and shapes.
Does not follow any rules. Predefined rules are followed for construction
machine readable format i.e. machine language. The process of translation of source code
into the machine language is called the compilation. Each programming language has its
own compiler program which translates the source code into its target code. The converted
program in machine language is then executed by the computer which is known as program
execution.
• Testing and Debugging - Debugging is the process of finding errors and removing them from
developed program, otherwise they will lead to failure of the program. There are normally two
types of error: Syntax error and Logical error. The Syntax errors are identified by compiler
at the program compilation time while the logical errors are identified at the execution time.
Even after taking utmost care during program design and coding phase, some errors may exist
in the program and these errors appear during compilation or linking or execution process.
Debugging is generally done by program developer. After debugging, Testing is performed to
verify that whether the completed software functions or works according to the expectations
defined by the requirements. Testing is generally performed by testers. They repetitively
executes program with the intention to find errors. After testing, list of errors and related
information is sent to program developer. The developer solves the issues raised by the testers
and again sents for testing.
• Problem Documentation - All the technical information related to the program code are
contained in the programming documentation or manual. Even the original programmer finds
it difficult to update and maintain the application without clear documentation.
Programming languages are mainly categorized into three types : Machine level language,
Assembly level language and High-level language. Before going in detail on these types, we shall
briefly look into what language translator is and its importance.
Computers cannot read program statements that are written in any programming language
format. These needs to be converted. The language translator programs are used to convert English-
like software programs into machine code that can be understood by the computer. After conversion
to machine code (0s and 1s format), the program can be run and executed by the computer. Types of
Language Translators includes Compilers & Interpreters. These are programs that convert high level
programming languages into its corresponding machine code.
Table 1.3: Difference between Compilers and Interpreters
Compilers Interpreters
Scans the entire program and translates the Translates just one statement of the program at a
whole of it into machine code at once. time into its corresponding machine code.
Takes more time to analyze the source code. Takes very less time to analyze the source code.
However, the overall time taken to execute the But, the overall time to execute the process is
process is much faster. much slower.
Always generates an intermediary object code. Does not generate an intermediary code. Hence,
It will need further linking. Hence more memo- an interpreter is highly efficient in terms of its
ry is needed. memory.
Used by programming languages like C and Used by programming languages like Ruby and
C++ for example. Python for example.
A programming model based on the idea of invoking procedures and deriving from structured
programming is known as procedural oriented programming (POP) or procedural programming.
Procedures, usually referred to as routines, subroutines, or functions, are essentially a set of computing
processes that must be completed. Any given process may be called at any time while a programme
is running, either by other procedures or the same procedure itself. It usually follows a step-by-
step approach in order to break down a task into a set of variables and routines via a sequence of
instructions as depicted in Figure 1.3.
There are pros and cons to procedural programming, some of which are given here.
Advantages
• Programming for general purposes works very well with procedural programming.
• Clarity of the code and the simplicity with which compilers/interpreters can be implemented.
• Since the source code is portable, it can also be used to target a different CPU.
• The code can be reused in different parts of the program, without the need to copy it.
• The memory required is reduced by using procedural programming techniques.
• It is simple to follow the programme flow.
Disadvantages
• When procedural programming is used, writing programme code is more difficult.
• Because procedural code is frequently not reusable, it could be necessary to rebuild it if it
needs to be used in another application.
• Difficult to relate to real-world objects.
• The operation is given more weight than the data, which could cause problems in particular
circumstances where the data is important.
• It is less secure because the data is accessible to the entire application.
Programming that is built on the idea of objects is known as object-oriented programming. Data
are found in the form of attributes, while code is found in the form of methods. Computer programmes
are created in object-oriented programming (OOP) utilising the idea of objects that interact with the
outside environment. Although there are many different object-oriented programming languages, the
most widely used ones are class-based, which means that objects are instances of classes which also
define their types.
Advantages
• OOP allows easy management because to modularity and encapsulation.
• OOP mimics the real world, which makes it simpler to comprehend.
• Objects can be reused in other programmes since they are complete in and of themselves.
Disadvantages
• Programs that are object-oriented are frequently slower and consume a lot of memory.
• Over-generalization.
• It could take more time to develop programmes utilising this approach.
The most popular programming languages fall under the two main paradigms OOP and POP.
Although POP is a conventional programming method, OOP is a step ahead of it and it overcomes
the limitations that POP poses.
driven, register based, electronic device which reads instruction from a storage device, takes the data
from input unit and process the data as per the instructions and provides the result to the output unit.
• Programmable - perform various set operation on the given data depending on the sequence
of instructions supplied by the programmer.
• Clock Driven – whole task is divided into basic operations, are divided into precise system
clock periods.
• Register Based – storage element
• Electronic Device – fabricated on a chip
Microcomputers are any microprocessor-based systems with a restricted amount of
resources. The microprocessor is a component found in practically all modern electronics, including
smartphones, printers, washing machines, etc. Its basic job is to receive input and provide the
appropriate output. While this may seem like a simple task, modern processors can handle trillions
of calculations per second. It performs Arithmetic Logical Unit (ALU) operations and communicates
with the other devices connected with it. It is a single Integrated Circuit in which several functions are
combined. The concept of store-program is the foundation of almost all microprocessors. Programs
or instructions are sequentially stored in the memory locations where they will be executed in the
store-program concept. A microprocessor must be programmed by the user in order to perform any
task. Therefore, the programmer must be familiar with the system's internal resources, features, and
supported instructions. The manufacturer of the microprocessors provides a list of the instructions for
each microprocessor. A microprocessor's instruction set comes in two different formats: mnemonics
and binary machine code. Microprocessor while executing the instruction performs three basic
things:
• It performs operations like addition, subtraction, multiplication, division, and some logical
operations using its ALU. New Microprocessors also perform operations on floating-point
numbers also.
• Data in microprocessors can move from one location to another.
• It has a Program Counter (PC) register that stores the address of the next instruction based on
the value of the PC, Microprocessor jumps from one location to another and takes decisions.
• Games machine
• Complex industrial controllers
• Traffic light
• Control data
• Military applications
• Defense systems
• Computation systems
A microcontroller is a chip optimized to control various electronic devices. It is stored in a
single integrated circuit which is dedicated to performing a specific task and execute one specific
application. Devices that require some user input typically have microcontrollers. It is specially
designed circuits for embedded applications and is widely used in automatically controlled electronic
devices. It contains memory, processor, and programmable I/O. An electronic device belonging to the
microcomputer family, are fabricated using VLSI technology on a single chip. They are created and
implemented to carry out a particular task, such showing characters or integers on an LCD display
module of a home appliance. Microcontrollers have numerous uses. Simply said, a microcontroller
chip is found within any device or piece of equipment that performs tasks including measuring,
regulating, displaying, and computing information. They can be found in practically all modern toys,
office equipment, traffic lights, home appliances, and several other everyday gadgets.
Important features of Microcontroller:
• Processor reset
• Program and Variable Memory I/O pins
• Device clocking central processor
• Instruction cycle timers
Microcontrollers are mainly used in devices like:
• Mobile phones
• Auto-mobiles
• CD/DVD/Mp3 players
• Washing machines
• Cameras
• Security alarms
• Keyboard controllers
• Microwave oven
• Watches
The difference between Microprocessor and Microcontroller is given in the table below:
Microprocessor Microcontroller
Only a processor, so memory and I/O components Has a processor along with internal memory and
need to be connected externally I/O components.
Memory and I/O has to be connected externally, so Memory and I/O are already present, and the
the circuit becomes large. internal circuit is small.
The overall power consumption is considerable as Total power consumption is lower because there
a result of the external components. For devices are fewer external components. Therefore it can
using batteries or other forms of stored energy, it is be utilised with electronics that utilise batteries or
therefore not suitable. other forms of stored energy.
Microprocessor has a smaller number of registers, so Microcontroller has more register. Hence the
more operations are memory-based. programs are easier to write.
No RAM, ROM, Input-Output units, timers, and other Has a CPU along with RAM, ROM, and other
peripherals on the chip. peripherals embedded on a single chip.
Complex and expensive, with a large number of Simple and inexpensive with less number of
instructions to process. instructions to process.
Operation Cycle
The instructions given for the execution defines the operation cycle. This is the thorough
methodology computer processors use for executing any given instruction. The various steps
performed by any computer processor for each machine language instruction given or received. The
machine cycle is a four-process cycle that includes reading and interpreting the machine language,
executing obtained code, and then storing the result. The process of cycling instructions may also be
known as the Machine cycle, E-cycle (execution cycle), I-cycle (instruction cycle), fetch-decode-
execute cycle, or fetch-execute cycle. It can be show diagrammatically as given in Figure.1.5.
References
1. https://www.nielit.gov.in/gorakhpur/sites/default/files/Gorakhpur/OLevel_2_B4_CLang_26Mar_
SS.pdf
2. https://www.pvpsiddhartha.ac.in/dep_it/lecture%20notes/MP/unit1.pdf
3. https://vardhaman.org/wp-content/uploads/2021/03/CP.pdf
4. http://markburgess.org/CTutorial/C-Tut-4.02.pdf
Module II
Introduction to C Programming
The act of writing instructions to a device, such as a computer or mobile device, is referred to
as programming also known as coding. Programmers (developers) utilise a programming language,
which is a computer language, to communicate with computers. It is a series of instructions designed
to carry out a certain task and written in any particular language (C, C++, Java, Python, PHP, Perl). The
primary function of programming languages is to enable developers to create instructions/ commands
for transfer to devices.
The process of designing and developing various sets of computer programmes in order to
accomplish a certain computing outcome is known as Computer Programming. The process includes
a number of tasks, including analysis, coding, algorithm design, accuracy checking, and resource
utilization analysis. To address a given problem on a computer, a set of instructions must be found using
computer programming. Computer Programming is very easy if it is properly managed. Choosing the
best programming language is a difficult process because there are numerous programming languages
for computers.
C is a procedural oriented and structured programming language. A structured programming
language is a subset of the procedural language. Structure means to break a program into various
parts or blocks so that it may be easy to understand. The development of the Unix Operating System
and the history of the C programming language are inseparably connected. Dennis Ritchie created it
for the first time in 1972. It was primarily created as an operating system programming language. It
inherits many features of previous languages such as B and Basic Combined Programming Language
(BCPL). Advantages of using C programming language:
• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
Features/Characteristics of C
• Simple - is simple as it provides a structured programming approach. Also rich in data types,
library functions etc.
• Portable - programs written in C programming anguage can be executed on different machines
with some machine specific changes. Hence, this language is a machine independent language.
• Mid-level programming language - is employed to create system applications like kernels and
drivers, etc. Additionally, it supports the attributes of a high-level language. Because of this,
it is referred to as a mid-level language.
• Structured programming language - can break the program into parts using functions. Hence,
it is easy to understand and modify. Functions also provide code reusability.
• Rich Library - provides a lot of inbuilt functions that make the development fast.
• Memory Management - supports the feature of dynamic memory allocation. One can free the
allocated memory at any time by calling the free() function.
• Speed - compilation and execution time is fast since there are lesser inbuilt functions and
hence the lesser overhead.
• Pointer - C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.
• Recursion - a function can be called within the function thereby provides code reusability for
each function. Recursion enables us to use the approach of backtracking.
• Extensible - is extensible because it can easily adopt new features.
Applications of C languages
• Widely used in embedded systems, IOT applications and developing desktop applications.
• Used for developing system applications.
• Most of the applications by Adobe are developed using ‘C’ programming language.
• Used for developing browsers and their extensions. Example : Google’s Chromium.
• Used to develop databases. Example L MySQL .
• Used in developing an operating system. Operating systems such as Apple’s OS X, Microsoft’s
Windows, and Symbian are developed using ‘C’ language.
• Used for developing desktop as well as mobile phone’s operating system.
• It is used for compiler production.
Structure of C programs
There is a clear structure for almost everything in the world. As an example, each and every
human has a distinct structure, which includes head, neck, and four limbs etc. Similar to this, every
programming language has a distinct structure. When writing the code, one must adhere to these
structures. A C program's basic structure is broken down into 6 sections, making it simple to read,
edit, document, and comprehend in a certain style. To effectively compile and run, a C programme
must adhere to these. In a C programme that is well-structured, debugging is simpler. Various sections
is depicted in Figure. 2.1
32 Principles of Programming and Web Technologies
kn Unäv
Definition - The #define preprocessor is used to create a constant throughout the program. Whenever
this name is encountered by the compiler, it replaces all the constants with its value in the code.
Example:
#define val=20
Global Declaration - includes global variables, function declaration, and static variables. Variables
and functions which are declared in this scope can be used anywhere in the program. Example:
int num = 18;
You can also declare if needed user defined functions in the this section.
main() Function - There must be a main function in every C program. This section contains the
program's main() function. Declarative and executable operations are carried out inside the curly
braces of the main program. The main() function's return type has two additional options: int and
void. The program's primary function, void(), instructs the compiler that it will not return any values.
int main() specifies to the compiler that an integer value will be returned by the program.
Example:
void main() / int main()
Subprograms - In this section, user-defined functions are called. Both built-in functions and function
definitions specified in the Global Declaration section may be included there. Each time a function is
called from the main or from somewhere else outside the main() function, control of the programme
is transferred to the called function. According to the programmer's specifications, they are specified.
Example:
int product(int x, int y)
{
return x*y;
}
The structure of a C program can be seen as follows:
Header #include<studio.h> This command includes standard input out-
put header file(stdio.h) from the C library
before compiling a C program
Main function int main() It is the main function from where C pro-
gram execution begins.
{ Indicates the beginning of the main func-
tion.
Comments /*_some_comments_*/ Whatever written inside this command “/*
*/” inside a C program, it will not be con-
sidered for compilation and execution.
Variable Declaration int a=1;
Compilation process in C
The several steps that make up C compilation and execution process is given in Figure 2.2 :
• Assembly - An assembler is used to translate assembly code into object code. The name of the
source file and the object file created by the assembler are identical. The object file's DOS and
UNIX extensions are ".obj" and "o," respectively. Sample.obj would be the name of the object
file if the source file's name was "Sample.c."
• Linking - Almost all C programs make use of library functions. These library functions are
pre-compiled, and the.lib (or.a) extension denotes the location of the library files' object code.
The linker's primary function is to merge the object code of library files with the object code
of written program. There can be situation when the program refers to the functions defined
in other files; in that case linker plays a very important role. It connects the program's object
code with these files. Hence, it can be concluded that the linker's responsibility is to link the
object code of developed application with the object code of the library files and other files.
The executable file is the linker's output. The only thing separating the executable file's name
from the source file's is its extension. .exe is the executable file extension in DOS, whereas
a.out is a valid executable file name in UNIX.
The Figure 2.3 shows the execution of a ‘C’ program
can access. An identifier used to store a value is called a variable. Each variable in C has a unique
type that specifies its memory size and layout, the range of values that can be placed inside, and the
range of operations that can be performed on the variable. Because C is case-sensitive, uppercase and
lowercase letters are separate. At the time of execution, constants can never change. Variables have
the ability to alter while a program is running and update the value kept there. In a program, a single
variable may appear in several different places. A variable name ought to have some significance and
represent the purpose of the variable. A variable must be declared first before it is used somewhere
inside the program. A variable name is formed using characters, digits and an underscore.
A variable is declared in the form:
datatype variable_name; for single variable
datatype variable1_name, variable2_name, variable3_name; for multiple variables
Rules that must be followed while creating a variable:
• should consist of only characters, digits and an underscore.
• should not begin with a number.
• should not consist of white space.
• should not keyword.
• variable name are case sensitive language.
Local variables are variables that are defined and used just within the function or block. Its
scope is restricted to a function or a block. It is only used inside the block. Before use, local variables
must be initialised. A global variable is one that is declared outside of the function or block. When
the programme begins, it is declared. It can be used for all functions. A static variable is one that
keeps its value when called by different functions. The keyword "static" is used to declare it. In C,
by default, any variables that are declared inside a block are automatic variables. The auto keyword
can be used to explicitly declare an automatic variable. Local variables and automatic variables are
similar. External variables can be shared between numerous C files and these are declared using
extern keyword.
Various data types are present which makes the programmer easy to select a suitable data type
as per the requirements of an application. Following are the three data types:
• Primary datatype declaration is used to declare a variable with primitive data types, which are
also called as built-in data types.
• Derived datatypes are array, functions, pointers, structures.
• User-defined datatypes are the types that are defined by the user. The most commonly used
data types are struct, Union, enum, typedef etc.
The primitive or primary data types found in C programming language are following:
• Integer – are used for storing various whole numbers, such as 5, 8, 67, 2390, etc. “int” keyword
is used to declare and data type can be 4 bytes or 2 bytes.
• Character – refers to all ASCII character sets as well as the single alphabets, such as ‘x’, ‘Y’,
etc. Defined by the keyword “char” takes is 1 byte.
• Double – include all large types of numeric values that do not come under either floating-
point data type or integer data type. It is defined by “double” with 8 bytes and capable of
storing values that are comparatively double the size of the bytes that the float can store.
• Floating-point – points to all the real number values or decimal points, such as 40.1, 820.673,
5.9, etc. The size of the float data type is basically 32 bits or 4 bytes and is declared using
“float” keyword.
• Void – refers to no values at all, mostly used when defining the functions in a program. It takes
0 bytes and declared using “void” keyword.
C language help in making the primary data types much more specific using the modifiers.
‘short’, ‘long’, ‘unsigned’, ‘signed’ are some of the modifiers used in programming. Each data type
has a different set of format specifiers. These are used to receive inputs and print out a type's output.
Every format specifier uses the symbol %. The type of data that must be provided as input and the type
of data that must be displayed on the screen are both specified by format specifiers to the compiler.
Following table lists the specifiers used by C language.
Table 2.1 : C Specifiers
It is used when data type is of type signed int which stores an integer
%d or %i Signed Integer
value like 1,-1,2.
It is used when data type is of type unsigned int which stores unsigned
%u Unsigned Integer
integer value
It is used when data type is of type float which stores decimal floating
%f Floating Point
point values like 2.5, 3.4
It is used when data type is of type String which stores a string like
%s String
"HelloWorld".
It is used when data type is of type Char which stores a single character
%c Character
like 'a','b'.
%p Address Printing It is used only while printing the address of some variable or pointer
It is used when data type is of long int which stores a long integer value
%ld Long Integer
from range [−2,147,483,647, +2,147,483,647].
It is used when data type is of type long long int which stores a long
%lld Long Integer
long integer value of up to 64 bits.
It is used when data type is of type double which stores high-precision
%lf Double floating
floating-point data.
In programming, keywords are preset words that have unique meanings to the compiler. These
C library reserved words are utilised to carry out an internal operation. These keywords' functions and
meanings are already known to the compiler. Because they are a part of the syntax, keywords cannot
be used as identifiers. Following table lists the keywords used in C.
Constants are fixed values that cannot be changed by the programme while it is running.
Literals are another name for these fixed values. Any of the fundamental data types, such as an integer
constant, a floating-point constant, a character constant, or a string literal, can be used as constants.
Enumeration constants are also present. The only difference between constants and normal variables
is that after their definition, their values cannot be changed. There are two simple ways in C to define
constants −
• Using #define preprocessor.
• Using const keyword.
The constants are categorized into two basic types as given below
Primary Constants Secondary Constants
Numeric Constants
• Integer Constants • Array
• Real Constants • Pointer
Character Constants • Structure
• Single Character Constants • Union
• String Constants • Enum
• Backslash Character Constants
Integer constant refers to a sequence of digits while the real constant refers to numbers having
the fractional part. Single character constants simply contains a single character enclosed within
single quotes while the string constants are a sequence of characters enclosed in double quotes. Some
character constants that have a backslash before them are supported in C. The backslash characters
have a specific meaning known to the compiler. Also known as Escape Sequences. List of escape
sequences is given below.
Table 2.3 : Escape Sequence in C
Sl.No Escape Sequence Meaning
1 \t Inserts a tab in the text at this point.
2 \b Inserts a backspace in the text at this point.
3 \n Inserts a newline in the text at this point.
4 \r Inserts a carriage return in the text at this point.
5 \f Inserts a form feed in the text at this point.
C Input/Output
Offering the programme some data to use as input is referred to as input, and providing the
programme some data to use as output is referred to as output. To read any given input and display
output on the console, the C programming language offers standard library functions.
The two streams we use when dealing with input-output operations in C are:
Standard Input (stdin)
Standard Output (stdout)
Standard output, also known as stdout, is used to deliver output. Standard input, also known
as stdin, is used to receive input. The stdio.h header file contains the functions needed for standard
input and output. Because of this, in order to use those functions, we must include the stdio.h header
file in our programme, as demonstrated below.
#include <stdio.h>
We have a number of built-in functions in the C language that we may use to perform input/output
operations. The functions used for standard input and output are listed below:
printf() function – shows output
scanf() function - takes input
getchar() and putchar() function
gets() and puts() function
Using the printf() function, let's print a simple sentence.
#include <stdio.h>
void main() {
printf("Hello World");
}
The above program prints “Hello World” as output.
Now we shall just look how format specifiers are used with print() qith a sample program.
#include <stdio.h>
int main() {
int x = 10;
char ans = 'T';
float pi = 3.14;
double num = 22.7867898;
printf("Value of x is: %d", x);
printf("\nYour answer is: %c", ans);
printf("\nValue of num1 is: %f \n", pi);
printf("Value of num2 is: %lf", num);
return 0;
}
Output of the above program will be as follows:
// Value of x is: 10
// Your answer is: T
// Value of num1 is: 3.140000
// Value of num2 is: 22.786790
The format specifiers like %d, %c etc are used to specify the type of the value that will be
added there.
Using scanf(), now we shall look how to accept input from user
#include <stdio.h>
int main() {
int x;
char ans;
float pi;
printf("Please enter your answer (T or F): ");
scanf("%c", &ans);
printf("Your answer is: %c \n", ans);
printf("Please enter any number of your choice : ");
scanf("%d", &x);
printf("Value of x is: %d \n", x);
printf("Please enter value of pi :");
scanf("%f", &pi);
printf("\nValue of pi is: %f \n", pi);
return 0;
Principles of Programming and Web Technologies 41
kn Unäv
}
The output of the above program is as follows:
// Please enter your answer (T or F): T
// Your answer is: T
// Please enter any number of your choice : 5
// Value of x is: 5
// Please enter value of pi :3.14
// Value of pi is: 3.140000
getchar() functions returns a character from stdin stream(keyboard) and putchar() functions
writes a character to stdout stream(screen). Example program to demonstrate the getchar and putchar
functions.
#include<stdio.h>
int main(){
char c;
printf("Enter a character : ");
c = getchar();
printf("You Entered : ");
putchar(c);
return(0);
}
The output of the above program is as follows:
// Enter a character : j
// You Entered : j
Similar to the getchar function is the getch() function. The getch() function is used to read
a character from the keyboard and return it to the program. One character may be read using this
function. We must either write several times or use a looping statement to read multiple characters.
gets() reads a line from stdin(keyboard) and stores it into given character array while puts()
writes a string to stdout(screen) stream excluding null terminating character. Example program to
demonstrate the gets and puts functions.
#include <stdio.h>
int main(){
char string[50];
printf("Enter your name : ");
gets(string);
Relational Operators - Comparison operators are used to compare two values i.e. the relationship
between two operands is verified by a relational or comparison operator. It returns 1 if the relation is
true and 0 if the relation is false. Practically speaking, relational operators are used in programs to
define conditions. The following Table 2.5 shows relational operators supported by C and suppose
that variable A contains 15 and variable B contains 10.
Table 2.5 : Relational Operators
Logical Operators - Depending on whether the outcome of the expression is true or false, an expression
with logical operators yields either 0 or 1. In C programming, logical operators are frequently
employed in the decision-making process.
Table 2.6 : Logical Operators
Operator Name Description Example
Let A=15, B=25 then
Returns TRUE if all given conditions are
&& Logical AND expression (A && B) is
TRUE otherwise returns FALSE
FALSE
Let A=15, B=25 then
Returns true if any one of the given state-
|| Logical OR (expression (A || B) is
ments is true
TRUE
Multiplies and gives the product among
The logical state of its operand is reversed
If c = 15 then, expres-
! Logical NOT using it. When the logical NOT operator is
sion !(c==15) equals to 0.
used, it will make a condition false if it is
true.
Assignment Operators - A variable can be given a value by using the assignment operator. These are
used to give the left-side variable a right-side value. Along with arithmetic operators, the assignment
operator is used in several variants. The assignment operators in the C programming language are all
listed in the Table 2.7 that follows.
Table 2.7 : Assignment Operators
Bitwise Operators - Mathematical operations like addition, subtraction, multiplication, division, etc.
are transformed to bit-level computations during computation to speed up processing and saving
power. Bit-level operations are carried out using bitwise operators. Lets look into the truth table for
AND, OR and XOR.
Table 2.8 : Truth Table
A B A&B A|B A^B
1 1 1 1 0
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
The operations are carried out based on the binary values when the bitwise operators are used.
Table 2.9 : Bitwise Operators
Operator Name Description Example
This operator copies the bits to the result if and
& Binary AND A&B
only if they exist in both of operands.
This operator copies the bits if and only if they
| Binary OR A|B
exist in either of the two operands.
When using this operator, the bits should only be
^ Binary XOR A^B
set in one of the operands and not both of them.
Binary 1’s com- This is a unary operator. Additionally, it has the
~ ~A
plement effect of "flipping" the bits that are available.
Now that you are aware of C Operators, we shall move forward with C Expressions. Any
computation, condition, etc. can be performed in any programming language by using a set of
symbols. These symbols combine to form a statement. In C, an expression is made up of a number
of operators and operands that together compute a single value that is then saved in a variable. The
action or operation to be carried out is indicated by the operator. The entities to which we apply the
operation are known as operands. For example, in an expression, C = A + B, then ‘C’ is a variable, ‘A’
and ‘B’ are operands , ‘+’ is operator.
The expressions are divided into three types as follows.
• Infix Expression - those in which the operator is placed between the operands.
Example: A+B
• Postfix Expression - those in which the operator is placed after the operands.
Example: AB+
• Prefix Expression - those in which the operator is placed before the operands.
Example: +AB
1. Operator Precedence and Associativity
The order in which operators are evaluated in an expression is determined by their operator
precedence. Every operator in the c programming language has precedence that means the priority.
The operator with the highest precedence is evaluated first and the operator with the lowest precedence
is evaluated last when there are multiple operators in an expression. The order in which operators
with equal precedence are evaluated in an expression is determined by operator associativity. When
an expression in the c programming language has multiple operators with equal precedence, we use
associativity to determine the order in which those operators are evaluated. The following table
shows the operator precedence and associativity.
Table 2.12: Operator Precedence & Associativity
Precedence Operator type Associativity Category
1 () [] -> . ++ – – Left to right Function call, array reference,
structure member access
2 – + ! ~ – – ++ (type)* & sizeof Right to left Unary operator
3 /*% Left to right Multiplication, division, modulo
4 +- Left to right Addition, subtraction
5 >> << Left to right Shift operator
6 < > >= <= Left to right Relational operator
7 != == Left to right Equality operator
8 & Left to right Bitwise AND operator
9 ^ Left to right Bitwise XOR operator
10 | Left to right Bitwise OR operator
11 && Left to right Logical AND operator
12 || Left to right Logical OR operator
13 ?: Left to right Conditional operator
14 = -= += /= *= %=>>= &= <<= Right to left Assignment operator
|= ^=
15 , Left to right Comma operator
Conditional Statements
Decisions making involves selecting the sequence in which statements should be executed
based on specific criteria or repeating a collection of statements until the criteria are met. Programmers
must specify one or more conditions to be tested or evaluated by the programme, along with a statement
or statements to be executed if the condition is true, and optionally, further statements to be executed
if the condition is false.
C handles decision-making by supporting the following statements : if statement, switch
statement, conditional operator statement (? : operator).
Decision making with if statement
According to the complexity of the circumstances to be tested, the if statement may be implemented
in many ways. The various forms consists of,
• Simple if statement
• if....else statement
• Nested if....else statement
• Using else if statement
Simple if statement
This is used to check the given condition and executes the block of statements based on the
condition specified. The if statement evaluates specified condition. If it is found TRUE, executes the
next statement or block of statements. If the condition is FALSE, it skips the execution of the next
statement or block of statements. Syntax is as follows:
if(test expression)
{
statement inside; // block of code to be executed if the condition is true
}
statement outside;
Example: Program to demonstrate simple if condition:
50 Principles of Programming and Web Technologies
kn Unäv
# Program to check whether user entered number is greater than the given number
#include <stdio.h>
void main( )
{
int x, y;
printf("Enter any integer number: ") ;
scanf("%d", &x) ;
y = 13;
if (x > y )
printf("x is greater than y");
}
The output will be obtained as follows:
// Enter any integer number: 31
// x is greater than y
if....else statement
The if-else statement examines the given condition and only executes one of the two blocks of
statements depending on the result of the condition. The if-else clause analyses the given condition.
It runs a block of statements if it returns TRUE (True block). Another block of sentences is carried
out if the condition is FALSE (False block). Syntax is as follows:
if(test expression)
{ statement block1;
}
else
{
statement block2;
}
If the test expression is true, the statement-block1 is executed, else statement-block1 is skipped
and statement-block2 is executed.
# Program to check whether user entered year is leap year
#include <stdio.h>
void main()
{
int year;
printf("Enter a year to check :");
scanf("%d", &year);
Principles of Programming and Web Technologies 51
kn Unäv
{
printf("Given number is below 500\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 500") ;
}
The output of the above program will be obtained as follows as per the users entry
// Enter any integer number: 233
// Given number is below 500
// And it is ODD
case 4: printf("Thursday");
break;
case 5: printf("Friday");
break;
case 6: printf("Saturday");
break;
case 7: printf("Sunday");
break;
default: printf("not a day for given number") ;
}
}
The output will be obtained as follows
# Enter any digit of the week : 5
# Friday
Control Statements
We may occasionally need to repeatedly run a specific code statement while developing. The
code statement can be written to execute as many times as necessary, but that would be incredibly
inefficient since what if you want the code statement to execute 100 times? We employ loops because
of this. Control in C programmes has always been passed from one instruction to the next. Sequential
control flow refers to this control flow from one command to the next. The following types of loops
are available in C:
• while loop
• for loop
• do while loop
According to the given diagram, the loop is executed if the Test Condition is true, and if it
is false, the execution exits the loop. When the loop is successfully completed, the execution cycle
repeats, starting at the Loop entry and checking the Test condition once more. The body of the loop
is not executed when the condition check returns false, and execution exits the loop. Entry-controlled
loops and Exit controlled loops are two categories of loops. In former, before executing the loop's
body the condition is checked. So, when the condition is never true, it won't execute even once. For
example, for and while loop. Whereas, in the case of latter, the condition is checked after the loop's
body is executed, i.e., in the end. Hence, even if the condition is not fulfilled, this loop will execute
atleast one time. Example, do-while loop.
while(condition)
{
//statements inside the loop
}
Since ‘while’ is a keyword, it can only be written in lower case. If a variable is present in the condition,
it must first be given a value before it can be used. The condition variable's value must be changed in
accordance with the while block's requirements. The condition in a while statement could be either an
explicit integer value, a variable, or another condition. Example program to demonstrate the working
of while loop.
// Program to display even numbers upto 20.
#include<stdio.h>
void main(){
int n = 0;
printf("Even numbers upto 20\n");
while( n <= 20 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}
}
The output of the given program is obtained as follows:
// Even numbers upto 20
// 0 2 4 6 8 10 12 14 16 18 20
is carried out repeatedly until the condition is determined to be FALSE. If the condition is determined
to be FALSE, the for block's execution control is terminated. Example program to understand the
working of for loop.
// Program to display even numbers up-to 20.
#include<stdio.h>
void main(){
int n = 0;
printf("Using For Loop ");
printf("Even numbers upto 20\n");
for( n = 0 ; n <= 20 ; n++ )
{
if( n%2 == 0)
printf("%d\t", n) ;
}
}
The output of the given program is obtained as follows:
// Using For Loop Even numbers upto 20
// 0 2 4 6 8 10 12 14 16 18 20
In the C programming language, we can also have nested for loops, or one for loop inside
another for loop. Syntax is as follows:
for(initialization; condition; increment/decrement) // outer loop
{
for(initialization; condition; increment/decrement) // inner loop
{
statement ;
}
}
The "inner loop" will be executed one time for each iteration of the "outer loop". Example
given shows how to work with nested for loops.
#include<stdio.h>
void main( )
{
int i, j;
// Outer loop
for (i = 1; i <= 2; ++i) {
if(i % 5 == 0)
break;
printf("%s\n", name);
}
}
In the above code, once we find a value of ‘i’ which is divisible by 5, the loop breaks and
control is shifted out of the loop. The output is given below:
// Enter the number of times you want to execute the for loop:45
// Enter your name:kannan
// The loop begins
// kannan
// kannan
// kannan
// kannan
In order to continue executing the loop, the ‘continue’ statement forces the control to move
immediately to the test-condition. When the continue statement is encountered, the loop's current
cycle is terminated and the next cycle is begun. Example to show the usage of continue statement:
// Program to demonstrate usage of break in control statements
#include <stdio.h>
int main()
{
int n;
printf("Enter the number of times you want to print your name:");
scanf("%d", &n);
char name[25];
printf("\nEnter your name:");
scanf("%s", name);
printf(" Loop begins --- \n");
for(int i = 1; i <= n; i++) {
if(i % 2 == 0)
continue;
printf("%d : %s\n",i,name);
}
return 0;
}
The only instance where using goto is advantageous is when we need to break many loops
simultaneously with a single statement. Consider the example below.
#include <stdio.h>
int main()
{
int count = 0;
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
for(int k=0;k<10;k++){
count++;
printf("%d ",count);
if(count==5)
{ // goto statement
goto end;
}
}
}
}
end : printf("Complete");
return 0;
}
The output is given below:
// 1 2 3 4 5 Complete
Three loops are active in the code; to exit all three of them simultaneously, we would need to
add three break statements, one for each loop. However, in this code, since the label has been defined
after the three nested loops, we may use a single goto line to exit all three of the nested loops.
References
Module III
C Programming: Arrays and Functions
Introduction to Arrays
Arrays are referred to as structured data types in the C programming language. An array is
described as a finite, ordered collection of uniform data kept in a single block of memory. At this
context, the words, finite means range of the data must be defined, ordered implies that the data must
be stored in continuous memory addresses/location and homogenous indicates data must be of similar
type. Instead of creating distinct variables for each item, arrays are used to store numerous values in
a single variable. A linear data structure, an array stores its elements continuously in memory. This
makes it simpler to access the components. Indexing for array items begins at 0 and goes up to n-1,
where n is the array's size. By using arrays, we can simplify our work by defining an array of size 100
rather than defining 100 variables. To create an array, define the required data type and specify the
name of the array followed by square brackets []. General syntax to create an array is :
datatype arrayName [ size ] ;
Example of array declaration
char sample[15]; /* char data type array declaration*/
float sample[10]; /* float data type array declaration*/
int sample[10]; /* int data type array declaration*/
To access an array element, refer to its index number. The index of an array starts from 0 to
size-1. The first element of any array will be stored at the address arr[0] and the last element will be
at arr[size – 1].
Array Size = 7
0 1 2 3 4 5 6
Indices
Arrays can have one dimension or multi-dimensions. The number of indexes is the same
as the number of dimensions in an array. A 2-D array, commonly known as a matrix, contains two
indexes: one for each row and one for each column.
We shall now see how to initialize an array. The initialization can be done either one by one
or using a single statement. Example:
int marks[5] = {89, 78, 93, 86, 84} (1)
int marks[] = {89, 78, 93, 86, 84} (2)
The number of values between braces cannot be greater than the number of members we
declare for the array between square brackets []. We can initialize an arry either by specifying the size
as (1) or as in (2). In the first case, we have specified the size of the array while in the (2) , we have
directly assigned the values to array and the size will depend on the number of elements we have
passed.
We can change the values assigned to the array as follows
// make the value of the third element to -1
mark[2] =95;
// make the value of the fifth element to 0
mark[4] = 88;
Let’s look how to declare, assign, and access arrays with an example:
// Program to find sum and average of array elements
#include <stdio.h>
void main() {
int num[10], i, n, sum = 0;
double average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i < n; ++i) {
printf("Enter number %d : ",i+1);
scanf("%d", &num[i]);
// adding integers entered by the user to the sum variable
sum += num[i];
}
// converting sum to double then calculate average
average = (double) sum / n;
printf("Sum = %d\n", sum);
printf("Average = %.2lf", average);
}
The program illustrated here shows how to declare a single dimensional array. It also
demonstrates how to accept values from user. The output obtained is as follows:
// Enter number of elements: 3
// Enter number 1 : 45
// Enter number 2 : 67
// Enter number 3 : 34
// Sum = 146
// Average = 48.67
Multidimensional arrays are also supported by the C language. An array of arrays is usually
called as multi dimensional array. It can be of two dimensional array or three dimensional array or
four dimensional array or more. The two-dimensional array is the most basic type. Data in the form
of tables is stored in 2-D arrays. Additionally, 2-D arrays are used to build mathematical matrices.
Both a row index and a column index are present in this. The index for the row and column both starts
at 0. We can initialise two-dimensional arrays at runtime or during compilation, just like we do with
a single-dimensional array. The declaration of a two-dimensional array is as follows:
datatype arrayName [ rowSize ] [ columnSize ] ;
For declaring and initialising a two-dimensional array with a given number of rows and columns with
initial values, we use the general syntax shown below.
datatype arrayName [rows][colmns] = {{r1c1, r1c2, ...},{r2c1, r2c2,...}...} ;
Example: int A[3.4];
has three rows and 4 columns
Column 1 Column 2 Column 3 Column 4
Row 1 A[0][0] A[0][1] A[0][2] A[0][3]
Row 2 A[1][0] A[1][1] A[1][2] A[1][3]
Row 3 A[2][0] A[2][1] A[2][2] A[2][3]
}
printf("\n");
}
}
The output of the above program is as follows:
// a[r0][c0] = 1 a[r0][c1] = 2
// a[r1][c0] = 2 a[r1][c1] = 4
// a[r2][c0] = 3 a[r2][c1] = 6
Now we shall look how to accept values from user and find the sum
// Program to find the sum of mxn matrix
#include<stdio.h>
int main()
{
int i,j,m,n;
int a[5][5], b[5][5], sum[5][5];
printf("Enter row and column size:\n");
scanf("%d%d", &m, &n);
/* Accepting values from user for 1st matrix*/
printf("Enter elements of first matrix:\n");
for(i=0;i< m;i++)
{
for(j=0;j< n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%d", &a[i][j]);
}
}
/* Accepting values from user for 2nd matrix*/
printf("Enter elements of second matrix:\n");
for(i=0;i< m;i++)
{
for(j=0;j< n;j++)
Principles of Programming and Web Technologies 67
kn Unäv
{
printf("b[%d][%d]=",i,j);
scanf("%d", &b[i][j]);
}
}
/* Performing addition*/
for(i=0;i< m;i++)
{
for(j=0;j< n;j++)
{
sum[i][j] = a[i][j]+b[i][j];
}
}
/* Displaying the sum in matrix format*/
printf("Added matrix is:\n");
for(i=0;i< m;i++){
for(j=0;j< n;j++)
{
printf("%d\t", sum[i][j]);
}
printf("\n");
}
return 0;
}
Output obtained is as follows:
// Added matrix is:
// 12 4 6 8
// 7 9 6 8
// 7 9 11 13
Introduction to Functions
In order to make the writing of a programme to handle a larger problem easier, the larger
problem is broken down into smaller sub-problems and is tackled separately. This idea is implemented
in C by means of functions. In other words, a block of code called a function carries out a certain task.
Functions are used to break up larger programmes into smaller subprograms so that they are simpler
to comprehend and use. It is possible in many circumstances to write the same line of code more
than once in a programme. This could result in erroneous code repetition, problems, and even boring
the programmer. Therefore, the C language offers a method that enables you to declare and define a
collection of statements once in the form of a function that can then be called and used as needed. C
functions can be classified into two categories,
1. Pre-defined functions
2. User-defined functions
The functions that are already specified in the C library are known as library or pre-defined
functions; for instance, printf(), scanf(), strcat(), etc. To use these functions, you only need to include
the required header files. In C libraries, these have already been declared and defined. On the other
hand, user-defined functions are those that the user defines when a programme is being written.
These functions are designed to reduce time and space usage and encourage code reuse.
Benefits of Using Functions
• It gives your program's architecture modularity.
• It allows you to reuse your code.
• To use a function, all you need to do is call it by name wherever it is needed.
• Use of functions makes debugging and modification of huge applications with thousands of
lines of code easier.
• It improves the program's readability and comprehension.
Every function in C has the following...
• Function Declaration
• Function Definition
• Function Call
The function declaration provides information to the compiler about the function name,
parameters, and the data type of the return value. A function prototype is another name for the function
declaration. The function declaration is carried out either before the main function or inside the main
function or any other function. Syntax for declaring function:
returnType function_name(parameter_list)
The data type of the value sent as a return value from the function definition is specified by
returnType. The function_name is a user-defined name that the programme uses to identify the function
specifically. The data values given to the function definition are in the parameter_list/ arguments.
The actual code for that function is provided in the function definition. The body of the function
is another name for the function specification. The function definition includes the implementation of
the function's actual task. Accordingly, a function's definition contains the actual instructions that the
function will follow. Syntax for defining a function is as follows:
returnType function_name(parameter_list)
{
// body of the function
}
The function call instructs the compiler when to run the function declaration. When a function
call is executed, the execution control moves from the function call to the function definition, where
the actual code is executed. When the execution is finished, the control moves back to the original
function call. The function call is made within the function itself, the main function, or any other
function. Syntax for calling function is as follows:
functionName(parameters);
Lets write a simple user defined function to find the sum of two integers:
#include <stdio.h>
void main()
{
int num1,num2,sum;
printf("Enters two numbers: ");
scanf("%d %d", &num1,&num2);
sum = addNumbers(num1, num2); // function call
printf("sum = %d",sum);
}
int addNumbers(int a, int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
In the above example, int addNumbers(int a, int b); is the function declaration or prototype
which provides the information to the compiler such as the name of the function is addNumbers(),
return type of the function is int and two arguments of type int are passed to the function.
A function must define variables that accept the values of the arguments if it uses arguments.
An argument may or may not be accepted by a function. It might or might not give back any value.
The formal parameters of the function are what are known as these variables. Formal parameters are
created at function entry and destroyed at function exit, behaving similarly to other local variables
inside the function. These facts lead to the conclusion that function calls can be divided into four
different categories.
70 Principles of Programming and Web Technologies
kn Unäv
The empty parentheses in the function name checkPrimeNumber(); inside main() function
indicates that no argument is passed to the function. The return type of the function is void. Hence, no
value is returned from the function. So, in this function passes no arguments and has no return type.
Example for function without arguments and with return value
// Program to check a number is prime or not
#include <stdio.h>
int main() {
int n, i, flag = 0;
n = getInteger(); // no argument is passed
if (n == 0 || n == 1)
flag = 1;
for(i = 2; i <= n/2; ++i) {
if(n%i == 0){
flag = 1;
break;
}
}
if (flag == 1)
printf("The entered number %d is not a prime.", n);
else
printf("The entered number %d is a prime.", n);
return 0;
}
int getInteger() {
int n;
printf("Enter any positive number : ");
scanf("%d",&n);
return n; // returns integer entered by the user
}
The output obtained is as follows:
// Enter any positive number : 7
// The entered number 7 is a prime.
In the above program, n = getInteger(); statement indicates that no argument is passed to the
function. And, the value returned from the function is assigned to n.
Example for function with arguments and with the return value
// Program to check a number is prime or not
#include <stdio.h>
int checkPrime(int n);
int main() {
int n, flag;
printf("Enter any positive number : ");
scanf("%d",&n);
// n is passed to the function & the returned value is assigned to the flag variable
flag = checkPrime(n);
if(flag == 1)
printf("The entered number %d is not a prime",n);
else
printf("The entered number %d is a prime",n);
return 0;
}
int checkPrime(int n) {
if (n == 0 || n == 1)
return 1;
int i;
for(i=2; i <= n/2; ++i) {
if(n%i == 0)
return 1;
}
return 0;
}
The output obtained is as follows:
// Enter any positive number : 7
// The entered number 7 is a prime.
In the above program, the checkPrime() function determines whether or not the argument
passed in is a prime number. The function returns 0 if the provided input is a prime number. The
function returns 1 if the provided input is a non-prime number. The flag variable receives the return
value as its value. Depending on whether flag is 0 or 1, the main() method prints the appropriate
message.
74 Principles of Programming and Web Technologies
kn Unäv
Nesting of Functions
The C programming language also permits nesting, or calling one function from inside the
body of another. Syntax is:
function1()
{
// function1 body here
function2();
// function1 body here
}
If function2() also has a call for function1() inside it, then in that case, it will lead to an infinite
nesting. They will keep calling each other and the program will never terminate.
Recursive Functions
Recursion is a unique method of function nesting in which a function calls itself inside of it.
Recursion is the act of repeating things in a way that is self-similar. To exit the recursion, the function
must meet a number of criteria; else, it will repeat indefinitely. Syntax for defining a recursive function
is as follows:
function1()
{
function1();
}
We shall look deep into this using a program.
// Program to find sum of natural numbers using recursion
#include <stdio.h>
int sum(int n);
int main() {
int number, output;
printf("Enter the limit : ");
scanf("%d", &number);
Principles of Programming and Web Technologies 77
kn Unäv
output = sum(number);
printf("The sum of the n natural numbers is = %d", output);
return 0;
}
int sum(int n) {
if (n != 0)
return n + sum(n-1); // sum() function calls itself
else
return n;
}
The output obtained for the above program is as follows:
// Enter the limit : 7
// The sum of the n natural numbers is = 28
In the above program, sum() is initially invoked from the main() function with the argument
number. Assume that n in the sum() function starts off at 7. The sum() function receives the value
6 on the subsequent function call. Until n equals 0, this process keeps on. When n equals 0, the if
statement fails, and the else condition is then carried out, returning the sum of the numbers to the
main() function.
//Program to find out average of all the elements of the array using functions
#include <stdio.h>
float findAvg(int marks[]);
int main()
{
float avg;
int num[] = {80, 93, 89, 84, 94};
avg = findAvg(num);
printf("Average marks = %.1f", avg);
return 0;
}
float findAvg(int num[])
{
int i, sum = 0;
float avg;
for (i = 0; i <= 4; i++) {
78 Principles of Programming and Web Technologies
kn Unäv
sum += num[i];
}
printf("Total marks = %d \n",sum);
avg = (sum / 5);
return avg;
}
The outout obtained is as follows
// Total marks = 440
// Average marks = 88.0
Built-in functions make up the common functions. The standard functions in the C programming
language are defined in the .dll files and declared in header files. The pre-defined functions or library
functions are other names for the common functions. The standard functions are "the ready created
functions established by the system to make coding more easy," to put it simply. The Table 3.1 below
shows the header files with standard functions.
Table 3.1: List of Header Files
Strings in C
One way to describe a string is as a one-dimensional array of characters that is terminated by
a null ('\0'). Text, including words and sentences, can be edited using a character array or string. The
last character in the array must always be 0, and each character takes up one byte of memory. Since
there is no other way to tell where a string stops, the termination character ('\0') is important. When
a string is defined as char s[10], the memory initialization of character s[10] is implicitly set to null.
The String is a set of characters that are enclosed in double quotation marks and in C programming
language, it is a character array of single dimension.
0 1 2 3 4 5 6
Indices
String K a n n a n
Address
Now we shall look one more program with out using strung functions:
// Program to convert string in upper case and lower case.
#include<stdio.h>
int main()
{
char text[100];
int i;
printf("Enter any string: ");
gets(text);
printf("Entered string is: %s\n",text);
for(i=0;text[i]!='\0';i++)
{
if(text[i]>='a' && text[i]<='z')
text[i]=text[i]-0x20;
}
printf("String in Upper case : %s\n",text);
for(i=0;text[i]!='\0';i++){
if(text[i]>='A' && text[i]<='Z')
text[i]=text[i]+0x20;
}
printf("String in Lower case : %s\n",text);
return 0;
}
The output obtained is as follows:
// Enter any string: Hello.. Welcome ALL
// Entered string is: Hello.. Welcome ALL
// String in Upper case : HELLO.. WELCOME ALL
// String in Lower case : hello.. welcome all
In the above program, we will first receive a string as input, convert it to upper case, print
upper case string, then convert it to lower case & print the lower case. Logic behind this program's
implementation is as simple as checking the alphabets. If they are in upper case, add 32 [0x20 - hex
value] to make letter lower case; otherwise, make the character upper case by subtracting 32 [0x20 -
hex value]. Because ASCII difference between uppercase and lowercase characters is 32 .
We can pass strings to functions in the same manner we pass an array to a function since
strings are character arrays. Here's an example programme that does this:
#include <stdio.h>
void printStr(char str[])
{
printf("String is : %s", str);
}
int main()
{
char str[] = "Welcome to the world of Programming";
printStr(str);
return 0;
}
The output obtained is as follows:
// String is : Welcome to the world of Programming
String Functions
Although manual string manipulation is possible, this makes the programming large and
complex. In order to solve these issues, ‘C’ provides standard library functions to manipulate strings
in a program. String manipulators are stored in <string.h> header file. The Table given below lists
various string functions.
Table 3.2: String Functions
Function Syntax (or) Example Description
strcpy() strcpy(string1, string2) Copies string2 value into string1
strncpy() strncpy(string1, string2, 5) Copies first 5 characters string2 into string1
strlen() strlen(string1) returns total number of characters in string1
strcat() strcat(string1,string2) Appends string2 to string1
strncat() strncpy(string1, string2, 4) Appends first 4 characters of string2 to string1
Returns 0 if string1 and string2 are the same;
strcmp() strcmp(string1, string2) less than 0 if string1<string2; greater than 0 if
string1>string2
Compares first 4 characters of both string1 and
strncmp() strncmp(string1, string2, 4)
string2
Compares two strings, string1 and string2 by ignor-
strcmpi() strcmpi(string1,string2)
ing case (upper or lower)
Compares two strings, string1 and string2 by ignor-
stricmp() stricmp(string1, string2)
ing case (similar to strcmpi())
strlwr() strlwr(string1) Converts all characters of string1 to lower case.
strupr() strupr(string1) Converts all characters of string1 to upper case.
Function Description
rounds up the given number. It returns the integer value which is greater
ceil(number)
than or equal to given number.
rounds down the given number. It returns the integer value which is less
floor(number)
than or equal to given number.
sqrt(number) returns the square root of given number.
pow(base, exponent) returns the power of given number.
abs(number) returns the absolute value of given number.
// cosine of π is -1.0000.
// arc cosine of cos(π) is 3.1416.
// hyperbolic tangent of 10.0 is 1.0000.
Though you don't have to learn about pointers, structures and file handling, we shall just go
through the same for your basic knowledge.
A pointer is a special type variable that is used to store the address of a variable's memory
location. Any datatype can be used to generate pointer variables. Each pointer only stores the address
of variables that have the same datatype. That implies that a single integer variable's address is stored
in an integer pointer. This variable may be of type int, char, array, function, or any other pointer. The
architecture determines the size of the pointer. Syntax for pointer declaration:
datatype *pointer_variablename;
Example: int *sum; char *ch;
The following syntax is used with the assignment operator to assign an address to a pointer variable:
pointer_variablename = & variable_name ;
The addresses of other variables are stored in pointer variables. This address can be used to access
the variable's pointer, which holds the value of the variable. To access the value of the variable that
the pointer is referring to, we place the symbol "*" in front of the variable name. General syntax is:
*pointer_variablename;
Example to demonstrate the working of pointer:
#include<stdio.h>
void main()
{
int number=25;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
}
The output is as follows:
// Address of p variable is 1b67032c
// Value of p variable is 25
In the example given, variable ‘p’ contains the address of the number and *p is used to
dereference the pointer ie *p gives us the original value.
Pointers are used with arrays, structures, and functions to retrieve strings, trees, and other data
while reducing code and enhancing efficiency. Using the pointer, we may use a function to return
several values. It enables you to access any memory place.
Since we already know this, a pointer is used to hold the address of a variable and speeds up
access to it. Additionally, a pointer can be defined to hold the address of another pointer. A double
pointer is one such pointer (pointer to pointer). The address of a variable is stored in the first pointer,
whereas the address of the first pointer is stored in the second pointer. Syntax is:
datatype **pointer_variablename
// Program to show the working of double pointer
#include<stdio.h>
void main(){
int num=25;
int *p;//pointer to int
int **q;//pointer to pointer
p=#//stores the address of number variable
q=&p;
printf("Address of 'num' variable is %x \n",&num);
printf("Address of 'p' variable is %x \n",p);
printf("Value of '*p' variable is %d \n",*p);
printf("Address of 'q' variable is %x \n",q);
printf("Value of '**q' variable is %d \n",*p);
}
The output obtained for the above program is as follows:
// Address of 'num' variable is 3d249cb4
// Address of 'p' variable is 3d249cb4
// Value of '*p' variable is 25
// Address of 'q' variable is 3d249cb8
// Value of '**q' variable is 25
Structures, often known as structs, are a means to collect numerous related variables in a
single place. The structure's variables collectively are referred to as its members. In the C programming
language, the structure is used to build user-defined data types. The structure is also referred to as a
"user-defined data type in C" because it is the one that is used to generate a user-defined data type. A
structure, as opposed to an array, can hold a wide variety of data types (int, float, char, etc.). In other
words, a structure is a grouping of non-homogeneous elements. We can create new data types, known
as user-defined data types, using structure, which can hold numerous values of various data types. The
general syntax to define the structure is as follows
Principles of Programming and Web Technologies 87
kn Unäv
struct structure_name
{
data_type member1;
data_type member2, member3;
.
.
data_type memeberN;
};
Example:
struct Student
{
char stud_name[30];
int roll_number;
float m1,m2,m3,m4,m5;
double percentage;
};
Here, struct is the keyword; Student is the name of the structure; roll_number, std_name,
m1,m2,m3,m4,m5 and percentage are the members of the defined structure. To access the structure
in the main program, you need to create a variable of it. The struct keyword is used inside the main(),
followed by the structure name of the structure and then the name of the structure variable as given
below:
struct Student stud;
Structure variables can be created in two different methods. Through the use of the struct
keyword, we can create structure variables both during the structure's definition and after it has been
finished. We use the dot (.) operator to access members of a structure using a structure variable. Now
we shall try to understand more about structure using a simple example
#include<stdio.h>
struct Student
{
char stud_name[30];
int roll_number;
int clas;
char division[5];
int marks[10];
} stud_1 ;
void main(){
struct Student stud_2; // using struct keyword
int sum=0, i, n=5;
double average;
printf("Enter details of stud_1 : \n");
printf("Name : ");
scanf("%s", stud_1.stud_name);
printf("Roll Number : ");
scanf("%d", &stud_1.roll_number);
printf("Class : ");
scanf("%d", &stud_1.clas);
printf("Division : ");
scanf("%s", &stud_1.division);
for(i=0; i < n; ++i) {
printf("Enter marks %d : ",i+1);
scanf("%d", &stud_1.marks[i]);
sum += stud_1.marks[i];
}
average = (double) sum / n;
printf("Total Marks Obtained = %d\n", sum);
printf("***** Student 1 Details *****\n");
printf("Name of the Student : %s\n", stud_1.stud_name);
printf("Roll Number of the Student : %i\n", stud_1.roll_number);
printf("Class & Division : %i,%s\n", stud_1.clas,stud_1.division);
printf("Percentage of the Student : %f\n", average);
}
The output obtained from the above program is as follows:
// Enter details of stud_1 :
// Name : Kannan
// Roll Number : 128
// Class : 8
// Division : A
// Enter marks 1 : 98
// Enter marks 2 : 89
// Enter marks 3 : 91
// Enter marks 4 : 85
// Enter marks 5 : 90
// Total Marks Obtained = 453
// ***** Student 1 Details *****
// Name of the Student : Kannan
// Roll Number of the Student : 128
// Class & Division : 8,A
// Percentage of the Student : 90.600000
The structure variable "stud 1 is generated while defining the structure in the above example
programme, and the variable "stud 2 is created for using struct keyword. The dot (.) operator is used
to access a structure's members whenever we need to. Other way to access structure is as follows:
struct Student{
int rno;
char name[50];
float percentage;
};
void main() {
struct Student s1 = {101, "Asha", 89.50};
struct Student s2 = {102, "Ardra", 92.25};
struct Student s4 = {112, "Kannan", 94.85};
struct Student s5 = {109, "Deepa", 86.65};
printf("%d, %s, %f%\n", s1.rno, s1.name, s1.percentage);
printf("%d, %s, %f%\n", s2.rno, s2.name, s2.percentage);
printf("%d, %s, %f%\n", s4.rno, s4.name, s4.percentage);
printf("%d, %s, %f%\n", s5.rno, s5.name, s5.percentage);
}
The output obtained is as follows:
// 101, Asha, 89.500000%
// 102, Ardra, 92.250000%
A user-defined data type known as a union can be described as a grouping of various variables
of various data kinds stored in the same memory address. The union can also be thought of as having
numerous members, but at any given time, only one member can have a value. Union is a user-defined
data type, however unlike structures, they are stored in the same location in memory. Syntax for
creating union is as follows:
union <structure_name>{
data_type member1;
data_type member2, member3;
.
.
};
// Program using Union
union test {
int m, n;
};
int main(){
union test t;
t.m = 25;
printf("After making m = 25:\n m value is = %d, n value is = %d\n",t.m, t.n);
t.n = 35;
printf("After making y = 35:\n m value is = %d, n value is = %d\n\n",
t.m, t.n);
return 0;
}
The output obtained is as follows
// After making m = 25:
// m value is = 25, n value is = 25
// After making y = 35:
// m value is = 35, n value is = 35
// Program to show difference between unions and structures
#include <stdio.h>
Principles of Programming and Web Technologies 91
kn Unäv
union unionStudent{
char std_name[40];
int roll_number,clas, marks[10];
float percentage;
} uStudent;
struct structStudent{
char std_name[40];
int roll_number,clas, marks[10];
float percentage;
} sStudent;
void main()
{
printf("size of union = %d bytes", sizeof(uStudent));
printf("\nsize of structure = %d bytes", sizeof(sStudent));
}
The output of the above program is obtained as follows:
// size of union = 40 bytes
// size of structure = 92 bytes
From the above program , you can see that the size of union uStudent is 40 while that of
structure sStudent is 92. It's because the size of a union variable will always be the size of its largest
element. In the above example, the size of its largest element, (std_name[40]), is 40 bytes.
In programming, we might need to generate a certain type of input data more than once.
Sometimes merely displaying the facts on the console is insufficient. The quantity of data that can be
displayed on the console may be extremely small or very vast, and because the memory is volatile, it
is hard to repeatedly restore the programmatically generated data. However, we can store data on the
local file system, which is volatile and accessible at all times, if needed. Here, file handling becomes
necessary. File can be seen as a collection of data or information that is stored on secondary memory
like hard disk of a computer. Text files and binary files are supported. The following operations can
be performed on a file.
• File creation
• Opening an existing file
• Reading from the file
• Writing to the file
• Deletion of the file
There are many functions that can be performed on file and the followng Table 3.4 gives the list of
the file functions available.
A file pointer of type FILE must be created in order to open an existing file or create a new one. It is
defined as
File *fp ;
fp = fopen("file_name", "mode") ;
Different modes available for opening any files are the following:
r : Enables the reading of a text file.
w : Opens a text file in writing mode.
a : Opens a text file in append mode.
r+ : Permits a text file in both reading and writing mode.
w+ : Opens a text file in both reading and writing mode. When a file exists, it moves the
cursor to the beginning of it.
a+ : Enables the reading and writing of a text file. Reading operations are carried out from
the beginning of the file, while writing operations are carried out from its end.
Predefined functions like getc(), getw(), fscanf(), fgets(), fread() file operations which are used
to read data from the files. Predefined file handling methods which includes putc(), putw(), fprintf(),
fputs(), fwrite() are used to write data into the files. Using a pre-defined method fclose() , closing of
a file is performed. Several pre-defined techniques are available in the C programming language to
set the cursor location in files. The methods available to place the cursor in a file are: fseek(), ftell(),
rewind().
References
1. Programming in ANSI C, E. Balagurusamy, McGraw Hill Education
2. Let Us C : Authentic guide to C programming language, Yashavant Kanetkar, BPB Publications
3. https://www.vssut.ac.in/lecture_notes/lecture1424354156.pdf
Module IV
Web Programming: HTML, CSS and JavaScript
Learning web technology is crucial today because the internet has surpassed other informational
mediums as the most important source, and many earlier software programs have evolved into web
apps. The majority of the time, web applications may now completely replace desktop applications
because of their increased capabilities. Web technologies are those that deal with how web servers and
clients interact. Markup languages, programming interfaces, and standards for document identification
and display are all included in this information. Through the use of multimedia software and markup
languages, web technology allows computers to communicate with one another. Creating a website
for the Internet or an intranet is another aspect of Web technology. In a similar vein, it can involve
creating the most complicated web-based internet apps or the smallest static single page of plain text.
In order to access websites, a web browser is required. Web browsers are described as applications that
show text, data, images, animations, and videos on the Internet. Using software interfaces provided
by Web browsers, users can access hyperlinked resources on the World Wide Web.
Generally speaking, web technology includes methods and tools for creating websites.
Backend and frontend technologies are two categories of web technologies. The front end of a website
is designed using front-end technologies, whereas the back end of a website or web application is
developed using back-end technologies.
Three languages are needed to generate a typical web page and as shown in the illustration below.
Web Application
Nowadays, everyone uses the internet. Longer loading times and static web pages are no
longer common on the Internet. With the development of attractive and effective web applications,
the internet has shifted in the direction of active user interaction and increased functionality. A web
application is exactly like a typical computer application, with the exception that it operates online.
The use of web applications is emerging daily in the modern world. A web application is a computer
program that works via the Internet using web technology and web browsers. It is stored or maintained
on a remote server. Web applications can be made for a wide range of tasks and are accessible to
everyone, from individuals to businesses, for a variety of tasks. It is a computer programme that,
to put it simply, uses a web browser to perform some predetermined tasks for its client. The term
"web apps" also refers to web-based programs. Webmail, online games, file conversions, video/audio
editing, and e-commerce sites are some examples of frequently used web apps. The majority of
web apps are accessible on any browser, while certain web apps can only be viewed by a particular
browser. There are six different types of applications:
• Static
• Dynamic
• Online Store or E-Commerce
• Portal Web Apps
• Animated
• Content Management System
• Benefits of web apps
• These function across several platforms independent of the operating system or device
provided the browser is appropriate
• Every user has access to the same version, therefore there are no compatibility problems.
• There are no space restrictions because they are not installed on the hard disc.
• They minimize software piracy in web applications with subscription fees.
• Because there is less need for business support and maintenance and fewer demands placed on
the end user's computer, they minimize costs for both the business and the end user.
• Web apps can be customized.
• As long as a user has a functional internet connection, they can work from anywhere in the
world.
• An username, password, and URL are all that is needed to create a new user, which only takes
a moment.
Working of Webapps
Since web applications are accessed through a network, they don't need to be downloaded.
Web browsers like Google Chrome, Mozilla Firefox, or Safari can be used by users to access a Web
application. The web application needs a web server to handle client requests, an application server to
carry out the duties, and sometimes a database to store the data. Web servers manage client requests
while the application server completes the assigned work. A database can be used to store any relevant
data. The workflow of the web application can be depicted as given in Figure 4.2:
Transfer Protocol (HTTP) is used. Most of the information on these websites is static and consists of
HTML documents, graphics, style sheets, tests, etc. In addition to HTTP, a web server also supports
the Simple Mail Transfer Protocol (SMTP) and File Transfer Protocol (FTP) protocols for emailing
and transferring and storing files, respectively.
Table 4.1: Difference between Application & Web Server
Client
A client is a part of user software that communicates with a server to access a service. It can be
either any device or any machine. It is categorized into Thin clients, Fat clients, and Hybrid clients. The
Thin client normally relies on the host computer resources and is lightweight. A Fat client otherwise
known as a Thick client provides rich functionalities and is server-dependent slightly. Whereas, the
hybrid client usually takes the characteristics of both thin and thick clients. A web browser, such as
Firefox, Chrome, Safari, etc is a client program that makes use of web server facilities.
Client server is a relationship in which one program normally the client requests a service or
resources from another program namely the server. The clients in the form of Pcs, laptops, mobile
phones, etc. Request for any services like a file or application transfer from the server. The server
in turn hears these requests from the client, verifies the user credentials, and if found correct and
accurate, fulfills the client's requests.
Table 4.2: Difference between Client & Server
Client Server
Depends on the server services and requests are Authorizes the requests given by client and
generated for various sessions. facilitates them with the requested services.
Has basic hardware configuration Has advanced hardware configuration.
Limited efficiency. Highly efficient and has high performance.
Switching off may result in unavailability or
Can be switched off at anytime without any fear.
undeliverable of requests from other clients.
Supports simultaneous multiple user login at
Only single login possible.
a time.
Performs simple tasks. Performs complex tasks and stores huge data.
scripts. It is generally accomplished in the front end, where it is visible to visitors and less prone to
leaks and vulnerabilities. As a result, it is frequently employed to create user interfaces and other types
of lightweight functionality. Since they operate locally, they typically offer superior performance and
do not burden the server.
Server-side uses
• It processes the user input
• it displays the requested pages
• Structure of web applications
• It interacts with servers/storages and databases
• Querying the database
• Encoding of data into HTML
• Operations over databases like delete, and update.
Examples of server-side scripting languages includes : PHP, ASP.NET, Java and JSP, Python, Ruby
on Rails, and so on.
Client-side uses
• It makes interactive web pages
• Make stuff work dynamically
• It interacts with temporary as well as local storage
• Works as an interface between the user and the server
• Sends requests to the server
• Retrieval of data from the Server
• Provides remote access for client-server program
Examples of client-side scripting languages include JavaScript, VBScript, HTML, CSS, AJAX,
jQuery, etc.
The use of scripting languages over other programming languages has numerous advantages.
They are open-source, to begin with. This makes it possible for users from all over the world to
contribute to the improvement process. Other instances and benefits of scripting language include:
• No compilation is necessary, though it is occasionally required.
• Switching between operating systems is simple.
• Web pages that use scripting languages look fabulous.
• Easier to write and learn.
• Scripts can be used as a program's prototype, reducing the need for test projects.
It was also advantageous to incorporate general-purpose scripting languages rather than
developing a new language for each application, particularly because the application developer did
not have to write a language translator from scratch and the users could use the skills they had already
acquired elsewhere.
Principles of Programming and Web Technologies 99
kn Unäv
Introduction to HTML
HyperText Markup Language (HTML) is the fundamental component of the World Wide
Web. Hypertext is the text that is displayed on a computer or other electronic device and contains
links to other text that the user can access right away, typically by clicking a mouse or pressing
a key. Hypertext may also include tables, lists, forms, graphics, and other presentational features
in addition to text. It is a simple and adaptable format for information sharing via the Internet.
Markup languages characterize text elements inside a document using collections of markup tags,
which provide directions to web browsers on how the page should appear. Tim Berners-Lee created
HTML for the first time in 1990. He is also known as the father of the web. The World Wide Web
Consortium (W3C) was given the responsibility of maintaining the HTML specifications in 1996. In
2000, HTML also earned ISO certification as a global standard. The most recent HTML version is
HTML5. In terms of web development, HTML5 offers a more fast and more effective method. It has
more sophisticated features like Geo-location, native audio, and video support, Canvas, Web Socket,
etc. Typically, learning and using HTML is simple. HTML is one of the most widely used languages
on the web. Some of the application areas are:
• Development of Webpages - Web pages are rendered using HTML. For the purpose of
rendering information in browsers, almost every web page has HTML tags.
• Internet Navigation - HTML offers tags that are used to traverse between pages and is widely
used for internet navigation.
• Responsive UI - Nowadays, HTML pages function well on all platforms, including mobile,
tablets, desktops, and laptops, due to responsive design concepts.
• Offline support - Once loaded, HTML pages can be accessed locally on the computer without
an internet connection.
• Development of Games - HTML5 now offers native support for rich experiences and is helpful
in the development of video games.
• Additionally, HTML permits the use of templates, which simplifies the process of creating a
website.
• Because the text can be compressed, downloading is quick.
• Very helpful for those just getting started in the field of web design.
• Even if not supported by every browser, HTML can be supported by the majority of them.
• Nearly all websites are designed with HTML.
• Similar to XML syntax, HTML is increasingly being used for data storage.
• HTML offers a variety of tags and attributes that might help you shorten your code.
Since HTML files simply text files, any text editor can be used to create them. Web page
creation and editing are done using HTML text editors. Any text editor, including notepad, can be
used to create HTML codes. Simply type HTML in any text editor and save the document with the
".html" or ".htm" extension. Following are a few of the well-known HTML text editors including
Notepad, Notepad++, SublimeText3, Atom, etc.
HTML Tags
HTML tags act as keywords that specify how a web browser will format and present content.
A web browser can tell the difference between plain content and HTML content with the help of tags.
The opening tag, content, and closing tag are the three essential parts of an HTML tag. However,
some HTML tags are not closed. An HTML document is read by a web browser from top to bottom
and left to right. In order to generate HTML documents and render their characteristics, HTML tags
are used. Every HTML tag has a unique set of features. To distinguish between simple text and HTML
text, a web browser needs a few basic tags in an HTML file. As required by your code, you are free
to use as many tags as:
• All HTML tags need to be enclosed inside these brackets (< >).
• Every HTML tag has a different function.
• An open tag must be followed by a close tag if you previously used one (except some tags)
Normally HTML tags are written in lower case. Syntax for defining a tag:
<tag> contents </tag>
HTML Elements
An HTML element is a discrete element contained within an HTML document. Semantics
or meaning is represented by it. The title element, for instance, displays the document's title. The
majority of HTML components have content between start and end tags, also known as opening and
closing tags. Elements may also have attributes that specify extra features.
The beginning of the content is indicated to the browser using the opening tag. To specify
to the browser where the content terminates, use the closing tag. The actual text contained within
the opening and closing tags is referred to as the content. An overall HTML Element is created by
combining all three of these components. As an illustration, the following would be written as a
paragraph, which is represented by the p element:
A start tag, its attributes, an end tag, and everything in between makes up an HTML element
technically. On the other hand, as you can see in the above illustration, an HTML tag (either opening
or closing) is used to designate the start or end of an element. However, in common parlance, the
terms "HTML element" and "HTML tag" are synonymous, meaning that a tag is an element and vice
versa.
Since empty elements are not container tags, you cannot write <hr>some content</hr> or
<br>some content</br>. They are also known as self-closing, unpaired tags or void elements. The
<br> element, which denotes a line break, is a common example of an empty element. Other often
used empty elements include <img>, <input>, <link>, <meta>, <hr>, etc.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<p>Examples <br> use of empty elements</p>
<p> Placing an image</p>
<img src="/examples/images/sky.jpg" alt="Cloudy Sky" width="200" height="100" >
<p> Placing an textbox</p>
<input type="text" name="username">
<p>you can draw an horizontal line <hr></p>
</body>
</html>
An element can contain another element in HTML, which means that nesting is possible. The
majority of HTML elements have the ability to contain a variable number of additional elements,
which are composed of tags, attributes, content, and/or other elements. When other elements are
nested within a nested element, also known as a child element, it can also function as a parent element.
HTML tags need to be nested correctly. The last tag opened must be closed first, and they must be
closed in the reverse order of how they are defined.
Example:
<p>Welcome to <b>HTML</b> programming</p>
Block-level and inline-level elements are two distinct categories into which elements can be
categorized. The former comprises the document's structure, whereas the latter comprises a block's
contents. A block element is also shown with a line break before and after and takes up 100% of
the available width. The most often used block-level elements are <div>, <p>, <h1> through <h6>,
<form>, <ol>, <ul>, <li>, and so on. An inline element will only use as much space as it requires.
<img>, <a>, <span>, <strong>, <b>, <em>, <code>, <input>, <button>, etc. are frequently used
inline-level elements. Inline-level elements must not contain any block-level elements.
HTML Attributes
The modifier of an HTML element, attributes are special words that provide more information
about the element. Each element or tag has characteristics that can be used to describe how it behaves.
It should be placed within the start tag and typically take the form of name=value pairs. Values for
attributes must always be enclosed in quotation marks. To quote attribute values, use either single
or double quotation marks. But double quotes are the most typical. The W3C advises writing the
attribute's name and values exclusively in lowercase because they are case-sensitive. There must be
space between two attributes when adding multiple attributes to an HTML element.
In HTML5, there are numerous attributes that only have names and no values. These are
referred to as boolean attributes. Checked, disabled, read-only, required, etc. are a few examples of
common Boolean attributes. There are some attributes commonly known as general purpose attributes,
such as id, title, class, style, etc. that can be used on the majority of HTML elements.
Table 4.4: Attributes in HTML5
HTML Comments
The purpose of adding comments is often to make the source code clearer to understand. It
might aid other developers in understanding what you were attempting to do with the HTML. The
browser does not display comments. <!— and --> are the starting and closing tags for an HTML
comment. It is helpful to understand the complex code's steps. When codes are being debugged,
the comment tag is useful. It is a small piece of code that web browsers ignore, meaning that it is
not displayed. Understanding the purpose of a piece of code, particularly in complex source code, is
beneficial to both coders and readers. There are three different ways of commenting in HTML which
includes Single-line comment, Multi-lines comment. Example:
<!-- comment example -->
<h1>Hello World Program</h1>
<!--
how does comment tag works
-->
<h12>Hello World Program using heading 2</h2>
HTML Heading
Headings assist in outlining the hierarchy and organization of the content on a web page. The
heading level values in HTML range from h1 to h6, with h1 being the most significant heading and h6
denoting the least important heading. The lower the heading level number, the greater its importance.
Browsers show headers by default with a larger and bolder font than other text. Additionally, h1
headers are displayed in the largest font size, whereas h6 headings are shown in the lowest font size.
Principles of Programming and Web Technologies 107
kn Unäv
The example here demonstrates different levels of heading and the output of the same:
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<h1>Heading level 1 : Hello World</h1>
<h2>Heading level 2 : Hello World</h2>
<h3>Heading level 3 : Hello World</h3>
<h4>Heading level 4 : Hello World</h4>
<h5>Heading level 5 : Hello World</h5>
<h6>Heading level 6 : Hello World</h6>
</body>
</html>
Using Paragraph
Using paragraph elements, the text is published on web pages. The <p> tag is used to define
paragraphs in a text. There are opening and closing tags on these. In order to publish your text on
the web pages, you will normally need to use the paragraph tag. The built-in style sheets of web
browsers automatically add some blank space known as a margin before and after each heading
whenever you set a heading element on a web page. In order to increase user engagement, carefully
optimize the HTML headings because they highlight key points and the document's structure and
offer vital information. Don't use headings to make your text appear capitalized or bold. Use them
just to draw attention to your document's heading and to illustrate its organization. Utilize headers on
your webpage carefully since search engines like Google use them to index the structure and content
of web pages. Use the h1 headings as the page's primary headings, followed by the h2 headings, the
h3 headings, and so on, which is quite simple. Therefore, everything that occurs between <p> and </
p> is considered to be a paragraph. Even if we don't use the closing tag, </p>, most browsers still treat
a line as a paragraph, although this could lead to unexpected outcomes. On web pages, <br> tag is
used to add line breaks, and <hr> tag is used to add horizontal rules or lines to visually divide content
sections.
When displaying the page, a browser will eliminate superfluous spaces and lines if <p> tag
contains a lot of blank spaces. Multiple lines and spaces are counted as one by the browser. It isn't
always convenient to manage spaces by using , <br>, etc. As an alternative, you can display
blank spaces, tabs, line breaks, etc. precisely as they are in the HTML file by using the <pre> element.
It is especially useful when presenting content that requires line breaks and space, such as poetry or
computer code. This provides the alignment feature that enables us to center, right, or left align our
paragraphs. Example:
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<p>Demonstrates multiple spaces in the source code.
<p> Demonstration <hr> of multiple tabs <br>
in the source code. </p>
<pre>
Baa baa black sheep, have you any wool?
Yes sir, yes sir, three bags full!
One for the master, one for the dame,
And one for the little boy who lives down the lane.
</pre>
</body>
</html>
Avoid using the empty paragraph <p></p> to create extra space on your website pages. Since
it is a logical tag, the browser may ignore the empty paragraphs.
Text Formatting
Text can be formatted in HTML just like it is in Microsoft Word or other text-editing tools.
You can use the HTML tag <b> to make text bold, the tag <I> to make text italic, the tag <mark> to
highlight the text, the tag <code> to display a portion of computer code, the tag <ins> and <del> to
indicate editorial insertions and deletions, and more to make some text on your web pages appear
differently than normal text. The formatting tags in HTML are divided into two groups namely
Physical tags and Logical tags. Former is employed to give the text a visual look and the latter is used
to enhance the text's logical or semantic content. List of formatting tags is given in Table 4.5.
Links or Hyperlinks
A link, often known as a hyperlink, connects one website to another. Users can easily navigate
between pages on any server in the world by using links. A link has two anchors at each end. The link
begins with the source anchor and leads to the destination anchor, which could be any web resource,
such as an image, an audio or video clip, a PDF file, an HTML page, or even an individual element
inside the document. In the majority of browsers, links will typically show like follows by default:
• An unclicked link is blue and underlined.
• An active link is marked in red.
• A visited link is underlined in purple.
An anchor and a direction are the two endpoints of a link. The link begins at the "source"
anchor and directs the user to the "destination" anchor, which could be any Web resource, including
an image, a video clip, a sound bite, a program, an HTML document, or an element contained within
an HTML document. Many websites and social media platforms link an image or text to a URL, for
example. This basically means that you can link one element of your code to another element that may
or may not be in your code by utilizing the 'a' tag. Where to open the linked content is specified by the
target attribute in the browser. The names of the four defined targets all begin with an underscore (_)
character.
_blank — This command displays the linked document in a new window or tab.
_parent — This command opens the linked file in the parent window.
_self — Opens the linked file in the same tab or window as the original file.
It is not essential to explicitly give this value because it is the default.
_top — This command opens the linked document in the whole browser window.
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML Link</title>
</head>
<body>
110 Principles of Programming and Web Technologies
kn Unäv
</body>
</html>
To enable users to quickly navigate to a particular area of a web page, bookmark anchors can
also be made. If your web page is really lengthy, bookmarks will be especially useful. The procedure
of making bookmarks involves two steps: As illustrated in the example below, first add the id attribute
to the element where you wish to jump, then use that id attribute value, followed by the hash symbol
(#), as the value of the href attribute of the a> tag:
<p><a href="#sectionA">Jump to first section</a></p>
<p><a href="#sectionB">Jump to second section</a></p>
<h2 id="sectionA">First Section</h2>
<p> Welcome to my First Section. </p>
<h2 id="sectionB">Second Section</h2>
<p> Welcome to my Second Section </p>
Colors
To give your website a pleasant and beautiful look and feel, colours are essential. Using
the tag or the bgcolor attributes, you can set colours for specific tags or for the entire page.
The tag can be used to set various colours using the following attributes:
• The bgcolor setting determines the colour of the page's background.
• For the body text, text specifies a colour.
• Alink determines the colour of selected or active links.
• Link specifies a colour for text that is linked.
• Vlink creates a colour for links that have been visited or links that have already been clicked.
The three techniques listed below can be used to change the colours on your website:
• Color names — You can directly define colours like green, blue, or red.
• Hex codes — a six-digit code that indicates the percentage of red, green, and blue in a given
colour.
• Decimal or percentage values for colours - The rgb() property is used to define this value.
Fonts
When it comes to improving a website's usability and content readability, fonts are important.
Although the font face and colour of the text on your website are entirely dependent on the machine
and browser being used to view it, you can use HTML tags to change the text's style, size, and colour.
To uniformly size, face, and colour all of your text, utilise tags. Size, colour, and face are the three
properties of the font tag that allow you to personalize your fonts. Simply use the element to modify
any font property at any moment within your webpage.
Until you close with the tag, the text after this one will still be modified. Within a single tag,
you can modify any or all of the font characteristics. Using the size attribute, you may modify the
content font size. Between 1 (smallest) and 7 are the acceptable values (largest). A font's standard size
is 3. You can specify how many font sizes should be added to or subtracted from the default size. You
can say something like, <font size = "+n"> or <font size = "−n">.
If the user viewing the website doesn't have the font installed, they won't be able to see
it, thus be cautious while setting the font face using the face attribute. The user will see the
computer's default font face in its place. Using the colour attribute, you can choose whatever
font colour you like. Using the colour attribute, you can choose whatever font colour you
like. Either the color's name or hexadecimal code can be used to specify the shade you want.
For those portions of the document not covered by a <font> tag, the <basefont> element is
intended to set a default font size, colour, and typeface. The base font settings can be overridden by
using the <font> elements. The size attribute of the <basefont> tag accepts values of +1 for a size
greater or 2 for two sizes smaller, supporting the relative font setting. It also accepts colour, size, and
face properties.
<!DOCTYPE html>
<html>
<head></head>
<body>
<basefont face = "arial, verdana, sans-serif" size = "2" color = "#008080">
<p>This is the page's default font.</p>
<h2>Example of the <basefont> Element</h2>
<p><font size = "+3" color = "purple">
This is purple text is with +3 size
</font></p>
<p><font face = "courier" size = "-1" color = "#008080">
Font is courier, a size smaller and with TEAL color.
</font> </p>
</body>
</html>
a media attribute that defines a media condition similar to the media query that the browser uses to
decide when to use a specific source.
Using an image map, you may create hotspots on an image that function exactly like hyperlinks.
The main goal of generating image maps is to give people a simple way to connect different elements
of an image without having to break it into individual image files. An example of this would be a
global map with hyperlinks to more nation information.
<td>2</td>
<td>Three Thousand Stitches</td>
<td>Sudha Murthy</td>
<td>2017</td>
</tr>
<tr>
<td>3</td>
<td>Fire on the Mountain</td>
<td>Anita Desai</td>
<td>1977</td>
</tr>
<tr>
<td>4</td>
<td>The Inheritance of Loss </td>
<td>Kiran Desai</td>
<td>2006</td>
</tr>
<tr>
<td>5</td>
<td>That Long Silence</td>
<td>Shashi Deshpande</td>
<td>1988</td>
</tr>
</table>
</body>
</html>
Tables do not by default have borders. Table borders can be added using the CSS border
attribute. Additionally, table cells are automatically scaled to suit their contents. Use the CSS
padding property to increase the amount of space around the content in table cells. You can
extend table rows and columns across numerous additional rows and columns by using spanning.
A table cell cannot typically cross over into the area just below or above another table cell.
However, you can span several rows or columns in a table using the rowspan or colspan attributes.
Similar to this, you may make a cell that spans more than one row by using the rowspan attribute.
Using the <caption> element, you can specify a caption (or title) for your tables. The starting
<table> tag must come just after the <caption> element. The caption shows at the top of the table by
default, but you can move it by using the CSS caption-side property. By specifying the header, body,
and footer areas, respectively, the HTML <thead>, <tbody>, and <tfoot> tags make it easier to build
more organised tables.
</li>
<li>Black Forest Cake</li>
<li>White Forest Cake</li>
</ol>
<h4>Example for Description List </h4>
<dl>
<dt>Chocolate Cake</dt>
<dd>Cake made of melted chocolate, cocoa powder, or both.</dd>
<dt>Black Forest Cake</dt>
<dd> Chocolate sponge cake sandwiched with a rich cherry filling and whipped
cream.</dd>
</dl>
</body>
</html>
Attribute Description
Lists the character encodings that the server handling this form will accept for
accept-charset
input data.
Specifies the web server's programme or script's URL, which will be used to
action
handle any form-submitted data.
This Boolean value indicates that the form's submission should not trigger
novalidate
validation. Only in HTML5
Specifies the HTTP method that is used by the browser to transfer data to the
method
web server. Either get (the default) or post can be used as the value.
Specifies the location where the response will be displayed once the form has
target
been submitted. Possible options are _blank, _self, _parent and _top.
Gives instructions on how to encode the form's data before sending it to the
enctype
server. Only applicable when the method attribute's value is post.
HTML Iframes
To show external items, such as other web pages, within a web page, an iframe or inline
frame is utilised. Iframes essentially function as a tiny online browser inside a larger web browser.
Additionally, an iframe's content exists completely independently of the items around it. The following
is the general syntax for including an iframe in a web page:
<iframe src="URL"></iframe>
A web page or external object can be found at the URL mentioned in the src attribute. There
are two different kinds of URL links: Relative URLs, which connect to other files on the same web
page, and Absolute URLs, which point to another web page. The HTML <iframe> tag supports the
following characteristics.
• HTML <iframe> allow attribute
• HTML <iframe> allowfullscreen attribute
• HTML <iframe> allowpaymentrequest attribute
• HTML <iframe> height attribute
• HTML <iframe> width attribute
• HTML <iframe> loading attribute
• HTML <iframe> scrolling attribute
• HTML <iframe> name attribute
• HTML <iframe> referrerpolicy attribute
• HTML <iframe> sandbox attribute
• HTML <iframe> src attribute
• HTML <iframe> srcdoc attribute
<!DOCTYPE html>
<html>
<body>
<p>The content follows here...... </p>
<iframe src=
"https://www.learn-html.org/"
height="300"
width="400"
style="border: 4px solid blue">
</iframe>
</body>
</html>
HTML- Marquee
An HTML marquee is a scrolling piece of text displayed either horizontally across or vertically
down your webpage depending on the settings. This is created by using HTML <marquees> tag. The
general syntax to use HTML <marquee> tag is as follows −
<marquee attribute_name = "attribute_value"....more attributes> text </marquee>
The attibute used with this tag width, height, direction, bgcolor, behaviour, scrolldelay, loop,
scrollamount, hspace, vspace.
Embedding Audio and video
Before, it was difficult to include audio and video on a web page since there was no standardized
way for web browsers to define embedded media files like audio/video. A standard method for including
audio in web pages is offered by the recently released HTML5 <audio> and <video> elements.
Although the audio component is rather new, it is compatible with the majority of current web browsers.
In the example below, an audio/video is simply inserted into the HTML5 document using the
standard set of controls provided by the browser, with a single source specified by the src attribute.
<audio controls="controls" src="media/birds.mp3"> bird </audio>
<video controls="controls" src="media/shuttle.mp4"> hello </video>
You can make links to your audio/video files using href and play it by clicking on them.
Different types of media files can be embedded into an HTML document using the <object> element.
Originally used to insert ActiveX controls, the specification states that an object can now be any
type of media object, including audio, video, PDF files, Flash animations, and even photographs.
Multimedia content can be included in an HTML document using the <embed> element.
<object data="media/sea.mp3"></object>
<embed src="media/wind.mp3"></embed>
Example to embed youtube vedioes is as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Embedding a YouTube Video in an HTML Page</title>
</head>
<body>
<iframe width="560" height="315" src="//www.youtube.com/watch?v=n38kGst16sI"
frameborder="0" allowfullscreen></iframe>
<p>Source: <a href="https://www.youtube.com/watch?v=n38kGst16sI" target="_blank"
rel="nofollow">https://www.youtube.com/watch?v=n38kGst16sI</a></p>
</body>
</html>
Introduction to CSS3
In this section, we introduce you to cascading style sheets (CSS), which are widely used
on the Internet. We'll briefly discuss what they are, the various types, and give you a few typical
examples. Hypertext Markup Language, or HTML, is used to create the majority of web pages.
This is how hyperlinks, graphic ornamentation, and other elements are typically added to plain web
text. But websites have the potential to grow significantly large. When that occurs, using HTML is
a very difficult approach to carry out a really simple task. CSS can make designing websites simple
once more! The CSS was developed by the World Wide Web Consortium (W3C). CSS3 is a latest
standard. All previous CSS versions and CSS3 are fully compatible.
Together, HTML and CSS are used to create the well-known and popula web pages. It's crucial
to recognise that these are distinct languages with distinct functions. Text, links, photos, videos, and
other elements of a web page are all determined by HTML. All of the "things" on a page are listed in
an HTML file, but the appearance of these "things" in a browser is not specified. As we already know,
CSS governs how these elements look. CSS makes sure that users see the HTML contents as intended
by designers. Numerous applications for CSS features exist. The usage listed below are only a few
instances.
• The same style rules can be readily applied to several sections.
• A single style sheet can be used to manage the presentation of numerous website pages.
• On several devices, the same page can be displayed in various ways.
• Dynamic states of elements, such as hover, focus, etc., can be styled, which is otherwise not
feasible.
• An element's position on a web page can be changed without altering the HTML.
• Present HTML elements can have their displays changed.
• In 2D or 3D space, you can change objects using operations like scale, rotation, and skew.
• Without using JavaScript, animations and transition effects can be produced.
• You can develop web pages that are print-friendly.
• Variety of Device Support - Content can be optimised for a variety of devices with the use
of style sheets. Different versions of a website can be displayed for printing or for portable
devices like PDAs and cellphones by using the same HTML document.
• Global web standards - Attributes in HTML are currently being deprecated, and CSS is advised
instead. Therefore, including CSS in all HTML pages is a smart idea to ensure that they are
compatible with future browsers.
• Offline browsing - CSS uses an offline cache to enable local storage of web apps. This allows
us to view websites that are offline.
</style>
</head>
<body>
<h1>My heading</h1>
<p>Paragraph</p>
</body>
Inline Style Sheets - Inline styles are positioned exactly where you need them, close to the text or
image you want to beautify. Since inline styles can be inserted anywhere in the middle of your HTML
code, you have complete control over how each element of a web page is defined. However, this
can make updating websites a tremendous hassle! A CSS rule can be rapidly and simply added to an
HTML page. For testing or previewing the modifications and making quick fixes to your website,
this method is helpful. Unlike the external style, you don't need to generate and upload a separate
document. Example:-
<h1 style="color:red; font-size:30px;">Heading Section</h1>
<p style="color:green; font-size:22px;">Paragragh Section</p>
<div style="color:purple; font-size:14px;">Here goes the text section</div>
It is typically thought of as bad practice to use inline styles. As style rules are included straight
inside the HTML tag, the display of the document becomes entangled with its content, making it
difficult to maintain the code and contradicting the point of adopting CSS.
A CSS stylesheet is made up of a set of rules that the web browser interprets and then applies
to the corresponding page elements, such as paragraphs, headings, etc. A selector and one or more
declarations are the two fundamental components of a CSS rule:
Selector {Declaration}
The selector indicates which HTML page element(s) the CSS rule applies to. While the
formatting of the items on a webpage is determined by the declarations contained within the block.
Each declaration consists of a property and a value that are separated by a colon (:) and concluded
with a semicolon (;). Curly brackets are used to enclose the declaration groups. Now the above rule
can further enhanced as follows:
Selector {Property: Value; Property:Value}
The HTML element you want to style is represented by the selector. For instance, from the
above diagram Figure 4.5 , h1 {color: red}. The code informs the web browser that , wherever h1
tag is found, its color must be orange. You can also give more than on declaration or property values
to the selector which needs to be differentiated using a ‘;’ as represented in the illustration.
According to their element name, id, attributes, etc., CSS selectors are used to choose HTML elements.
It can choose one or multiple elements at once.
The five categories of the CSS Selector are as follows:
• Simple Selector: Based on their element name, id, attributes, and other criteria, it is used to
choose the HTML elements.
• Combinators Selector: The relationship between two selectors is described using it.
• Pseudo-classes Selector: The special state of an element is defined by it.
• Pseudo Elements Selector: It is a keyword that has been added to a selector that enables you
to design a certain area of the chosen elements.
• Attribute Selector Selector: An element with a particular attribute or attribute value is chosen
using this method.
The Table 4.7 given below shows various selectors with description and syntax of usage.
Matches all instance of the element in the document with the corresponding element
type name e.g., p, span, div, a.
Element
Selector Syntax: .class-name { property:value; }
p { color: orange; font-family: Serif; }
Regardless of where they are in the document tree, the style rules included in the p
selector will be applied to every element in the page and color it with orange.
Any HTML element with a class property can be chosen using the class selectors.
Every element belonging to that class will be formatted in accordance with the spec-
ified rule. The class value is followed immediately by a period (.) to specify the class
Class selector.
Selector Syntax: .class-name { property:value; }
Example: p.large { font-size: 16pt; color:blue;}
The style rule contained within the selector p.large only affects the <p> elements whose
class attribute is set to large; it has no impact on other paragraphs.
To specify style rules for a single or particular element, use the id identifier. The dis-
tinctive identifier in an HTML document is the id attribute. A # character is used with
the id selector.
ID Selector
Syntax: #id_name {property:value; }
Example: #error { color: red;}
This style rule renders the text of an element in red, whose id is set to error.
An asterisk (*) indicates that the universal selector is the one that matches every ele-
ment on the page. Additionally, it chooses all elements that are nested inside another
Universal element.
Selector Syntax: *{property:value; }
Example: *{ margin: 0; color: red; text-align: center;}
When the mouse is over an element, it is used to style that element. It is applicable to
all elements.
Hover
Syntax: element :hover{ property:value; }
Selector Example: h1:hover { color: white; background-color: red; }
Example shows how the background color can change as you hover over an element.
It is used to target the element based on language attributes for a certain value. The
language-codes are used by this selector to function.
Lang Se- Syntax: :lang(lang-code){ property:value; }
lector Example: h1:lang(en) { color: white; background-color: red; }
The language codes for languages are as follows: en for English, hi for Hindi, fr for
French, de for German, it for Italian, ca for Canadian.
This selector is used to match elements according to where they fall inside a set of
sibling elements. It matches any element that is the nth-child of its parent, regardless
of the type.
Syntax: :nth-child(number){ property:value; }
Nth-child where number is the sole argument used to indicate how the items should match. It
could be in a functional notation, odd, or even. Odd indicates elements in a series
Selector whose positions are odd 1,3,5, etc. Even indicates elements in a series whose po-
sitions are even. For every positive integer or zero value of n, functional notation
(An+B>) denotes items whose siblings' positions fit the pattern An+B. In this case, A
stands for the integer step size, and B for the integer offset.
Example: h1:lang(en) { color: white; background-color: red; }
It is used to view the links that had been visited. For instance, if you click on a link
on a website once and then again, the link's color will have changed. The visited se-
Visited lector is used to adjust the color. The following is a list of the selectors that the CSS
property of:visited accepts: color, border-color, background-color, outline color, col-
Selector umn-rule-color, fill-color and stroke.
Syntax: :visited{ property:value; }
Example: a.visited { color: brown; }
In CSS, comments can be included just like in HTML. The browser ignores comments, which
are helpful for adding context and notes to your code. CSS comments are written as /*, your comment
text, and */ at the conclusion. Example:
/* Your comments goes here*/
Adjusting/Setting the Color Property
HTML elements' colours can be changed using the CSS colour attribute. This attribute is
typically used to change an element's background or font colour. Color values are used in CSS to
specify the colour. This parameter can also be used for ornamental effects like border colour. The
color property defines the text color (foreground color in general) of an element. These methods can
be used to specify an element's colour.
Methods Description
The HTML element's colour can be specified using the R, G, and B values that are
in the range of 0 to 255 using the RGB format, which is the abbreviation for "RED,
GREEN, and BLUE". The rgb() parameter is used to specify the colour values for
RGB this format. This property permits three values, each of which can be an integer or a
percentage (range from 0 to 255).
Syntax: tag_name { color: rgb(R, G, B);}
Example: h1{color:rgb (255, 99, 71); text-align:center;}
Except that RGBA contains an A (Alpha) that indicates the element's transparency,
it is virtually identical to the RGB format. The range of alpha values is 0.0 to
1.0, with 0.0 denoting complete transparency and 1.0 denoting complete lack of
RGBA transparency.
Syntax: tag_name { color: rgbA(R, G, B,A);}
Example: h1{color:rgba(255, 99, 71, 0.5); text-align:center;}
The few colour keywords that CSS defines make it simple to declare colour values.
Aqua, black, blue, green, lime, maroon, olive, purple, red, silver, teal, white,
Built-in and yellow are some common colour terms.The names of the colours are case-
Color insensitive.
Syntax: tag_name { color: color_name;}
Example: h1{color:fuchsia; text-align:center;}
Border Property
You can specify the border area of a box that contains an element using the CSS border
attributes. Between a given element's margin and padding, borders are displayed. The border may be
an image or one of several predefined styles, such as a solid line, dotted line, double line, etc.
Each and every displayable element on a web page is made up of one or more rectangular
boxes. Typically, CSS box model explains how these rectangular boxes are organised on a web page.
Every box contains a content area and optional surrounding padding, border, and margin portions.
These boxes can each have different properties & interact with one another in many ways.
The following Figure 4.6 shows how width, height, padding, border, and margin CSS attributes
affect how much room an element can use on a web page.
You can specify the border area of a box that contains an element using the CSS border
attributes. Between a given element's margin and padding, borders are displayed. There are several
predefined border-styles that can be used, including none, hidden, solid, dashed, dotted, double, inset,
outset, groove, and ridge. The width of the border region is specified by the border-width attribute.
The border area's colour is defined by the border-color attribute. In order to style an element's borders
more elegantly, CSS3 introduces two new properties: the border-image property, which adds images
to borders, and the border-radius property, which creates rounded corners without the use of pictures.
To create space around elements, use the CSS margin attributes. The margin attributes control
how much space is left outside the border. For defining the margin on either side of an element, CSS
has the following properties: margin-top, margin-right, margin-bottom, margin-left. The white space
between an element's content and border is specified by the CSS padding attributes. The padding
creates a space around an element's content. For defining the padding on either side of an element,
CSS has the following properties: padding-top, padding-right, padding-bottom, padding-left. For
example,
p{
margin-bottom: 100px;
margin-right: 230px;
margin-left: 80px;
border-top-style: dotted;border: 10px solid transparent;
border-image: url(border.png) 10% round;
padding-top: 20px;
padding-right: 30px;
padding-bottom: 20px;
padding-left: 80px;
}
between characters in a text can be specified using the letter-spacing attribute. The distance between
lines can be set using the line-height attribute. An element's text direction can be changed using the
direction attribute and accepts one of the following values: underline, overline, line-through, and
none. The space between words in a text can be specified using the word-spacing attribute. Example:
p{
font-size: 14px;
color: #9000A1;
line-height: 20px;
background-color: #f0e68c;
text-decoration:overline;
word-spacing: 10px;
text-indent: 50px;
}
CSS Links
An integral component of a website is a link or hyperlink. It enables site navigation for visitors.
Building a user-friendly website therefore requires careful consideration of how to style the links. The
following anchor pseudo-class selections can be used to style the four different states of a link in
different ways.
a:link - specify styles for regular or inactive links.
a:visited - for URLs that the user has already visited, provide styles.
a:hover - create link styles when a user hovers their mouse over them.
a:active - When links are clicked, styles are defined for them.
Sample code: Program to show different link states described above
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Styling Different Link States using CSS</title>
<style>
a:link {color: #000000;
text-decoration: none;
border-bottom: 1px solid;
}
a:visited { color: #ff00ff; }
a:hover { color: #11ffee;
border-bottom: none;
}
a:active {color: #00ffff; }
</style>
</head>
<body>
<p><a href="https://www.cdit.org/" target="_top">TED @ C-DIT</a></p>
</body>
</html>
By paying attention to the left and right margins, for example, they are centred using a wide range
of methods and techniques. margin:auto should be used to horizontally centre a block element. text-
align: center; is used to center the text. Set the left and right margins to auto and turn the image into a
block element to centre it. For aligning elements is to use the float property is also employed. Sample
code is as follows:
.center {
margin: auto;
width: 60%;
border: 3px solid #73AD21;
padding: 10px;
}
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 40%;
}
CSS Position
A good layout design requires that elements be positioned correctly on the web pages. Elements
can be positioned using a variety of CSS techniques. The type of positioning mechanism used for an
element is specified by the position attribute. These can be sticky, absolute, fixed, relative, or static.
An element with the positioning attribute static is always positioned in accordance with the natural
flow of the page and does not require any additional positioning. A component with the positioning
attribute relative is positioned in relation to its default location. Positioned relative to the viewport,
an element with the attribute position: fixed; always remains in the same location regardless of how
far the page is scrolled. The element's position can be adjusted using the top, right, bottom, and
left properties. Positioned relative to the nearest positioned ancestor is an element with the attribute
absolute. Based on the user's scroll position, an element with the property position: sticky is placed.
According on the scroll position, a sticky element can be fixed or relative. Sample code is as follows:
p {width: 100px;
padding: 10px;
}
.up {background: #ee665a;
position: absolute;
top: 0;
}
CSS Gradients
A customizable method for producing seamless transitions between two or more colours is
offered by the CSS3 gradient feature. We previously had to use images to obtain this effect. You
can speed up downloads and use less bandwidth by using CSS3 gradients. Given that the output is
generated by the browser, gradient-containing items can be scaled up or down to any degree without
sacrificing quality. You can exhibit seamless transitions between two or more specified colours using
CSS gradients. CSS identifies three different gradient types: Conic Gradients, Radial Gradients and
Linear Gradients.
You need to define at least two colour stops in order to build a linear gradient. However, you
can define multiple colour stops to produce gradient effects that are more sophisticated. The colours
you want to produce smooth transitions between are colour stops. Additionally, you can specify the
gradient effect's starting point and the direction (or angle) in which it will be applied.
Syntax: background-image: linear-gradient(direction, color-stop1, color-stop2, ...);
Example: .gradient {
width: 800px;
height: 300px;
background: linear-gradient(to right, red, yellow); }
A gradient can also be made in a diagonal direction. In the example that follows, the element's
box will have a linear gradient running from the bottom left corner to the top right corner.
.gradient {
width: 400px;height: 350px;
background: linear-gradient(to top right, green, blue);
}
Instead of using the default keywords, you can set the angle to have more control over the
gradient's direction. Positive angles indicate clockwise rotation, hence the angle 90° provides a
gradient from left to right. The value 0° creates a gradient from bottom to top.The basic syntax for
generating linear gradients using angle is as follows:
linear-gradient(angle, color-stop1, color-stop2, ...)
Example: .gradient {
width: 400px;
height: 300px;
background: linear-gradient(35deg, blue, yellow);
}
Additionally, gradients with more than two colors are possible. You may learn how to make
a linear gradient with several colour stops by looking at the example below. Each colour is evenly
spaced apart.
.gradient { width: 450px;
height: 380px;
background: linear-gradient(blue, lime, olive);
}
Color stops are places along a gradient line where a particular colour will be present. Both a
percentage and an absolute length can be used to specify where a colour stop is. In order to get the
desired result, you can specify as many colour stops as you'd like.
.gradient {
width: 450px;
height: 390px;
background: linear-gradient(red, olive 30%, yellow 60%);
}
Instead of fading from one colour to another in a single direction as with linear gradients,
a radial gradient sees colour emerge from a single spot and smoothly spread outward in a round or
The size of the gradient's final shape is specified by the size argument of the radial-gradient()
function. The closest-side, farthest-side, closest-corner, and closest-corner keywords can be used to
specify size. Example follows:
.gradient {
width: 480px;
height: 370px;
background: radial-gradient(ellipse farthest-side at left bottom, red, yellow, lime);
}
The repeating-radial-gradient() function also allows you to repeat radial gradients. Example:
.gradient {width: 400px;
height: 300px;
background: repeating-radial-gradient(red, pink 10%, lime 20%); }
Transparency is also supported by CSS3 gradients. When stacking numerous backgrounds,
you can utilise this to give background images fading effects.
.gradient {width: 470px;
height: 370px;
background: linear-gradient(to right, rgba(255,255,255,0), rgba(255,200,255,1)),
url("/images/sea.jpg");
}
Principles of Programming and Web Technologies 135
kn Unäv
Introduction to Javascript
In a web page, HTML is used to set up the page's structure, while CSS is used to add styling
features like colors, fonts, etc. However, a web page with simple HTML and CSS is static, meaning
a user cannot fully interact with the page; this is where Javascript comes in. Javascript (JS) is a just-
in-time compiled, object-oriented, cross-platform scripting language. JavaScript runs on the user's
computer rather on the server that hosts the website because it is a client-side scripting language. It
develops dynamic effects for interactive webpages. Programming on the client and server sides can
both be done with Javascript. Features of Javascript:
• JS is a simple scripting language that was designed exclusively for web browser data handling.
The lightweight nature is a great advantage because it is exclusively intended for client-side
execution, specifically for web applications.
• JS allows dynamic typing, meaning that the types of variables are defined based on the value
that has been stored.
• JS is case-sensitive.
• As a result of JavaScript's platform independence, or portability, you can write a script once
and execute it at any time or place.
• JS is an object-oriented programming language which uses prototypes instead of using classes
for inheritance.
• Being an interpreted language, JavaScript processes scripts line by line.
For the creation of interactive webpages, JS is employed. The following uses are its primary focus.
• Validation on the client side.
• A dynamic drop-down menu.
• Displaying the time and date.
136 Principles of Programming and Web Technologies
kn Unäv
<body>
Click here for the result </br>
<input type="button" onclick="firstProgram()" value="First Program" />
</body>
</html>
The script goes in the <body> section of the document if you need it to execute as the page
loads and create content for the page. You wouldn't have any JavaScript-defined functions in this
scenario. Examine the code that follows.
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Welcome to the Programming world")
//-->
</script>
<p>Body of the WEB Page </p>
</body>
</html>
You can combine the <head> and >body> sections to include your JavaScript code.
JS supports primitive and non-primitive datatypes. It also supports operators like arithmetic,
conditional, logical or relational, assignment and comparison operators. Following example program
depicts the operators usage in JS.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var c = true;
var d = false;
var linebreak = "<br />";
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("(a < b) => ");
result = (a < b);
document.write(result);
document.write(linebreak);
result = (typeof b == "string" ? "B is String" : "B is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
document.write("Value of a => (a *= b) => ");
result = (a *= b);
document.write(result);
document.write(linebreak);
document.write("(a ^ b) => ");
result = (a ^ b);
document.write(result);
document.write(linebreak);
document.write("(c && d) => ");
namevalues.displayItems();
document.write("<br />The array in the REVERSED order using reverse() <br />");
namevalues.reverse();
namevalues.displayItems();
document.write("<br />The array after REMOVING the LAST item using pop() <br />");
namevalues.pop();
namevalues.displayItems();
document.write("<br />The array shows the usage of push()<br />");
namevalues.push("New entry");
namevalues.displayItems();
</script>
</head>
<body></body>
</html>
You may run the program and check the output.
Functions in JS
A function is a collection of statements that accept inputs, carry out certain operations, and
output the results. A function is created by grouping together a few actions that are frequently or
repeatedly performed so that we can call it rather than writing the same code over and over again for
various inputs. The function keyword is used to define a JS function, which is then followed by the
function's name and parenthesis (). Function names may also include underscores, dollar signs, and
other characters. Names of parameters may be included in parenthesis and separated by commas.
Curly {} brackets enclose the code that the function will execute. Syntax for defining the function is
as follows:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
// program to print the text declaring a function
function greet(name) {
console.log("Hello " + name + "!!");
}
// variable name can be different
let name = prompt("Enter a name: ");
// calling function
greet(name);
The definition of the function includes a list of function parameters enclosed in parentheses ().
When a function is called, values are passed to it as arguments. The arguments or parameters behave
as local variables within the function. Following code helps you to learn how to call a function and
pass parameters. You may run the code to see the solution
<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var fullname;
fullname= first + " " + last;
return fullname;
}
function secondFunction() {
var result;
result = concatenate('Yadhu', 'Krishna');
document.write (result );
}
</script>
</head>
<body>
<p> Button calls function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
</body>
</html>
Loops in JavaScript
When you need to run the same lines of code again, for a specified number of times, or for as
long as a predefined condition is true, loops are extremely useful. There are 4 types of loops which
JS supports for loop, while loop, do-while loop and for-in loop. We shall look into these now.
for loop :- This loop iterates the elements for the fixed number of times. It should be used only if
number of iteration is known. The syntax is given below.
count++;
}
document.write("Loop ends !");
</script>
</body>
</html>
do---while loop :- This loop iterates the elements for the infinite number of times. This loop will
execute the block of codes once, even before checking whether the condition is true, then it will
repeat the loop as long as the condition remains true. The syntax is given below.
do {
// code block to be executed
}while (condition);
Though very much similar to while loop, the only difference is that in do…while loop, the block of
code gets executed once even before checking the condition. Let's look to an example for the same:
<html>
<body>
<script type = "text/javascript">
var count = 0;
document.write("Loop begins <br />");
do
{
document.write("Current value: " + count + "<br />");
count++;
}while (count < 12)
document.write("Loop ends !");
</script>
</body>
</html>
for-in loop: - The JavaScript for-in loop is used to iterate through an object's properties. If we want to
display the contents of an object during debugging, it can be a great tool. The for-in loop only iterates
across keys that have their enumerable property set to "true" for an object. An object's primary values
consist of four characteristics namely value, writable, enumerable, and configurable. When "true" is
set for Enumerable, we can iterate over that property. The general syntax is given below:
for (let i in obj1) {
// Prints all the keys in object1 on the console
console.log(i);
}
The example given below shows the usage of for-in loop to display all the properties of window
screen object.
<html>
<body>
<script type = "text/javascript">
<!--
var giveProperty;
document.write("Screen Object Properties <br /> ");
for (giveProperty in screen) {
document.write(giveProperty);
document.write("<br />");
}
document.write ("Exiting from the for in loop!");
//-->
</script>
</body>
</html>
You may run the above code and check for the result obtained yourself.
Condition in JavaScript
There could be times when you have to choose one of a given set of options to follow while
creating a program. Use conditional statements in these situations so that your program can make the
right choices and take the appropriate actions. JS provides following conditional statements, which
are used to carry out various operations in response to certain circumstances.
• If you want to tell a block of code to run only if a certain condition is true, use the if statement.
• If the same condition is false, use else to describe a block of code that should be run.
• If the first condition is false, use the else if clause to specify a new condition to test.
• For various different code blocks to be executed, use the switch statement.
The fundamental control statement in JavaScript that enables decision-making and conditional
statement execution is the if statement. The general syntax is:
if (condition) { // statements to execute if true }
A switch statement's goal is to provide an expression for evaluation along with a number of
statements to execute in response to the expression's result. Until a match is found, the interpreter
compares each case against the expression's value. A default condition will be used if none of the
criteria match. General syntax is as follows:
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
:
case condition n: statement(s)
break;
default: statement(s)
}
Run yourself the given example and try to learn the program implementation
<html>
<body>
<script>
let year = 2015, month = 2;
let dayCount;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
dayCount = 31;
break;
case 4:
case 6:
case 9:
case 11:
dayCount = 30;
break;
case 2:
if ((year % 4 == 0 && !(year % 100 == 0)) || year % 400 == 0) {
dayCount = 29;
} else {
dayCount = 28;
}
break;
default:
dayCount = 0; // invalid month
}
document.write(dayCount);
</script>
</body>
</html>
There may be times when you need to exit a loop before getting to the bottom of it. There
may also be instances where you want to ignore a section of your code block and begin the loop's
next iteration. JavaScript has the break and continue statements to address every one of these
circumstances. These statements are used to end any loop immediately or to begin the next iteration
of any loop, as appropriate.
JavaScript Events
An event is defined as a change in an object's state. There are a number of events in HTML
that show when a user or browser performs a certain action. A page load is referred to as an event.
An event also occurs when a user hits a button. The actions of clicking any key, closing a window,
resizing a window, etc. are other examples. JS responds to these events when JS code is embedded
in HTML and permits execution. The act of responding to events is known as event handling. As a
result, JS uses event handlers to handle HTML events. The following Table 4.9 list out various events:
Table 4.9 : List of Events
Event Event Event
Explanation
Name Performed Handler
Key Key down onkeydown Script runs when any key is pressed
Key Pressed onkeypress Script runs when any key is pressed and released
Key Up onkeyup Script runs when any key is released
Dialog box
The alert, confirm, and prompt dialogue boxes are the three types of dialogue boxes that
JavaScript supports. These dialogue boxes can be used to carry out particular functions such generating
an alert, validating an event or input, and requesting user feedback.
The most common function of an alert dialogue box is to issue a warning to users. For instance,
if a text input field requests input from the user but receives none, you may use an alert box to display
a warning message as part of validation. Syntax for writing an alert message is as follows:
alert(message);
Let's look at the following example to demonstrate an alert dialogue box.
<html>
<head>
<script type = "text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
document.write ("You have seen alert dialogue box!");
}
//-->
</script>
</head>
<body>
<p>Lets check what happens when you click the given button </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form>
</body>
</html>
Most often, a confirmation or confirm dialogue box is used to obtain the user's approval for
any option. It shows a dialogue window with the two options OK and Cancel. The window method
confirm() will return true if the user hits the OK button. confirm() returns false if the user clicks the
Cancel button. Let's look at the following example to demonstrate a confirm dialogue box.
<html>
<head>
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
document.write ("Continue!");
return true;
} else {
document.write ("Exit!");
return false;
}
}
//-->
</script>
</head>
<body>
<p> Lets check what happens when you click the given button </p>
<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();" />
</form>
</body>
</html>
When it is necessary to show a text box to request user input, the prompt dialogue box is
used. As a result, it permits communication with the user. Additionally, the prompt dialogue box has
two buttons: OK and Cancel. The user must enter information in the textbox before clicking OK.
The dialogue box reads that value and returns it to the user when they click the OK button. When
the Cancel button is clicked, however, the prompt() method returns null. Let's look at the following
example to demonstrate the usage of prompt dialogue box.
<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var givVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + givVal);
}
//-->
</script>
</head>
<body>
<p>Lets check what happens when you click the given button </p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>
You can insert a line breaker ("\n") to create a break in your chat box message. Sample function
is given below.
function Warn() {
alert ("This is a \n warning message!");
document.write ("You have seen alert dialogue box!");
}
Form Validation
Validation is the process of ensuring that the data provided by the front-end user complies
with the criteria. The server will have to send any missing or wrong data back to the client and ask
them to submit the form again with the right data if it was provided by the client. In most cases, the
server-side validation process transmits the validation information to the front-end user. Both user
and execution time are wasted by this approach. Before submitting the form's data to the server-side,
JavaScript gives us a technique to validate it. In general, validation in forms serves the following two
purposes:
• Basic Validation - The form must first be reviewed to ensure that all of the required fields are
filled in. It would just be necessary to loop through each field in the form and look for data.
• Data Format Validation - Next, the entered data must be examined for accuracy of form and
content. To test the accuracy of the data, your code must have the necessary logic.
The basic form validation verifies the form's required input fields, whether they are filled in or
not. The entered data is checked to make sure it has the right value as part of data format validation.
It verifies if information entered into fields that have already been validated is accurate or not. Let's
look at the example below to further understand the idea of validation.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {
if( document.myForm.Name.value == "" ) {
alert( "Plz enter your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Plz provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Pin.value == "" || isNaN( document.myForm.Zip.value ) ||
document.myForm.Pin.value.length != 5 ) {
alert( "Plz provide a zip in the format #####." );
document.myForm.Pin.focus() ;
return false;
}
if( document.myForm.State.value == "-1" ) {
alert( "Plz choose your state!" );
return false;
}
return( true );
}
//-->
</script>
</head>
<body>
<form action = " " name = "myForm" onsubmit = "return(validate());">
</body>
</html>
The example that follows demonstrates how to verify an entered email address. An email
address must have at least a @ symbol and a dot (.). Additionally, the final dot must appear at least
one character after the '@' symbol and cannot be the initial character of the email address.
<html>
<body>
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
References
1. https://www.techopedia.com/definition
2. https://www.tutorialrepublic.com/
3. Web Development for beginners, White Belt Mastery
4. https://www.tutorialsteacher.com/javascript
5. https://www.kirupa.com/html5/anatomy_css_style_101.htm
Module V
Introduction to PHP and Python Programming
generate dynamic website content, receive and send cookies, and receive input from forms. In addition,
PHP features a large number of hash functions that may be used to encrypt user data, making it safe
and dependable for usage as a server-side scripting language. These are a few of the features of PHP
that make it appropriate for usage as a server-side scripting language. All popular operating systems,
including Windows, Linux, Unix, Mac OS X, and others, can execute PHP. PHP is supported by
almost all of the popular servers still in use today, including Apache.Numerous databases can be used
with PHP. The most crucial aspect is that PHP may be downloaded and used without cost from its
official website, www.php.net. Let’s list few:
• Using the MySQL database, dynamic web applications are created using PHP, a server-side
programming language.
• The website's session monitoring or tracking, database, and dynamic content are all handled
by it.
• In PHP, sessions can be created.
• It has the ability to both set and access cookies.
• Validation and data encryption are helpful.
• Numerous protocols, including HTTP, POP3, SNMP, LDAP, IMAP, and many others are
supported by PHP.
• You can limit who can access certain pages of your website using the PHP programming
language.
• The key factor making PHP the greatest language to learn is how simple it is to instal and
configure.
• PHP is capable of handling forms, such as collecting user data via forms, saving it to a database,
and providing the user with helpful information. The registration form is an example.
Advantages of PHP
• Since PHP was created specifically for the web, it offers several benefits to web development.
• Simple – PHP is a very simple language to learn and use.
• Fast – PHP websites often function quite quickly.
• Stable – Since PHP has existed for a while, it is stable.
• Open-source and free – PHP is open source and cost nothing.
• That basically means that using PHP to create software doesn't require you to pay a licence
price.
• Community support – Whenever you run into a problem, PHP's active online community will
assist you.
Applications of PHP
PHP is one of the most widely used languages on the internet. Some of them are:
• PHP executes system-level operations, which include creating, opening, reading, writing, and
closing files on a system.
• PHP is capable of handling forms, which includes gathering data from files, saving data to a
file, sending data via email, and returning data to the user.
• PHP allows you to create, delete, and alter database elements.
Install PHP
On a web server that supports PHP, scripts are executed. Therefore, you must install the
following programme on your computer before you can begin creating any PHP code.
• The most often used Web server is the open-source Apache Server. PHP is compatible with
almost all Web server software, including Microsoft's Internet Information Server (IIS).
• The PHP engine - A parser must be installed in order to process PHP script instructions and
produce HTML output that can be delivered to the Web Browser.
• The MySQL database server - Although PHP is compatible with almost all database
programmes, including Oracle and Sybase, MySQL is the most often used.
We'll advise you to install the AMP (Apache, MySQL, PHP) software stack in order to install PHP. It
works with all operating systems. Following are a some of the several AMP choices that are currently
available on the industry:
• Windows-based WAMP.
• Linux's LAMP.
• MAMP for Mac - MAMP works well with Apple products. It installs everything you require
for this course, similar to Wampserver.
• The Solaris SAMP.
• FAMP for FreeBSD.
• XAMPP for Cross Platform. The Apache HTTP Server, MariaDB & MySQL databases, and
interpreters for PHP and Perl scripts make up this free and open source cross-platform web
server solution stack bundle created by Apache Friends. XAMPP stands for Cross-Platform
(X), Apache (A), MariaDB & MySQL (M), PHP (P) and Perl (P). Developers may easily build
a local web server for testing and deployment using this straightforward, lightweight Apache
distribution. Other elements like FileZilla, OpenSSL, Webalizer, Mercury Mail, etc. are also
included.
PHP ─ Syntax
PHP syntax refers to the language's defining structure. The PHP script is run on the server, and
the HTML output is transmitted to the browser. Typically, HTML and PHP tags are allowed. This is a
popular general-purpose open-source programming language that can be integrated with HTML. The
".php" suffix is used to save PHP files. Along with standard HTML, PHP programmes can be written
anywhere in the document within PHP tags.
PHP code needs to be distinguished from other page components by the PHP parsing engine.
The method for doing this is referred to as "Escaping to PHP." Four options exist for doing this:
160 Principles of Programming and Web Technologies
kn Unäv
Canonical PHP tags - . The most universally effective PHP tag style is:
<?php...?>
The PHP parser ignores anything not enclosed in an opening and closing tag pair. Delimiters are the
words for the open and closing tags. Each PHP command is followed by a semicolon (;). You can be
certain that your tags will always be appropriately translated if you follow this coding style.
• Short-open (SGML-style) tags - These are the shortest option to initialize a PHP code. 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 php.ini 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. ASP-style tags look like this:
<%...%>
To use ASP-style tags, you will need to set the configuration option in your php.ini file.
HTML script tags - HTML script tags look like this:
<script language="PHP">...</script>
PHP Comments
A comment is just text that the PHP engine skips over. Comments are used to improve
readability of the code. When you update the source code in the future, it might be helpful for you
or another developer to know what you were trying to do using PHP. Both single-line and multi-line
comments are supported by PHP. A single-line comment must begin with either two slashes (//) or a
hash sign (#). For instance:
<?php
// This is a single line comment
# This is also a single line comment
echo "I Love PHP!"; ?>
However, to create multi-line comments, begin the comment with a slash and an asterisk (/*),
and end it with an asterisk and a slash (*/), as in the following example:
<?php
/* This is a multiple line comment block that spans across more than one line */
echo "I Love PHP!"; ?>
Variable in PHP
Data like strings of text, numbers, and other types of data are stored in variables. The values
of variables can alter during a script.
• In PHP, a variable can have a value added to it without first needing to be declared. Depending
on the value of the variable, PHP will automatically convert it to the appropriate data type.
• A variable can be used repeatedly after being declared in the code.
• A variable's value can be assigned using the assignment operator (=). In PHP variable can be
declared as: $var_name = value;
Let’s look into an example:-
<?php // Declaring variables
$txt = "Hello World!";
$number = 10; // Displaying variables value
echo $txt; // Output: Hello World!
echo "\n";
echo $number; // Output: 10 ?>
These are the following rules for naming a PHP variable:
• In PHP, each variable has a $ sign before the variable's name.
• A variable name must begin with a letter or the underscore symbol ( ).
• A variable name cannot begin with a numeric character.
• PHP only allows underscores(_) and alphanumeric characters (A-z, 0-9) in the variable
names.
• Spaces are not permitted in variable names.
Constant in PHP
An identifier or name for a fixed value is a constant. Similar to variables, constants cannot be
altered or undefined after they have been defined (except magic constants). For storing information
that doesn't change while the script is executing, constants are quite useful. These data frequently
take the form of configuration options like the database username and password, the base URL of a
website, the name of the business, etc.
The define() function in PHP is used to define constants. It takes two arguments: the name
of the constant and its value. Once defined, a constant value is always accessible by using its name
alone. As an example, consider the following:
<?php // Defining constant
define("SITE_URL", "https://www.cdit.org/"); // Using constant
echo 'Welcome to - ' . SITE_URL; ?>
echo Statement
One or more strings may be printed using the echo statement. In general, the echo command
can display everything that the browser can display, including strings, numbers, the values of
variables, the output of expressions, etc. You can use echo without parentheses since it is a language
construct and not technically a function unlike an if statement. The parameters must not be enclosed
in parentheses if you want to pass echo more than one parameter.
<!DOCTYPE html>
<html>
<body>
<?php
echo "<h4>Welcome to PHP Programming </h4>";
echo "<h4 style='color: red;'>Welcome to PHP Programming</h4>"; ?>
</body>
</html>
print Statement
To display output to the browser, you can also use the print statement as an alternative to
echo. The language construct print is not a true function, just like echo. In other words, you can use
it without parenthesis like this: print or print (). The only difference between the echo and print
statements is that the print command can only produce one string and always returns 1. Because the
echo statement doesn't return any values, it is thought to be slightly faster than the print statement.
<?php
print "<h4>Welcome to PHP Programming </h4>";
print "<h4 style='color: red;'>Welcome to PHP Programming</h4>"; ?>
Variables can be constructed using these data types. Let's now go into more explanation on each of
them.
Strings- Strings are sequences of characters, where each character corresponds to a single byte.
Anything enclosed in quotations can be a string. You can enclose text in single or double quotes. For
example:
<?php
$a = "Welcome!!!";
$b = 'To the World of PHP Programming';
echo $a;
echo "<br>";
echo $b;
?>
Integers- Whole numbers without a decimal point are integers (..., -2, -1, 0, 1, 2, ...). Rules for
defining integers:
• There must be one digit in an integer.
• A decimal point is not permitted in an integer.
• Positive(+) and negative(-) integers are both acceptable.
• It is possible to specify integers using the following notations: binary (base 2), octal (base 8),
hexadecimal (base 16), and decimal (base 10).
Lets look into a simple example:-
<?php
$a = 123; // decimal number
var_dump($a);
echo "<br>"; # output = int(123)
$b = -123; // a negative number
var_dump($b);
echo "<br>"; # output = int(-123)
$c = 0x1A; // hexadecimal number
var_dump($c);
echo "<br>"; # output = int(26)
$d = 0b11101111; // binary number
var_dump($d);
echo "<br>"; # output = int(239)
$color_codes = array(
"Red" => "#ff0000",
"Green" => "#00ff00",
"Blue" => "#0000ff"
);
var_dump($color_codes); # array(3) { ["Red"]=> string(7) "#ff0000" ["Green"]=> string(7) "#00ff00"
["Blue"]=> string(7) "#0000ff" }
?>
Object- The two basic components of object-oriented programming are classes and objects. An object
is an instance of a class, which serves as a template for objects. An object is a sort of data that not only
allows for the storage of data but also for the information necessary to process that data. A specific
instance of a class that acts as a template for other objects is called an object. By using the new
keyword, objects are produced based on this template. Each object contains attributes and operations
that are identical to those of its parent class. Each instance of an object is totally independent, has its
own set of attributes and methods, and can thus be handled separately from other objects of the same
class. Let’s understand the concept with a simple example given below:
<?php
class Car {
public $color;
public $model;
public $year;
public function __construct($colour, $model, $year) {
$this->colour = $colour;
$this->model = $model;
$this->year = $year;
}
public function message() {
return "My car has colour " . $this->color . " , model is " . $this->model . " & year of purchase " .
$this->year . "!";
}
}
$myCar = new Car("red", "Alto",2010);
var_dump($myCar); # object(Car)#1 (4) { ["color"]=> NULL ["model"]=> string(4) "Alto" ["year"]=>
int(2010) ["colour"]=> string(3) "red" }
echo "<br>";
echo "<br>";
echo $myCar -> message(); # My car has colour , model is Alto & year of purchase 2010!
echo "<br>";
$myCar = new Car("Grey", "Swift", 2012);
echo $myCar -> message(); # My car has colour , model is Swift & year of purchase 2012!
?>
NULL- In PHP, empty variables are represented by the special NULL value. A unique data type called
Null can only have one possible value, which is NULL. A variable of data type NULL is one that
doesn't have a value. A variable is automatically given the value NULL if it is created without a value.
Adding the value NULL to a variable will also empty it. For example,
<?php
$a = NULL;
var_dump($a); # output - NULL
echo "<br>";
$b = "Welcome to the world of PHP Programming!";
$b = NULL;
var_dump($b); # output - NULL
$c = 125;
var_dump($c); # output - int(125)
$c = NULL;
var_dump($c); # output - NULL
?>
Resources- There is no real data type corresponding to the special resource type. It involves the
keeping of a reference to resources and functions outside of PHP. A resource is a unique variable
that keeps track of a reference to an external resource. Special handlers for opened files and database
connections are often stored in resource variables. For example, let’s consider following example:
<?php
// Open a file for reading
$handle = fopen("note.txt", "r");
var_dump($handle); # bool(false)
?>
Operators in PHP
Symbols known as operators are used to direct the PHP processor to carry out specific tasks.
PHP divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
• Conditional assignment operators
Let’s look each of these in detail
Arithmetic Operators- Common arithmetical operations like addition, subtraction, multiplication, etc.
are carried out using the arithmetic operators. The entire list of PHP's arithmetic operators is provided.
Table 5.1 : Arithmetic Operators
<?php
$a= 25;
$b = 6;
echo($a+ $b)."\n"; # output - 31
echo($a- $b)."\n"; # output - 19
echo($a* $b)."\n"; # output - 150
echo($a/ $b)."\n"; # output - 4.166667
echo($a% $b)."\n"; # output - 1
?>.
Assignment operators-To write a value to a variable, these operators are combined with numeric
values.
Table 5.2 : Assignment Operators
<?php
$a= 25;
echo $a; # output - 25
$a+= 30;
echo $a; # output - 55
$a-= 20;
echo $a; # output - 35
$a*= 25;
echo $a; # output - 875
$a/= 10;
echo $a; # output - 87.5
$a %= 15;
echo $a; # output - 12
?>
Comparison Operators- To compare two values, use the PHP comparison operators (number or string).
Table 5.3 : Comparison Operators
<?php
$a= 45;
$b = 65;
$c = "45";
var_dump($a== $c); # output - bool(true)
var_dump($a=== $c); # output - bool(false)
var_dump($a!= $b); # output - bool(true)
var_dump($a!== $c); # output - bool(true)
var_dump($a< $b); # output - bool(true)
var_dump($a> $b); # output - bool(false)
var_dump($a<= $b); # output - bool(true)
var_dump($a>= $b); # output - bool(false)
?>
Incrementing and Decrementing Operators- A variable's value can be increased by using the PHP
increment operators while variable's value can be decreased using the PHP decrement operators.
Table 5.4 : Increment/Decrement Operators
<?php
$a= 25;
echo "Value of x : ", $a; # Output - 25
echo ++$a; # Output - 26
echo $a; # Output - 26
$a = 25;
echo $a++; # Output - 25
echo $a; # Output - 26
$a = 25;
echo --$a; # Output - 24
echo $a; # Output - 24
$a = 25;
echo $a--; # Output - 25
echo $a; # Output - 25
?>
Logical or Relational Operators- Basically, these are applied when working with conditional
statements and expressions. Conditions form the basis of conditional expressions. Additionally, a
condition can be met or not met, therefore the outcome of a conditional statement can be either true
or false. The PHP logical operators are listed below.
Table 5.5 : Relational Operators
and Logical AND $x and $y True if both the operands are true else false
Array Operators- When dealing with arrays, these operators are utilised. Here are the array operators
that PHP offers for array operation, along with their syntax and operations.
Table 5.6 : Array Operators
String Operators-There are two operators for strings. The concatenation operator ('.'), which yields a
concatenation of its right and left parameters, is the first. The second method appends the argument
on the right side to the parameter on the left side using the concatenating assignment operator ('.=').
<?php
// First String
$fname = 'Kendriya';
// Second String
$lname = 'Vidyalaya!';
// Concatenation Of String
$c = $fname." ".$lname; # Outputs - Kendriya Vidyalaya!
echo " $c \n";
// First String
$f_string = 'Welcome to ';
// now $f_string contains "HelloWorld!"
$f_string .= " World of Php Programming!";
echo " $f_string \n"; # Outputs - Welcome to World of Php Programming!
?>
Spaceship Operator- A new spaceship operator (=>) is available in PHP 7 and can be used to compare
two expressions. The combined comparison operator is another name for it. If both operands are
equal, the spaceship operator returns 0, 1 whenever the left operand is greater, and -1 when the right
operand is greater. As seen in the accompanying table, it generally offers three-way comparison.
Table 5.7 : Spaceship Operators
Operator Result
Conditional Statements
When coding, you could reach a moment when a condition must be true in order to obtain
the desired outcomes. We use conditional statements. Statements that can only be carried out if a
specific condition is met are known as conditional statements. Like the majority of programming
languages, PHP enables you to create code that executes various operations based on the outcomes
of comparison or logical test conditions at run time. This implies that you can define test conditions
as expressions that can be either true or false, and depending on the outcome, you can take different
actions. You can use a number of statements in PHP to reach decisions, including:
• The if statement
• The if...else statement
• The if...elseif....else statement
• The switch...case statement
In the sections that follow, we'll look into each of these claims. You have already seen how
conditional statements function in "C" programming. Therefore, we'll merely examine the syntax
here with an example.
1) if statement
With the if statement your code executes only if the condition is true.
Syntax:
if(condition){
// statements
}
Let’s look into a simple example:
<?php
$mark = 350;
if($mark >= 280){
echo "Excellent";
}
?>
2) if...else statements
This conditional sentence is used both when a condition is met and when it is not. This means
that it is used when the condition is either true or false.
Syntax:
if (condition){
//True conditional statements }
else {
//False conditional statements
}
Let’s look into a simple example:
<?php
$gender = 'F';
if ($gender == 'F'){
echo "FEMALE";
}
else {
echo "MALE";
}
?>
3) if...elseif...else statements
Syntax:
if (condition1){
//code 1 to be executed
}
elseif(condition2) {
//code 2 to be executed
}
else{
//code to be executed if above codes are not true
}
Let’s look into a simple example:
<?php
$marks = 75;
if ($marks>79){
echo "A";
}
elseif($marks<=79&& $marks>60) {
echo "B";
}
elseif($marks<=60&& $marks>50) {
echo "C";
}
elseif($marks=50) {
echo "D";
}
else{
echo "F";
}?>
5) Switch Statement
The if...else statement and the switch statement are quite similar. However, a switch statement
is recommended to an if...else when your conditions are complex, such as when you need to check a
condition with many constant values.
Syntax:
switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
,
,
default:
// code to be executed if n doesn't match any constant
}
Let’s look into an example:-
<?php
$gender = 'M';
switch ($gender) {
case 'F':
echo 'F is FEMALE';
break;
case 'M':
echo 'M is MALE';
break;
case 'T':
echo 'T is TRANS-GENDER';
break;
default:
echo 'Invalid choice';
}
?>
Ternary Operator
The if...else sentences can be written quickly using the ternary operator. The question mark
(?) symbol designates the ternary operator, which has three operands: a condition to verify, a result
for true, and a result for false. Consider the following examples to better explain how this operator
functions:
<?php
if($age < 18){
echo 'Child'; // Display Child if age is less than 18
} else{
echo 'Adult'; // Display Adult if age is greater than or equal to 18
}
?>
Using the ternary operator the same code could be rewritten as:
<?php echo ($age < 18) ? 'Child' : 'Adult'; ?>
If the condition evaluates to true (that is, if $age is less than 18), the ternary operator in the
example above selects the value on the left of the colon (i.e., "Child"), and if the condition evaluates
to false (i.e., if $age is greater than 18), it selects the value on the right of the colon (i.e., "Adult").
The null coalescing operator allows us to chain multiple times. In such cases, the operator will
scan from left to right a non-null value. Consider the example given below.
<?php
$theme = $_GET['theme'] ?? $_COOKIE['theme'] ?? 'system-default';
echo "Current theme is: {$theme}"
?>
Loops in PHP
Loops are used to repeatedly run the same piece of code as long as a predetermined condition
is met. A loop's main purpose is to save time and effort by automating the repetitive processes within
a program. Four different loop types are supported by PHP.
• while — until the stated condition evaluates to true, the loop iterates over a block of code.
• do…while — After the code block has been performed once, the condition is assessed. The
statement is repeated if the condition is true for the time that it is true.
• for — until the counter reaches a certain value, it iterates through a block of code.
• foreach — runs a section of code in a loop for every element in an array.
while Loop
As long as the while statement's condition evaluates to true, it will repeatedly loop through a
block of code. .
Syntax:
while(condition){
# Code to be executed
}
The code block will be performed if the test expression is true. The test expression will again
be evaluated after the code has run, and the loop will continue until it is found that the test expression
is false. Let’s look into an example:
<?php
$j = 0;
while ($j < 5){
echo $j + 1 . "<br>";
$j++;
}?>
do…while Loop
Unlike the while loop, the do-while loop evaluates the condition at the end of each loop
iteration.
Syntax:
do{
# block to be executed
}
while(condition);
A do-while loop repeats a statement as long as the supplied condition evaluates to true after
executing a block of code once and before determining if the condition is true. Let’s look into an
example:
<?php
$j = 1;
do{
$j++;
echo "The number is " . $j . "<br>";
}
while($j <= 5);
?>
for Loop
As long as a specific condition is satisfied, the for loop repeats a code block. It is often
employed to run a code block a certain number of times.
Syntax:
for(initialization; condition; increment){
# block to be executed
}
The counter variables are initialised using initialization, which is evaluated once
unconditionally before the first iteration of the loop's body. The condition is assessed at the start of
each repetition. The loop continues and the nested statements are executed if it evaluates to true. The
loop will stop executing if it evaluates to false. The increment adds a new value to the loop counter.
At the conclusion of each repetition, it is evaluated. Let’s look into an example:
<?php
for($j=1; $j<=5; $j++){
echo "The number is " . $j . "<br>";
}?>
foreach Loop
Arrays can be iterated through using the foreach statement.
Syntax 1:
foreach($array as $value){
# block to be executed
}
The array pointer is moved one position for each pass, and the value of the current array
element is assigned to the variable $value before processing the subsequent element. Let’s look into
an example:
<?php
$birds = array("Parrot", "Peacock", "Pigeon", "Penguin");
foreach($birds as $value){
echo $value . "<br>";
}?>
Syntax 2:
foreach($array as $key => $value){
# block to be executed
}
Let's have a look at another associative array looping example. Alphanumeric words are used
as access keys in an associative array.
<?php
$student = array(
"name" => "Vaiga",
"email" => "[email protected]",
"position"=> "s/w engineer",
"company" => "TCS",
"mob"=> 9042345123
);
foreach($student as $key => $value){
echo $key . " : " . $value . "<br>";
}?>
Introduction to Python
is built around objects which combine data and functionality. Particularly when compared to
powerful languages like C++ or Java, Python has a very simple yet incredibly effective OOP
approach.
• Extendable − low-level modules can be added to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
• Databases − provides interfaces to all major commercial databases.
• GUI Programming − facilitates the creation and porting of GUI programs to a variety of
system calls, libraries, and windows platforms, including Windows MFC, Macintosh, and the
X Window system of Unix.
• Scalable − provides a better structure and support for large programs than shell scripting.
• It supports functional and structured programming methods as well as OOP.
• It can be used as a scripting language or can be compiled to byte code for building large
applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with other programming languages like C, C++, COM, ActiveX,
CORBA, .Net, and Java.
Python is surely a powerful and exciting language. It has the right combination of performance
and features which make writing programs in Python both fun and simple. There are two major
Python versions, Python 2 and Python 3 which are quite different.
Programming Basics Terms
• code or source code: The sequence of instructions in a program.
• syntax: The set of legal structures and commands that can be used in a particular programming
language.
• output: The messages printed to the user by a program.
• console: The text box onto which output is printed.
Some source code editors pop up the console as an external window, and others contain their own
console window.
The input() reads a line from the user normally then converts it into a string by removing the trailing
newline, and returns it. If end of file is is read, an exception is raised. The print() function is used
to output data to the standard output device normally to a screen. The actual syntax of the print()
function is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
where,
objects - value(s) to be printed. The sep separator - used between the values. It defaults into
a space character. After all values are printed, end is printed. It defaults into a new line. The file is the
object where the values are printed and its default value is sys.stdout (screen). Lets take a look into
an example:
num=input("Enter a number")
product = eval("5*3")
print("The eval results in the product :", product)
print("Type of product is :", type(product))
print(2,4,6,8,10) # 2 4 6 8 10
print(2,4,6,8,10,sep='*') # 2*4*6*8*10
print(2,4,6,8,10, sep='$',end='&') # 2$4$6$8$10&
Formatting Outputs
If necessary, the output can be formatted with the str.format() method to make it look more
attractive. This method is visible to any string object. This is one of the string formatting methods
that allows multiple substitutions and value formatting. This method through positional formatting
helps to concatenate elements within a string. These operate by inputting a string with one or more
replacement fields and placeholders defined by a pair of curly brackets {} and then calling the str.
format (). The value that needs to be given to the placeholders and that needs to be concatenated
with the string is passed as parameters into the format function. The values can be strings, characters,
floating point constants, integers, or even variables.
x = 15; y = 10
print('The value of x is {} and y is {}'.format(x,y)) # The value of x is 15 and y is 10
print('I love {0} and {1}'.format('cake','ice cream')) # I love cake and ice cream
print('I love {1} more than {0}'.format('cake','ice cream')) # I love ice cream more than cake
The arguments can also be used to format the string. For example:-
print('Hello {name}, {greeting}'.format(greeting = 'Have a nice Day', name = 'friends'))
# Hello friends, Have a nice Day
Python Keywords
Keywords are unique, reserved words with a defined or specific meaning. The name of a
variable, the name of a function, or any other identifier cannot contain a keyword. They are used to
specify the Python language's syntax and structure. Key words in Python are case-sensitive.
Table 5.8: Keywords in Python programming language
False assert del for in or while
None break elif from is pass with
True class else global lambda raise yield
and continue except if nonlocal return
as def finally import not try
To get hold of the up-to-date list, you can open Python shell and run the following commands
as shown in the below snippet.
You can use the function keyword.iskeyword() to determine whether a Python keyword is
valid or not. It returns “True” if the keyword is correct or “False” otherwise. Let's try this with an
example program:-
import keyword
keyword.iskeyword("techs") # False
keyword.iskeyword("try") # True
Python Identifiers
The identifier is the name given to entities like classes, functions, variables, etc. in Python. It helps to
differentiate one entity from another. Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or underscore (_).
2. Names like myClass, var_1, and print_this_to_screen, all are valid examples.
3. An identifier cannot start with a digit, variable is invalid, but variable1 is perfectly fine.
4. Keywords cannot be used as identifiers.
5. We cannot use special symbols like !, @, #, $, %, etc. in our identifier.
6. Identifiers can be of any length.
To check whether a Python identifier is valid or not can be done using str.isidentifier() function.
But it is only available in Python3.0 and onwards. For example:-
'techs'.isidentifier() # True
'1techs'.isidentifier() # False
'techs.com'.isidentifier() # False
'techs_com'.isidentifier() # True
mentioning the data type is not needed. This feature is famously known as dynamic typing. The data
stored in memory can be of many types. Python has various standard data types that are used to define
the operations possible on them and the storage method for each of them. Important data types that
are commonly used in Python are listed below.
• Booleans: A boolean is a data type that almost every programming language has. Boolean in
Python can have two values – True or False. These values are constants and can be used to
assign or compare boolean values.
• Numbers: Numbers are one of the most prominent Python data types.
• Strings: A sequence of one or more characters enclosed within either single quotes ‘ or double
quotes ” is considered a String in Python. Any letter, number, or symbol could be a part of
the string. Python also supports multi-line strings which require a triple quotation mark at the
start and one at the end. The strings in Python are immutable. It means the memory will be
allocated once and re-used thereafter.
• Bytes: The byte is an immutable type in Python. It can store a sequence of bytes (each 8-bit)
ranging from 0 to 255.
• Lists: Python list is an array-like construct that stores arbitrarily typed objects in an ordered
sequence. It is very flexible and does not have a fixed size. Index in a list begins with zero in
Python.
• Tuples: A tuple is a heterogeneous collection of Python objects separated by commas. It means
objects of different data types can co-exist in a tuple.
• Sets: Amongst all the Python data types, the set is one which supports mathematical operations
like union, intersection, symmetric difference, etc. A set is an unordered collection of unique
and immutable objects. Its definition starts with enclosing braces { } having its items separated
by commas inside. Since the set derives its implementation from the “Set” in mathematics, it
can’t have multiple occurrences of the same element.
• Dictionaries: A dictionary in Python is an unordered collection of key-value pairs. It’s a
built-in mapping type in Python where keys map to values. These key-value pairs provide an
intuitive way to store data.
Numbers
The number data types are created when a number is assigned, and they are used to store
numeric values. The values of the numerical objects cannot be modified once they are created since
they are immutable. Python primarily supports two types of numbers: float for decimal values and
int for integers. In contrast to floating point numbers, which represent negative and positive numbers
with fractional parts, integers represent negative and positive numbers without fractional portions.
Python also introduces complex as a new type of number. The complex numbers have a real and
imaginary part in the format a+bj. Look at the following examples:-
# assign the integer to variables and its sum
i1 = 2
i2 = 3
print(i1 + i2) # 5
# assign a decimal number to a variable and its sum
i1 = 8.6
i2 = 6.7
print(i1 + i2) # 15.3
# assign a complex number to a variable and its sum
i1 = (2 + 5j)
i2 = (2 + 3j)
print(i1 + i2) # (4+8j)
Normally Python interprets all integers to be a decimal number. Following can be used to
interpret a number having a base other than 10.
• 0b : zero + lowercase letter 'b'/ uppercase letter 'B' gives a Binary number having a base 2
print(0b10) # 2
print(0b10101) # 21
• 0o : zero + lowercase letter 'o' / uppercase letter 'O' gives a Octal number having a base 8
print(0o10) # 8
print(0o123) # 83
• 0x : zero + lowercase letter 'x'/ uppercase letter 'X' gives a Hexadecimal number having a base 16
print(0x123) # 291
print(0x14) # 20
The type() function can be used to find the class of the defined variables. For examples:
a=100 #create a variable with integer value.
print("type of ", a, " is ", type(a)) # ('type of ', 100, ' is ', <type 'int'>)
c=100+3j #create a variable with complex value.
print("type of", c, " is ", type(c)) # ('type of', (100+3j), ' is ', <type 'complex'>)
Boolean
The Boolean datatype is a primitive datatype having one of two values either True or False.
This is a fundamental data type. Boolean values are the two constant objects False and True. They are
used to represent truth values (other values can also be considered false or true). Examples are given
below:-
x = (1 == True)
y = (1 == False)
192 Principles of Programming and Web Technologies
kn Unäv
a = True + 4
b = False + 10
print("x is", x) # ('x is', True)
print("y is", y) # ('y is', False)
print("a:", a) # ('a:', 5)
print("b:", b) # ('b:', 10)
bool() method is used to return or convert a value to a Boolean value i.e., True or False, using
the standard truth testing procedure.
Syntax:
bool([value])
It's not necessary to pass a value to bool(). Return types include
False if the value is omitted or false
True if the value is true
For example:-
x = []
print(x,'is',bool(x)) # [] is False
x = [0]
print(x,'is',bool(x)) # [0] is True
x = 0.0
print(x,'is',bool(x)) # 0.0 is False
x = None
print(x,'is',bool(x)) # None is False
x = True
print(x,'is',bool(x)) # True is True
x = 'Hello World'
print(x,'is',bool(x)) # Hello World is True
Type Conversion
There may be times when there is a need to specify a type of variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data types,
including its primitive types. Python supports two types of type conversion namely Implicit Type
Conversion and Explicit Type Conversion. In Type Casting loss of data may occur as we enforce the
object to a specific data type.
In Implicit type conversion, there is no need for a programmer to define the casting Python
automatically converts one data type to another data type. For example:-
num_int = 15
num_flo = 1.15
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int)) # ('datatype of num_int:', <type 'int'>)
print("datatype of num_flo:",type(num_flo)) # ('datatype of num_flo:', <type 'float'>)
print("Value of num_new:",num_new) # ('Value of num_new:', 16.15)
print("datatype of num_new:",type(num_new)) # ('datatype of num_new:', <type 'float'>)
In Explicit type conversion, developers convert the data type of an object to required data
type. This type conversion is also called typecasting because the user casts (change) the data type of
the objects.
Syntax :
(required_datatype)(expression)
Casting in Python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float literal (by rounding down
to the previous whole number), or a string literal (providing the string represents a whole
number)
y = int(2.8) # y will be 2
z = int("3") # z will be 3
• float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
• str() - constructs a string from a wide variety of data types, including strings, integer literals
and float literals
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Lets have a look into simple example:-
num_int = 123
num_string = "273"
print("Data type of num_int:",type(num_int)) # ('Data type of num_int:', <type 'int'>)
print("Data type of num_string before Type Casting:",type(num_string))
# Data type of num_string before Type Casting: <class 'str'>
194 Principles of Programming and Web Technologies
kn Unäv
new_num_string = int(num_string)
print("Data type of num_string after Type Casting:",type(num_string))
# Data type of num_string after Type Casting: <class 'str'>
num_sum = num_int + new_num_string
print("Sum of num_int and num_string:",num_sum) # Sum of num_int and num_string: 396
print("Data type of the sum:",type(num_sum)) # Data type of the sum: <class 'int'>
Table 5.9 : Conversion functions
Function Description
int(x) Converts x to an integer
long(x) Converts x to a long integer
Array
A group or set of data elements that are all kept under the same name is an array. Arrays are
unique variables that can store many values organised by index under the same variable name. Any
type of data can be stored in an array, and each element can be assigned a specific value and read
separately. An array consist of Elements and Index. Each item stored in an array is called an element.
The numerical number used to identify each location of an element in an array is known as the
array index. An array can be single dimensional, 2-dimensional or multidimensional. An array can be
created by importing array module in the program as:
import array as arr
arrayName = array(typecode, [Initializers])
The typecode are the codes that are used to define the value type that the array holds. Following
are the values that the type takes
Look into the given example:
import array as arr
a = arr.array('d', [1.1, 3.5, 4.5])
print(a) # array('d', [1.1, 3.5, 4.5])
From a array, elements are accessed by uing the indicies. In array the index starts from 0.
Example for accessing elements from an array is given below :
import array as arr
a = arr.array('i', [2, 4, 6, 8])
print("First element:", a[0]) # First element: 2
print("Second element:", a[1]) # Second element: 4
print("Second last element:", a[-1]) # Second last element: 8
A new element can be inserted into any location of an array using array index. We can insert
new data elements at specific position by using the insert() method and specifying the index.
from array import *
array1 = array('i', [2,4,6,8,10])
print('array before inserting',array1) # array before inserting array('i', [2, 4, 6, 8, 10])
array1.insert(1,20)
print('array after inserting',array1) # array after inserting array('i', [2, 20, 4, 6, 8, 10])
# single/one dimensional array insertion
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
print('array before inserting',T)
T.insert(2, [0,5,11,13,6])
print('array after inserting',T)
for r in T:
for c in r:
print(c,end = " ")
print()
# array before inserting [[11, 12, 5, 2], [15, 6, 10], [10, 8, 12, 5],[12, 15, 8, 6]]
# array after inserting [[11, 12, 5, 2], [15, 6, 10], [0, 5, 11, 13, 6], [10, 8, 12, 5], [12, 15, 8, 6]]
# 11 12 5 2
# 15 6 10
# 0 5 11 13 6
# 10 8 12 5
# 12 15 8 6
The remove() method is used to delete any element from array. Check the given example:
from array import *
array1 = array('i', [10,20,30,40,50])
print('array before deleting',array1)# array before deleting array('i', [10, 20, 30, 40, 50])
array1.remove(40)
print('array after inserting',array1)# array after inserting array('i', [10, 20, 30, 50])
Searching for an array element based on its value or its index is done using index() method.
Look into the given example:
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1.index(40)) # 3
Updation can be carried out by simply reassigning a new value to the desired index that needs
to be updated. Lets have a look to the given example:
from array import *
array1 = array('i', [2,3,6,8,10])
print('array before updating',array1) # array before updating array('i', [2, 3, 6, 8, 10])
array1[1] = 4
print('array after updating',array1) # array after updating array('i', [2, 4, 6, 8, 10])
Python provides a special way to create an array from another array using slice notation. We can
access a range of items in an array by using the slicing operator :. Lets learn with a simple example:
import array as arr
arr = [1,2,3,4,5,6,7]
arr1 = arr[0:3] #start to index 2
print(arr1) # [1, 2, 3]
arr1 = arr[2:] #index 2 to end of arr
print(arr1) # [3, 4, 5, 6, 7]
arr1 = arr[:3] #start to index 2
print(arr1) # [1, 2, 3]
arr1 = arr[:] #copy of whole arr
print(arr1) # [1, 2, 3, 4, 5, 6, 7]
arr1 = arr[1:6:2] # from index 1 to index 5 with step 2
print(arr1) # [2, 4, 6]
Operators in Python
Operators in programming are the constructs that allow you to manipulate an operand to
perform a specific function. They are similar to real life operators, such as arithmetic operators,
greater than, less than, and AND/OR operators, etc. There are 7 types of operators in Python:
• Arithmetic Operators
• Logical Operators
• Assignment Operators
• Comparison Operators
• Bitwise Operators
• Identity Operators
• Member Operators
Arithmetic operators- With this, we can do various arithmetic operations like +, -, *, /, etc. Python
provides multiple ways for arithmetic calculations like eval(), declare variable & calculate, or call
functions
Table 5.11 : Arithemetic Operators
Operator Description Example
Addition (+) Sum of a and b a+b
Subtraction (-) Difference of a and b a-b
Multiplication (*) Product of a and b a*b
Division (/) True Quotient of a and b a/b
Floor division (//) Quotient of a and b, removing fractional parts a // b
Modulus (%) Integer remainder after division of a by b a%b
Exponentiation (**) a raised to the power of b a ** b
Negation (-) The negative of a -a
#create two variables
a=5
b=15
print(a+b) # addition (+) operator, Output → 20
print(a-b) # subtraction (-) operator, Output → -10
print(a*b) # multiplication (*) operator, Output → 75
print(b/a)# division (/) operator, Output → 3.0
print(a%b) # prints the remainder of a/b5, Output → 5
print(a**b) #prints a^b, Output → 30517578125
Logical operators- The logical operators enable us to make decisions based on multiple conditions.
The operands act as conditions that can result in a true or false value.
Table 5.12 : Logical Operators
AND Returns true of the all the conditions are true (o1 and o2) is false
NOT Return the reverse of the actual logical state Not(o1) is false
Bitwise operators- Bitwise Python operators process the individual bits of integer values. They treat
them as sequences of binary bits.
Table 5.14 : Bitwise Operators
~
Bitwise NOT – inverts all of the bits in a single operand ~a
>> Right shift – shifts the bits of ‘a’ to the right by ‘b’ no.
a >> b
of times
<< Left shift – shifts the bits of ‘a’ to the left by ‘b’ no. of
a << b
times
Assignment operators- Assignment operators are used in Python to assign values to variables.
Table 5.15: Assignment Operators
Identity Operators- Identity operators compare the memory locations of two objects. These operators
enable us to compare the memory locations of two Python objects/variables. They can let us find if
the objects share same memory address.
Table 5.16 : Identity Operators
is True if the operands are identical (refer to the same object) x is True
True if the operands are not identical (do not refer to the same
is not x is not True
object)
X = [1, 2, 3, 4, 5]
A=6
print(A in X) # False
print(A not in X) # True
Program for adding two binary numbers
num1 = '00001' # decimal value 1
num2 = '10101' # decimal value 21
sum = bin(int(num1,2) + int(num2,2))
print(sum) #print(0bsum)
but if the test is False, it does nothing. The body of if statement is indicated by the indentation. The
body starts with an indentation and the first unindented line marks the end. Look into the given
example:
if grade == "A+":
print "Congratulations!"
if score < 0 or score > 100:
print "That’s not possible!"
score = input("Enter a correct value: ")
if with else
A Python if else statement takes action irrespective of what the value of the expression is. If
statement can have an optional else part, to be performed if the test result is False.
Syntax:
if Logical_Expression :
Indented Code Block 1
else :
Indented Code Block 2
Look at the given example:
if grade == "A+":
print ("Congratulations!")
else:
print ("You could do so much better.")
print ("Your mother will be disappointed.")
if with elif
The previous two if-else constructs would address at most two outcomes, i.e., True or False.
However, the expression next to the “if” statement can also evaluate to a different value other than the
boolean. It means the if statement can have any number of elif tests
Syntax :
if Logical_Expression_1 :
Indented Code Block 1
elif Logical_Expression_2 :
Indented Code Block 2
elif Logical_Expression_3 :
Indented Code Block 3
else :
Indented Code Block N
Look at the given example:
if grade == "A":
print ("Congratulations!")
elif grade == "B":
print ("That's pretty good.")
elif grade == "C":
print ("Well, it's passing, anyway.")
else:
print( "You really blew it this time!")
Nested if else
Some programs may have a code block under an “if” clause which subsequently has another
conditional block as the first statement. In such a case, nesting of an if-else or if-elif-else inside
another conditional clause is allowed.
Syntax :
if Logical_Expression_1 :
if Logical_Expression_1.1 :
if Logical_Expression_1.1.1 :
Indented Code Block 1.1.1
else
Indented Code Block
elif Logical_Expression_1.2 :
Indented Code Block 1.2
else :
Indented Code Block
elif Logical_Expression_2 :
Indented Code Block 2
elif Logical_Expression_3 :
Indented Code Block 3
...
...
else :
Indented Code Block
Look at the given example:
x = 10
y = 20
z = 30
if x == 10:
print(" Nested If")
if y == 20:
print(" End of Nested If Block ")
else:
print(" End of Nested If-Else Block ")
elif y == 20:
print(" Elif block ")
else:
print(" Nested If")
if z == 30:
print(" End of Nested If Block ")
else:
print(" End of Nested If-Else Block ")
print(" End")
3: wednesday,
4: thursday,
5: friday,
6: saturday,
7: sunday
}
def switch(dayOfWeek):
return switcher.get(dayOfWeek, default)()
print(switch(1)) # monday
print(switch(0)) # Incorrect day
Ternary operator
Python ternary operator is also termed as conditional operator as it can evaluate a statement
with a condition being true or false. There is no special keyword for ternary operator, it’s actually a
way of writing if-else statement that creates a ternary statement or conditional expression.
Syntax :
[when_true] if [condition] else [when_false]
Let’s look into a simple example:
a, b = 10, 20
min = a if a < b else b
print("minimum is ",min) # minimum is 10
max = b if a < b else a
print("maximumm is ",max) # maximumm is 20
It allows to quickly test a condition instead of a multiline if statement. It also allows to
replace simple if statements with a single line expression thereby increases the readability of code by
reducing number of lines of code.
Loops
Different control structures are offered by programming languages, enabling more complicated
execution sequences. We can run a statement or set of statements repeatedly by using a loop statement.
Loops can run a block of code repeatedly until a predetermined condition is satisfied. Python provides
for loops, while loops and nested loops to handle looping requirements. Loop control statements
change execution from its normal sequence. When execution leaves or completes the given scope, all
automatic objects that were created in that scope gets destroyed.
For Loop
A “for” loop is the most preferred control flow statement to be used in any program. It is
best to use when the total no. of iterations required for execution is known. It requires at least two
variables to work. The first is the iterable object such as a tuple, list or a string. And second is the
variable to store the successive values from the loop's sequence.
Syntax:
for iter in sequence:
statements(iter)
The “iter” represents the iterating variable. It gets assigned with the successive values from
the input sequence. The “sequence” may refer to any of the objects such as a list, a tuple or a string.
For example, suppose we have a word and we may need to print each letter of that given word, we
have to use for loop as shown below.
word="spyder"
for letter in word:
print (letter)
Another example:
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print ('Current fruit :', fruit)
# Current fruit : banana
# Current fruit : apple
# Current fruit : mango
An alternative way of iterating through each item is by index offset into the sequence itself.
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
The range() function can produce an integer sequence at runtime. For example, a statement
like range(0, 10) will generate a series of ten integers starting from 0 to 9. Look into the given
example:
for iter in range(0, 3):
print("iter: %d" % (iter))
The “for” loop can also be made to return the index by replacing the sequence with a range(len(seq))
expression. Look at the given example:
books = ['C', 'C++', 'Java', 'Python', 'Perl']
Another function, xrange(), performs the same task as range in loops but range creates the
whole sequence at once, xrange() creates only one number at a time.
Another expression for regulating the flow of loops is continue. If the Python continue
command is found inside a loop while it is being executed, the compiler will halt the current iteration
and start a new one from the beginning. If not, the continue statement is used in a loop to transfer
control to the top of the loop without executing the rest statements inside the loop.
Syntax:
continue:
Let’s have a look to an example:
for x in range(10):
if (x == 4 or x==6 or x==8):
continue
print(x)
When a statement is syntactically necessary but no command or code is to be executed, the
pass statement in Python is used. The pass statement is a null operation; nothing happens when it
executes. The pass is also useful in places where your code will eventually go, but has not been
written yet. The pass statement enables you to handle conditions that are triggered by outside variables
without having any significant impact on the loop; unless a break or other statement is used, the code
will continue to execute as is. The pass statement will, like the other statements, be in the block of
code that follows the if statement and is usually followed by a conditional statement. Let’s have a look
to given example-
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
While Loop
While Loop is used to repeat a block of statements for given number of times, until the given
condition is False.
Syntax:
while some condition (or expression) :
a block of code
For example, suppose we have a word, we need to print each letter of that word.
word="sypder"
pos=0 #initial position is zero
while pos < len(word) :
print (word[pos])
Principles of Programming and Web Technologies 215
kn Unäv
Infinite Loop
A loop becomes infinite loop if a condition never becomes FALSE. If you forgot to increment
or decrement the value inside the while loop then python while loop will execute infinite times .
var = 1
while var == 1 : # Construction of an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
In above example, var is always 1 so while loop statement will go on execute infinite times.
Else Clause with Python While Loop
There is a structural similarity between while and else statement. Both have a block of
statement(s) which is only executed when the condition is true. The difference is that block belongs
to if statement executes once whereas block belongs to while statement executes repeatedly. If the
else statement is used with a while loop, the else statement is executed when the condition becomes
false.
Syntax:
while (expression) :
statement_1
statement_2
......
else :
statement_3
statement_4
......
Let’s have a look to the given example :-
x = 0;
s=0
while (x < 10):
s=s+x
x=x+1
else :
print('The sum of first 9 integers : ', s)
Let’s have a look to the another example :-
# while loop with if-else and break statement
x = 1;
s=0
while (x < 10):
s=s+x
x=x+1
if (x == 5):
break
else :
print('The sum of first 9 integers : ' , s)
print('The sum of 5 numbers is :' ,s)
The continue statement can be used in while loops. It returns the control to the beginning of
the while loop. It rejects all the remaining statements in the current iteration of the loop and moves
the control back to the top of the loop. Let’s have a look to the given example :-
var = 6
while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
Nested Loops
Python programming language allows to use one loop inside another loop. The loop can be
nested that means, one can also write one for loop in between another for loop. While using nested
loops, indentation is to be maintained properly. Below example illustrates python nested for loop.
Principles of Programming and Web Technologies 217
kn Unäv
code. These looping strategies are most beneficial when there is no need to really manipulate the
structure or order the overall container; instead, it is better to print the elements for a specific use case
without changing the container. This can also be used in instances to save time.
Using enumerate(): This function is used to loop through the containers printing the index number
along with the value present in that particular index. Enumerate is built-in python function that takes
input as iterator, list etc and returns a tuple containing index and data at that index in the iterator
sequence. Let’s look to an example -
for key, value in enumerate(['Introduction', 'to', 'Python', 'Programming', 'Language']):
print(key, value)
Using zip(): zip() is used to combine 2 similar containers(list-list or dict-dict) printing the values
sequentially. The loop exists only till the smaller container ends. It uses the shortest length of these
input iterators. Other items of larger length iterators are skipped. In case of empty iterators, it returns
No output. Lets look to a simple a example
questions = ['name', 'colour', 'shape']
answers = ['apple', 'red', 'a circle']
for question, answer in zip(questions, answers):
print('What is your {0}? I am {1}.'.format(question, answer))
Using iteritem(): This function is used to loop through the dictionary printing the dictionary key-
value pair sequentially. Lets look with an example
d = { 'Language ': 'Python', 'Internet Technologies':'PHP', 'Web Tools':'HTML','Database':'SQL'}
print ("The key value pair using iteritems is : ")
for i,j in d.iteritems():
print i,j
Using items() : This function performs the similar task on dictionary as iteritems() but have certain
disadvantages when compared with iteritems(). It is very time consuming. Calling it on large
dictionaries consumes quite a lot of time. It takes a lot of memory. Sometimes takes double the
memory when called on dictionary. Lets look with an example:-
d = { 'Language ': 'Python', 'Internet Technologies':'PHP', 'Web Tools':'HTML','Database':'SQL'}
print ("The key value pair using items is : ")
for i,j in d.items():
print i,j
Using sorted(): This function is used to print the container is sorted order. It doesn’t sort the container,
but just prints the container in sorted order for 1 instance. Use of set() can be combined to remove
duplicate occurrences. Lets look to a simple example:-
lis = [ 1 , 3, 5, 6, 2, 1, 3 ]
print ("The list in sorted order (without duplicates) is : ")
for i in sorted(set(lis)) :
print (i)
The list in sorted order (without duplicates) is :
Using reversed(): This function is used to print the values of container in the descending order as
declared. Lets look to a simple example:-
lis = [ 1 , 3, 5, 6, 2, 1, 3 ]
print ("The list in reversed order is : ")
for i in reversed(lis) :
print (i)
Strings
Strings are a sequence of characters and are amongst the most popular types in Python. Python
does not have a character data type, a single character is simply a string with a length of 1. Square
brackets can be used to access elements of the string. Python treats single quotes the same as double
quotes. Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
In Python, Strings are objects, and the language comes with a variety of built-in and library
functions. String in single quotes cannot hold any other single quoted character in it otherwise an
error arises because the compiler won’t recognize where to start and end the string. Use of double
quotes is suggested to avoid this problem because it makes it easier to create strings with single
quotes inside of them. For strings which contain Double quoted words in them, use of triple quotes is
suggested. Along with this, triple quotes also allow the creation of multiline strings. For example −
String1 = ''' I'm studying
Python
programming languge '''
print(" Multiple lines ")
print(String1)
# Multiple lines
# I'm studying
# Python
# programming languge
Accessing characters
Individual characters of a String can be accessed by using the concept of Indexing. Python
allows to index from the zeroth position in Strings. But it also supports negative indexes. Index of
‘-1’ represents the last character of the String , -2 refers to the second last character and so on. While
accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed
as an index, float or other types will cause a TypeError.
P Y T H O N - P R O G R A M M I N G
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
-18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Modify/Delete a String
Python Strings are by design immutable. It suggests that once a String binds to a variable; it
can’t be changed or modified. The updation or deletion of any characters from a String is not allowed.
This will cause an error as the item assignment or item deletion from a String is not supported.
Although deletion of entire String is possible with the use of a built-in del keyword. If you want to
update the String simply re-assign a new String value to the same variable. For example :
var = "Hello World"
print("Initial value : " +var) # Initial value : Hello World
var = "Welcome to the world of Python"
print("\nUpdated value: " + var) # Updated value : Welcome to the world of Python
del var
print("\n Deleted value: " + var) # NameError: name ‘var’ is not defined
The method replace() returns a copy of the string in which the values of old string have been
replaced with the new value. Example :
old_string = 'I like flowers'
Principles of Programming and Web Technologies 221
kn Unäv
rfind(str[,i [,j]]) This is same as find() just that this var=’This is an example’
function returns the last index where str=’an’
‘str’ is found. If ‘str’ is not found it print (var.rfind(str,0,10)) # 8
returns ‘-1’. print (var.rfind(str,10)) # -1
splitlines(num) Splits the String at line breaks and var=’Print new line\nNextline\n\
returns the list after removing the linenMove again to new line’
breaks. print (var.splitlines())
where, # [‘Print new line’, ‘Nextline’, ”,
num = if this is positive value. ‘Move again to new line’]
It indicates that line breaks to be print (var.splitlines(1))
included in the returned list. # [‘Print new line\n’,
‘Nextline\n’, ‘\n’, ‘Move again
to new line’]
join(seq) Returns a String obtained after seq=(‘ab’,’bc’,’cd’)
concatenating the sequence ‘seq’ with str=’::’
a delimiter string. print (str.join(seq))
where, seq= sequence of elements to # ab::bc::cd
be joined
lstrip([chars]) Returns a String after removing the var=’ This is an example ‘
characters from the beginning of the print (var.lstrip())
String. # This is an example
where, var=’***This is an example***’
Chars=this is the character to be print (var.lstrip(‘*’))
trimmed from the String. Default is # This is an example***
whitespace character.
rstrip() Returns a String after removing the var=’ This is an example ‘
characters from the End of the String. print (var.lstrip())
where, # This is an example
Chars=this is the character to be var=’***This is an example***’
trimmed from the String. Default is print (var.lstrip(‘*’))
whitespace character. # ***This is an example
rindex(str[,i [,j]]) Searches for ‘str’ in complete var=’This is an example’
String (if i and j not defined) or in str=’is’
a sub-string of String (if i and j are print (var.rindex(str,0,10))
defined).This function returns the last # 5
index where ‘str’ is found. print (var.rindex(str,10))
If ‘str’ is not found it raises #Traceback (most recent call
‘ValueError’ exception.where, last):
i=search starts from this index # File "<stdin>", line 1, in
j=search ends at this index. <module>
#ValueError: substring not found
len(string) Returns the length of given String var=’This is an example’
print (len(var))
# 18
decode(encoding='UTF- Decodes the string using the codec var='This is an example' new_
8',errors='strict') registered for encoding. encoding var=var.encode('base64','strict')
defaults to the default string print "var = "+var
encoding. # var = This is an example
print "new var ="+new_var
# new var
=VghpcyBpcyBhbiBleGFtcGxl
%c character
%o octal integer
List
List is one of the simplest and most important data structures in Python. Lists are enclosed in
square brackets [ ] and each item is separated by a comma. LA list is a grouping of things, where each
item has a unique index value. A list's contents can be altered since it is mutable. Lists are not only
used for iterating through data, but they are also a popular data storage and categorization method
used for handling data as a program is running. These are very flexible and have many built-in control
functions. A list in Python, also known as a sequence, is an ordered collection of objects. Any form of
object can be hosted by it, including nested lists, strings, numbers, and letters. Every element rests at
Principles of Programming and Web Technologies 229
kn Unäv
some position (i.e., index) in the list. The index can be used later to locate a particular item. The first
index begins at zero, next is one, and so forth.
Creating Lists
To build a list, just put some expressions in square brackets.
Syntax:
lst1 = [ ] # blank list
lst2 = [expression1 , …. , expression_N]
You may look at the given example : -
# list of strings
lst1 = [“Python”, “Java”, ”Perl”, ”C”];
# list of integers
lst2 = [1993, 2016];
# List of heterogenous data types
lst3 = [2, 4, 6, ‘Java’, ‘Python’, ‘C’, 4.5];
Slicing Lists
Slicing of list can be done as strings. It is done by specifying a start and end point. It is done
by specifying the first index to include in the slice followed by the index to stop before. Slicing a list
results in a new shorter list.
Syntax :
[start(optional):stop(optional):step(optional)]
You may look at the given example :
prog_lang=['Basic','C','C++','Java','Perl','Python','VB','.NET']
print( prog_lang) # ['Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'VB', '.NET']
p_lang=prog_lang[:3]
print (p_lang) # ['Basic', 'C', 'C++']
p_lang =prog_lang[1:5]
print (p_lang) # ['C', 'C++', 'Java', 'Perl']
If the stop value is missing, then it indicates to perform slicing to the end of the list. It saves
us from passing the length of the list as the ending index. You may go through the given example :-
p_lang =prog_lang[4:]
print( p_lang) # ['Perl', 'Python', 'VB', '.NET']
p_lang =prog_lang[4:-1] # negative stop value ‘-1’ would mean the same as “length minus one.”
print (p_lang) # ['Perl', 'Python', 'VB']
Reverse a Python list using the slice operator. You may look at the given example :
num_list=[1,2,3,4,5,6,7,8,9,10]
n_list=num_list[::-1] # directs to traverse the list in the backward direction by 1.
print (num_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print (n_list) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
n_list=num_list[::-2] # skip every second member by setting the iteration to ‘-2’
print (n_list) # [10, 8, 6, 4, 2]
The items can be removed by assigning a blank list with a slice of its elements. Given example
demonstrates this:-
vowels = ['a','e','i','o','u']
vowels[2:3] = []
print(vowels)
# ['a', 'e', 'o', 'u']
vowels[2:5] = []
print(vowels)
# ['a', 'e']
If you wish to sort in descending order, then refer the below example.
vowels = ['a','e','i','o','u']
vowels.sort(reverse=True)
print(vowels)
# ['u', 'o', 'i', 'e', 'a']
List Comprehension
It helps in constructing lists in a completely natural and easy way. A list comprehension has
the following syntax:
Syntax :
theList = [expression(iter) for iter in oldList if filter(iter)]
It has square brackets grouping an expression followed by a for-in clause and zero or more if
statements. You can go through the example given below :-
num_list=[1,2,3,4,5,6,7,8,9,10]
num_list = [iter for iter in range(5)]
print (num_list)
# [0, 1, 2, 3, 4]
num_list = [iter for iter in range(8)]
print (num_list)
# [0, 1, 2, 3, 4, 5, 6, 7]
prog_lang=['Ada', 'Basic', 'C++', 'Java', 'Perl', 'Python', 'Fortrab','Cobol', 'Ruby']
firstLetters = [ programming[0] for programming in prog_lang ]
print(firstLetters)
# ['A', 'B', 'C', 'J', 'P', 'P', 'F', 'C', 'R']
Method Description
append() It adds a new element to the end of the list.
extend() It extends a list by adding elements from another list.
insert() It injects a new element at the desired index.
remove() It deletes the desired element from the list.
pop() It removes as well as returns an item from the given position.
clear() It flushes out all elements of a list.
index() It returns the index of an element that matches first.
count() It returns the total no. of elements passed as an argument.
sort() It orders the elements of a list in an ascending manner.
reverse() It inverts the order of the elements in a list.
copy() It performs a shallow copy of the list and returns.
Function Description
all() It returns True if the list has elements with a True value or is blank.
any() If any of the members has a True value, then it also returns True.
enumerate() It returns a tuple with an index and value of all the list elements.
len() The return value is the size of the list.
list() It converts all iterable objects and returns as a list.
max() The member having the maximum value.
min() The member having the minimum value.
sorted() It returns the sorted copy of the list.
sum() The return value is the aggregate of all elements of a list.
Multidimensional Lists
Even though, the lists are used to hold data, they are also be used to categorize it. Values inside
a list can be further broken down into other sets. You can go through the example given below : -
# Two Dimensional list
n_sets = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
print (n_sets) # [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
print(n_sets[1]) # [3, 6, 9, 12, 15]
print(n_sets[0][1]) # 4
# Three Dimensional list
n_sets = [[[1, 2, 3, 4],[5, 6, 7, 8,],[9, 10, 11, 12],], [[13, 14, 15, 16],[17, 18, 19, 20],[21, 22, 23, 24]],
[[25, 26, 27, 28], [29, 30, 31, 32], [33, 34, 35, 36]]]
print(n_sets[0][1][2]) # 7
# Three dimensional list consisting of one list holding a single list which also holds only a single list
n_sets = [[[[1, 2],[3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], [[[13, 14], [15, 16]], [[17, 18], [19, 20]],
[[21, 22], [23, 24]]], [[[25, 26], [27, 28]], [[29, 30], [31, 32]], [[33, 34],
[35, 36]]]]
print(n_sets[0][1][1][1]) # 8
All the methods that holds true for single dimensional list holds true for multidimensional list
also. Let’s look with an example :-
# appending elements to multidimensional list
n_sets = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
n_sets.append([5, 10, 15, 20, 25])
print(n_sets) # [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]
Sets
A set is collection type which can store elements of different data types but doesn’t index
them in a particular order. The elements don’t have a specific order, hence exist in a random style.
Since each item in a set is unique, there cannot be any duplicates. Since the elements are immutable,
once they are inserted, alterations cannot be made. set is itself mutable and allows addition or deletion
of items. Frozen sets are immutable objects that only support methods and operators that produce a
result without affecting the frozen set or sets to which they are applied.
Creating a Set
A set is created by placing all the elements inside curly braces {}, separated by comma or by
using the built-in function set(). It can have any number of items and they may be of different. But a
set cannot have a mutable element, like list, set or dictionary, as its element. Let’s take an example:-
# create a set of numbers
set_num = {3, 7, 11, 15}
print(set_num) # set([7, 3, 11, 15])
# create a set using the set() method & creating set with a fixed set of elements
set_mix = set([11, 1.1, "11", (1, 2)])
print(set_mix) # set(['11', (1, 2), 11, 1.1])
Modifying a Set
Sets are mutable. But since they are unordered, indexing have no meaning. Its elements cannot
be changed by accessing through an index or via slicing. Set methods like the add() which adds a
single element and the update() which can add more than one item can be used. If the element already
exists, the add() method does not add the element. The update() method can even accept tuples, lists,
strings or other sets as an argument. But, duplicate elements will automatically get excluded. Let’s
take an example:-
my_set = {1,3}
print(my_set) # set ([1, 3])
# add an element
my_set.add(2)
print(my_set) # set ([1, 2, 3])
# add multiple elements
my_set.update([2,3,4])
print(my_set) # set [1, 2, 3, 4])
# add list and set
my_set.update([4,5], {1,6,8})
print(my_set)
# set ([1, 2, 3, 4, 5, 6, 8])
# demonstrate differences between normal and frozen set Same as {"a", "b","c"}
normal_set = set(["a", "b","c"])
# Adding an element to normal set is fine
normal_set.add("d")
print( "Normal Set :: ", normal_set)
# Normal Set :: set(['a', 'c', 'b', 'd'])
# A frozen set
frozen_set = frozenset(["e", "f", "g"])
print( "Frozen Set :: " , frozen_set)
# Frozen Set :: frozenset(['e', 'g', 'f'])
# trying to add element to frozen set
frozen_set.add("h")
# Traceback (most recent call last):
Deleting a Set
To remove an item in a set, use the remove(), or the discard() method. The only difference
between the two is that, while using discard() if the item does not exist in the set, it remains unchanged.
But remove() will raise an error in such condition. Let’s take an example:-
# discarding “a”
x = {"a","b","c","d","e"}
x.discard("a")
print(x) # set(['c', 'b', 'e', 'd'])
# discarding “z’, set remains unchanged
x.discard("z")
print (x) # set(['c', 'b', 'e', 'd'])
# removing of element
x = {"a","b","c","d","e","f","h"}
x.remove("a")
print(x) # set(['c', 'b', 'e', 'd', 'f', 'h'])
# error message while removing element not in set
set(['c', 'b', 'e', 'd'])
x.remove("z")
print( x)
# Traceback (most recent call last):
# File "C:/Users/jisha/Desktop/b.py", line 13, in <module>
# x.remove("z")
# KeyError: 'z'
The pop() method is also used to remove an element. Since Set doesn’t use indexing, it
will randomly select one element and removes it from the set. The clear() method is used to flush
everything from the set. The del keyword will delete the set completely. Let’s take an example:-
# pop()
x = {"a","b","c","d","e","f","h"}
x.pop() # removes any element from the set
240 Principles of Programming and Web Technologies
kn Unäv
n = {1, 2, 3, 4}
returns a shallow copy of the set. A set new_n = n.copy()
can be copied using = operator print('numbers: ', n)
copy()
Syntax: # ('nums: ', set([1, 2, 3, 4]))
set.copy() print('new_n : ', new_n)
# ('new_n : ', set([1, 2, 3, 4]))
x = {"a","b","c","d","e"}
Removes the items in this set that are
y = {"b","c"}
also included in another, specified set.
difference_ print x.difference_update(y)
update() # None
Syntax:
x=x-y
set.difference_update(set)
print x # set(['a', 'e', 'd'])
x = {"a","b","c","d","e"}
Returns a set that contains the similarity
y = {"b","c"}
between two or more sets.
Intersection() z = x.intersection(y)
Syntax:
print (z) # set(['c', 'b'])
set.intersection(s1,s2…sn)
Dictionary
A dictionary is a collection of key-value pairs that is not ordered otherwise dictionary is
collection of unordered pairs. It is generally used when we have a huge amount of data. Dictionaries
are optimized for retrieving data. Key-value pairs are stored in dictionaries. Key value is provided in
Principles of Programming and Web Technologies 243
kn Unäv
the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon:,
whereas each key is separated by a ‘comma’. Keys of a Dictionary must be unique and of immutable
data type such as Strings, Integers and tuples, but the key-values can be repeated and be of any type.
Dictionaries are defined within curly braces {} with each item being a pair in the form key:value. Key
and value can be of any data type.
Creating a Dictionary
A Dictionary can be created by placing sequence of elements within curly {} braces, separated
by ‘comma’. Dictionary can also be created by the built-in function dict(). An empty dictionary can
be created by just placing to curly braces {}.
# creating an empty Dictionary
Dict = {}
# Creating a Dictionary with Integer Keys
Dict = {1: 'Perl', 2: 'Python', 3: 'Java'}
# Creating a Dictionary with Mixed keys
Dict = {'Name': 'Perl', 1: [1, 2, 3, 4]}
# Creating a Dictionary with dict() method
Dict = dict({1: 'Perl', 2: 'Python', 3: 'Java'})
# Creating a Dictionary with each item as a Pair
Dict = dict([(1, 'Java'), (2, 'Perl')])
Updating/Modifying a Dictionary
Addition of elements can be done in multiple ways. One value at a time can be added to
a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing
value in a Dictionary can be done by using the built-in update() method. Nested key values can also
be added to an existing Dictionary. While adding a value, if the key value already exists, the value
gets updated otherwise a new Key with the value is added to the Dictionary. Let’s look to a simple
example:-
dict = {'Name': 'Krishna', 'Roll No.': 12, 'Subject': 'Malayalam'}
print (dict) # {'Roll No.': 12, 'Name': 'Krishna', 'Subject': 'Malayalam'}
# Updating entry
dict['Roll No.'] = 9;
print (dict )# {'Roll No.': 9, 'Name': 'Krishna', 'Subject': 'Malayalam'}
# Adding an element
dict['Class'] = 'First';
print (dict) # {'Roll No.': 12, 'Class': 'First', 'Name': 'Krishna', 'Subject': 'Malayalam'}
Using pop()
Syntax :
dict.pop(key, def)
where,
key: The key whose key-value pair has to be returned and removed.
def : The default value to return if specified key is not present.
Returns:
Value associated to deleted key-value pair, if key is present.
Default value if specified if key is not present.
KeyError, if key not present and default value not specified.
# {'A': {1: 'Python', 2: 'Programming', 3: 'Language'}, 'B': {1: 'Python', 2: 'Language'}, 6: 'To', 7:
'World', 8: 'Of', 9: 'Python'}
clear() removes all items from the dictionary. dict1 = {1: 'a', 2:'e' };
Syntax: dict1.clear () # {'}
dict.clear()
values() Returns a list of all the values available in a dict1 = {1: 'a', 2:'e' };
given dictionary. dict1.values() # ['a', 'e']
items() Returns a list of dict’s (key, value) tuple pairs dict1 = {1: 'a', 2:'e' };
Syntax: dict1.items() # [(1, 'a'), (2, 'e')]
dict.items(key)
type() Returns the type of the passed variable dict1 = {1: 'a', 2:'e' };
Syntax: type(dict1) # <type 'dict'>
type()
keys() Returns list of dictionary dict’s keys. dict1 = {1: 'a', 2:'e' };
Syntax: dict1.keys() # [1, 2]
dict.keys()
setdefault() Returns the key value available in the dict = {1: 'a', 2: 'e'}
dictionary and if given key is not available print "Value : %s" % dict.
then it will return provided default value. setdefault(2, None)
Syntax: # Value : e
dict.setdefault(key, default=None) print "Value : %s" % dict.
where setdefault(4, None)
key − This is the key to be searched. # Value : None
default − This is the Value to be returned in
case key is not found.
cmp() Compares elements of both dict. dict1 = {1: 'a', 2: 'e'}
Syntax: dict2 = {1: 'a', 3: 'o'}
cmp(dict1, dict2) dict3 = {1: 'a', 2: 'e'}
where cmp(dict1,dict2) # -1
dict1 − This is the first dictionary to be cmp(dict1,dict3) # 0
compared with dict2. cmp(dict2,dict1) # 1
dict2 − This is the second dictionary to be
compared with dict1.
This method returns 0 if both dictionaries are
equal, -1 if dict1 < dict2 and 1 if dict1 > dict2
len() Gives the total length of the dictionary. This dict = {1: 'a', 2: 'e'}
would be equal to the number of items in the len(dict)
dictionary. #2
Syntax:
len()
str() Returns a printable string representation of a dict = {1: 'a', 2: 'e'}
dictionary. str(dict)
Syntax: # "{1: 'a', 2: 'e'}"
str()
Tuple
A Python tuple is a collection type data structure which is immutable and holds a sequence of
heterogeneous elements. It functions almost like a list but with the following distinctions.
Tuples store a fixed set of elements and don’t allow changes whereas the list has the provision to
update its content.
The list uses square brackets for opening and closing whereas, and a tuple has got parentheses for the
enclosure.
Elements of the tuple must have a defined order. Tuple also has the same structure where the
values are separated by commas
The simplest is the direct access method is by using the index operator [] to pick an item from
the tuple. The indexing from the 0th position. The index is always an integer. Violating the boundaries
of a tuple will result in an IndexError. Trying a float or any other form of numbers for the indexing
purpose result in TypeError.
# Accesing a single value from a tuple
prog_lang=('Ada', 'Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'VB', '.NET', 'Basic', '.Net')
print("Length:", len(prog_lang)) # ('Length:', 11)
# Indexing the fourth element
print(prog_lang[3]) # C++
# Indexing the last element
print("prog_lang[length-1]:", prog_lang[len(prog_lang) - 1])
# ('prog_lang[length-1]:', '.Net')
# reverse indexing
print("prog_lang[-3]:", prog_lang[-3])
# ('prog_lang[-2]:', 'Basic')
# Print values from tuple between 2 and 5
prog_lang=('Ada', 'Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'VB', '.NET', 'Basic', '.Net')
print(prog_lang[2:5])
# ('C', 'C++', 'Java')
# Indexing a non-existent member will raise the IndexError
try:
print(prog_lang[len(prog_lang)+1])
except Exception as ex:
print("prog_lang[length+1] Error:", ex)
# ('prog_lang[length+1] Error:', IndexError('tuple index out of range',))
print(prog_lang[0.0])
except Exception as ex:
print("prog_lang[0.0] Error:", ex)
# ('prog_lang[0.0] Error:', TypeError('tuple indices must be integers, not float',))
# accessing elements that appears after counting five from the rear end
print (prog_lang[:-5])
# ('Ada', 'Basic', 'C', 'C++')
# accessing five elements from the rear
print (prog_lang[-5:])
# ('Java', 'Perl', 'Python', 'VB', '.NET')
# accessing elements from the start to end
print (prog_lang[:])
# ('Ada', 'Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'VB', '.NET')
Modifying/Updating A Tuple
Since tuple is immutable, modification is not possible. But changing the elements instead of
directly modifying the tuple is possible. You may look to the given example:-
num_tuple = (22, 33, 55, 66, [88, 99])
print(" before modificaton:", num_tuple)
# (' before modificaton:', (22, 33, 55, 66, [88, 99]))
# Change the values of mutable elements inside the tuple i.e. list
num_tuple[4][0] = 77
num_tuple[4][1] = 88
print("after modificaton:", num_tuple)
# ('after modificaton:', (22, 33, 55, 66, [77, 88]))
prog_lang=('Python Programming', )
prog_lang=prog_lang*3
print(prog_lang)
# ('Python Programming', 'Python Programming', 'Python Programming')
Deletion Operation
Tuple doesnot support deletion of a single element but entire tuple can be deleted using the
del(). You may look to the given example:-
del (prog_lang1[2])
# Traceback (most recent call last):
# File "C:/Users/jisha/Desktop/b.py", line 18, in <module>
# del (prog_lang1[2])
# TypeError: 'tuple' object doesn't support item deletion
del (prog_lang1)
print prog_lang1
## Traceback (most recent call last):
# File "C:/Users/jisha/Desktop/b.py", line 20, in <module>
# print prog_lang1
# NameError: name 'prog_lang1' is not defined
Comparison Operations
The comparison starts with a first element of each tuple. If they do not compare to =,< or >
then it proceed to the second element and so on. You may look to the given example:-
a=(5,6)
b=(1,4)
if (a>b):print("a is bigger")
else: print("b is bigger")
# a is bigger
References
Abbreviation
1D : One Dimensional
2D : Two Dimensional
JS : JavaScript
PC : Program Counter