0% found this document useful (0 votes)
3 views

PROGRAMMING

This document is a study material prepared by the Centre for Development of Imaging Technology, focusing on principles of programming and web technologies. It includes modules on programming basics, C programming, web programming, and introduces PHP and Python. The material is designed for educational purposes and encourages user feedback for future improvements.

Uploaded by

adhilahamed2000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

PROGRAMMING

This document is a study material prepared by the Centre for Development of Imaging Technology, focusing on principles of programming and web technologies. It includes modules on programming basics, C programming, web programming, and introduces PHP and Python. The material is designed for educational purposes and encourages user feedback for future improvements.

Uploaded by

adhilahamed2000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 256

kn Unäv

CENTRE FOR DEVELOPMENT OF IMAGING TECHNOLOGY


(Under Government of Kerala)

TECHNOLOGY EXTENSION DIVISION


Ground Floor, TC 26/322 (3), Chittezham Lavanya, Behind SMSM Institute
Statue, Thiruvananthapuram - 695 001
Phone Number 0471- 2321360, 2322100
Website :www.tet.cdit.org
E-mail: [email protected]

principles of programming
and web technologies

STUDY MATERIAL
Version 1

For Private Circulation Only


Study Material
Printed on 2023
by
CENTRE FOR DEVELOPMENT OF IMAGING TECHNOLOGY
(Under Government of Kerala)

C-DIT – Head Office


Chithranjali Hills, Thiruvallam P.O.,
Trivandrum - 695027.
Ph: 0471-2380910, 2380912
E-mail:[email protected]
Web:www.cdit.org

©
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

This course material has been prepared with a broad


perspective by a team of Industry and Academic experts in tune with
the latest industry requirements and trends. This book is designed to
be the clear, concise, normative reference to Programming Principles
and Web Technologies.
The chapters are designed to help you understand and grasp
the concepts related to the subject matter. We hope that you find this
material informative and useful in your studies. Please note that this
material should not be considered a substitute for your coursework
or required reading. We encourage you to actively engage with the
material and seek additional resources as needed. We have included
various exercises and activities to help reinforce the concepts
discussed and encourage active engagement.
We request every user of this course material to send the
feedback to us. The suggestions and opinions of the users will serve
as a guideline for future modifications and improvements.
Contents

Sl.No. Subjects Page No.

1 Module I - Basics of Programming 07

2 Module II - Introduction to C Programming 31

3 Module III - C Programming: Arrays and Functions 64

4 Module IV - Web Programming: HTML, CSS and JavaScript 94

5 Module V - Introduction to PHP and Python Programming 157

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:

Figure 1.1 : Dataflow of an Algorithm


• Problem: A real-world problem or a real-world instance problem for which you need to create
a programme or a set of instructions.
• Algorithm: Designed for a problem which is a step by step procedure.
• Input: Once an algorithm has been created, the required and preferred inputs are provided to
the algorithm.
• Processing unit: The processing unit will receive the input and produce the desired output.
• Output: The output of a programme is referred to as its result or outcome.

What Makes a Good Algorithm?


• It's important to define input and output precisely.

Principles of Programming and Web Technologies 7


kn Unäv

• The algorithm's steps should all be distinct and unambiguous.


• The most efficient technique to tackle a problem should be an algorithm.
• Computer code shouldn't be used in an algorithm. Instead, the algorithm should be written so
that it may be applied to many programming languages.

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.

8 Principles of Programming and Web Technologies


kn Unäv

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.

Principles of Programming and Web Technologies 9


kn Unäv

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

How can an algorithm be expressed?


• Natural Language: Here, we use common English to express the algorithm. To comprehend
the algorithm from it would be too difficult.
• Flow Chart: In this case, we depict the algorithm graphically or visually. Compared to Natural
Language, it is simpler to understand.
• Pseudo Code: In this case, we represent the algorithm in the form of annotations and educational
text written in simple English that closely resembles genuine code, but because it lacks any
syntax resembling a programming language, it cannot be built or understood by a computer.
It is the greatest technique to convey an algorithm because even a normal person with basic
programming expertise can understand it.

Example 1: Agorithm to find the average of 5 subjects.
Step 1: Start
Step 2: Read 5 Subject, let’s say S1, S2, S3, S4, S5.
Step 3: Calculate the sum of all the 5 Subject values and store result in a variable i.e.
Total = S1+S2+S3+S4+S5
Step 4: Divide Total by 5 and assign it to Average variable. (Average = Total/5)
Step 5: Print Average
Step 6: End

10 Principles of Programming and Web Technologies


kn Unäv

Example 2: Find the greater number between two numbers


Step1: Start
Step2: Read 2 numbers num1 and num2
Step3: If num1 greater than num2 then C=num1
Step4: if num2 greater than num1 then C=num2
Step5: Print C
Step6: End

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.

Rules to write a pseudocode


• Write only one statement per line. Each statement of the pseudocode should express just one
action for the computer.
• Capitalize initial keyword. In the example above, READ and WRITE are in capital letters.
• Indentation is used to show hierarchy.
• End multiline structures.
• Keep statements language independent.
Let’s write pseudocode for: find the largest among 2 numbers
READ num1,num2, res
IF num1> num2
res= num1
WRITE "res is Maximum"
ELSE
res= num2
WRITE " res is Maximum"
ENDIF

Advantage of Pseudocode
• Enhances the readability of any strategy. It's one of the greatest methods for beginning the
implementation of an algorithm.

Principles of Programming and Web Technologies 11


kn Unäv

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

Example : Pseudocode to find the sum of natural numbers.


Start program
Declare variables n, sum = 0 and i
Enter the number for n
For i=1 to i<=n
Perform operation sum = sum + i
Increment i value by one
Print sum
End program

Example : Pseudocode to read 3 numbers and sort them.


Start program
Read n
i=2
answer = prime
While i <= n / 2
rem = n % i
if rem is not equal to 0
i=i+1
else
answer = not prime
End While Loop
Print answer
End program

12 Principles of Programming and Web Technologies


kn Unäv

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

Data Predefined Process


Internal
Storage
Principles of Programming
Indicates process andor
of inputting Web Technologies 13
outputting external data. Data stored locally
Represent a step in a process. Indicates the starting or ending
most common component of a of the program,
kn Unäv flowchart. Used to ask a question that can
be answered inYes/No,
True/False

Data Predefined Process


Internal
Storage
Indicates process of inputting or
outputting external data. Data stored locally

Document Multiple Preparation


document

A preparation step

Alternate Process Connector Manual


Operations
An alternate to normal process
step. Flow lines to this block is On-page connecter are used to
usually dashed. replace long lines on a flowchart Any manual adjustments done
page or multiple pages. to the data flow. The process is
not automated.

Off-page
Manual Input Connector Display

Data or information emtered


when promptedinto a system. used when the target is on Information shown to a user
another page.

Merge
Delay
Data Storage

Describes a waiting period that Point where sperate orocesses Data stored in any format
occurs while data flow join together

Database Direct Data

Flowlines that shows the


direction of the flow

14
General flowcharting guidelines Principles of Programming and Web Technologies

1. The flowchart's boxes are all connected together with arrows.


kn Unäv

General flowcharting guidelines


1. The flowchart's boxes are all connected together with arrows.
2. Flowchart symbols only have one entry point, which is located at the top of the symbol. With
the exception of the Decision symbol, all flowchart symbols have an exit point at the bottom.
3. The Decision symbol has two exits, either on the bottom and one side or on the sides and one
exit.
4. Generally speaking, a flowchart moves from top to bottom. However, an upward flow may be
displayed as long as it does not exceed three symbols.
5. The flowchart's breaks are linked together using connectors. Examples include:
• From one page to another page.
• From the bottom to the top of the same page.
• More than 3 symbols moving upward at once
1. The flowcharts for interrupt programmes and subroutines are separate and unique.
2. The first symbol in every flow chart is a Terminal or Predefined Process (for interrupting
programmes or subroutines).
3. A terminal or a contentious loop always concludes a flowchart.
Flowcharting uses symbols which have been in use for quite sometime to represent the type
of operations/actions and/or processes being performed. The standardised format provides a common
method for people to visualise the given problems together in the same order. The use of standardised
symbols makes the flow charts easier to understand, however, standardizing these symbols is not as
important as the sequence of activities that make up the given process.
Advantages of Flowchart
• Most efficient way of communicating the logic or the process of system.
• Acts like a guide for blueprint during program designed.
• Helps in debugging process.
• Using flowchart we can easily analyze the programs.
• These are good for documentation.

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.

Principles of Programming and Web Technologies 15


kn Unäv

Example 1: Calculate average of 5 marks obtained by student


Table 1.2: Difference between Algorithm and Flowchart

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

Replacement for any logic that is represented


Regarded as pseudocode for any program
using a flow diagram.

Easy to debugging. Hard to debug.

16 Principles of Programming and Web Technologies


kn Unäv

Example 2: Greatest among two numbers


Example : Algorithm and flowchart to print the first 15 multiples of 7.
1. Start
2. Initialise count = 1
3. Now check the condition if c < 16 then
goto step 4.
Else
goto step 6
4. Print 7 * c
5. c += 1. Then goto step 3.
6. Stop

Principles of Programming and Web Technologies 17


kn Unäv

Problem Solving using Computers


Computer-based problem solving is a systematic method that involves designing, implementing
and applying programming tools. Problem solving is the process of turning a problem's description
into its solution while relying on our understanding of the problem domain and our capacity to choose
and employ the most effective problem-solving strategies, techniques, and tools. Using this approach,
the computer system can be more intuitive with human logic rather than machine logic. Computers
are normally used for solving various day-to-day problems and thereby the problem solving is an
essential skill that you should know. It is important to note that computers cannot solve problems on
their own. We should provide detailed step-by-step directions for resolving the problem. Therefore,
the effectiveness of a computer in solving a problem depends on how exactly and correctly we
characterise the problem, create an algorithm to solve it, and then use a programming language to
implement the algorithm to create a programme. Determining a problem, creating an algorithm to
address it, and then putting the method into practise to create a computer programme are the steps
involved in problem solving.
The Figure:1.2 depicts various stages while solving a problem using computer

18 Principles of Programming and Web Technologies


kn Unäv

Figure: 1.2: Steps in solving problem using computers


• Problem Definition - A clear and well- defined problem is already half the solution expected.
Before even attempting to create a solution, computer programming requires us to first define
the problem properly.
• Problem Analysis - It is important to clearly understand the given problem before we begin
to find the solution for the same. We need to analyze and understand it well before solving as
the user’s requirements cannot be fulfilled without clear understanding of his/her problem in
depth. Therfore, we need to study and analyse the problem statement carefully so that we
can list the principal components of the problem and decide the core functionalities that our
solution should have. In order to determine the inputs and outputs that our program should
generate, we must first analyse the problem statement.
• Problem Design - Creating algorithms, flowcharts, and pseudocodes is what this step entails.
Before creating the program code to solve a particular problem, a solution must be thought
out. Algorithms, flowcharts, and pseudocodes are used to illustrate the solution. Generally,
this stage aims to improve the program's usability, feasibility, and efficiency.
• Coding - After finalising the algorithm, we now need to convert algorithm developed into
the format which can be understood by the computer to generate the required output. This
stage, where the programmer creates a series of instructions ready for execution, is where
the computer is actually used. Programming is another name for coding. Various high level
programming languages can be used for developing a program.
• Compilation and Execution - The source code thus developed using any programming
language cannot be executed by the computer directly. It needs to be translated into to the

Principles of Programming and Web Technologies 19


kn Unäv

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.

Introduction to Programming Languages


An instruction set known as a programme is used by computers to carry out tasks.
Alternatively known as scripts, these set of instructions. Scripts are interpreted by the processor,
whereas programmes are executed by them. Programming languages are the languages that are used
to create a programme or set of instructions. In other words, a programming language is a collection
of symbols, grammars, and rules used to convert algorithms into computer programmes that can be
run by computers. Programming languages are used by the programmer to interact with the computer.
The majority of the programmes have a very defined set of rules. The majority of desktop, web, and
mobile applications are created using programming languages.

Characteristics of a programming Language –


• A programming language must be straightforward, simple to learn and use, easy to comprehend,
and easily recognisable by humans.
• Abstraction is a necessary feature for a programming language since it allows for the definition
of complicated structures, which in turn increases usability.
• It is usually preferable to use a portable programming language.
• The efficiency of a programming language is important because it determines how quickly it
can be translated into machine code and how much memory it uses when it is executed.

20 Principles of Programming and Web Technologies


kn Unäv

• For a programming language to be useful for application development, it must be well


organised and documented.
• A programming language must offer the tools required for the creation, maintenance, testing,
and debugging of a programme.
• Integrated development environment (IDE) should be provided by a programming language.
• A programming language needs to be semantically and syntactically consistent.

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.

Keeps translating the program continuously


Generates the error message only after it scans
till the first error is confronted. If any error is
the whole program & hence debugging is rela-
spotted, it stops working and hence debugging
tively harder while working with a compiler.
becomes easy.

Used by programming languages like C and Used by programming languages like Ruby and
C++ for example. Python for example.

Principles of Programming and Web Technologies 21


kn Unäv

Now we can look types of programming language:


• Machine Language - are the most basic level of programming languages. it is considered as
first-generation of programming languages. In the early stages of computer development, all
program instructions was written using binary codes unique to each computer. This type of
programming involves the difficult task of writing instructions in the form of strings of binary
digits (1's and 0's). The internal workings of the specific type of CPU used by programmers
must be properly understood. To do even simple processing tasks, they must create lengthy,
complex instructions. Every instruction and data item used in machine language programming
must have its storage location specified. These requirements make programming in machine
language challenging and error-prone. In machine language instructions, some bits are
often used to describe operations, like addition, and others are used to represent operands or
possibly the position of the next instruction. Since machine language has different codes from
computer to computer and does not match either traditional mathematical notation or human
language, it is challenging to understand and write. The benefit of using machine language
over a high-level and low-level programming language is that it allows programmers to run
their code more quickly.
• Low-Level Language – these are considered as the next level of programming languages also
known as Assemble languages or second-generation languages. It is very close to machine
level language. They were developed to reduce the difficulties in writing machine language
programs. They require language translator programs called assemblers that allow a computer
to convert the instructions of such languages into machine instructions. Assembler languages
are also frequently called as symbolic languages because symbols are used to represent
operation codes and storage locations. Operation codes, storage locations, and data items are
represented by practical alphabetical abbreviations termed mnemonics (memory aids) and
other symbols. Assembly language has the benefit of using less memory and less time to
execute programmes. Assembly language encourage modular programming
• High-Level Language – considered as the third-generation languages use instructions, which
are called statements, that use brief statements or arithmetic expressions. They uses the format
or language that is very much familiar to users. The instructions are called codes or scripts.
Each individual statement or script generates several machine instructions when translated into
machine language by high-level language translator programs called compiler or interpreters.
i.e. computer needs a compiler and interpreter to convert program written in high-level
language to machine language. Examples include BASIC, COBOL, C, Python, Java, Perl,
Pascal, LISP, FORTRAN, etc. It is easy to write a program using high level language and is
less time-consuming. Debugging is also easy. Main disadvantages of thisis that it takes lot
of time for execution and occupies more space when compared to Assembly and Machine
languages. These statements resemble the phrases or mathematical expressions required to
express the problem or procedure being programmed. The syntax which includes vocabulary,
punctuation, and grammatical rules and the semantics of such statements do not reflect the
internal code of any particular computer.
The high-level programming languages are further divided into procedural programming
and object-oriented programming. Both these programming languages are used to develop desktop
applications.

22 Principles of Programming and Web Technologies


kn Unäv

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.

Figure 1.3: Procedure Programming

Features of Procedural Programming


• Predefined functions: An instruction with a name attached to it is often a predefined function.
Predefined functions are frequently included in higher-level programming languages, but they
come from libraries or registries rather than programmes.
• Local Variable: A local variable is a variable that is declared in the method's main structure
and has the local scope to which it is assigned. If the local variable is used outside the declared
method, the code will stop working because it can only be used in the method in which it is
defined.
• Global Variable: A global variable is one that is declared independently of all other functions in
the code. As a result, unlike a local variable, global variables can be accessed in all functions.
• Modularity: When two different systems with two distinct tasks at hand are brought together
to finish a larger task first, this is known as modularity. The individual tasks within each group
of systems would subsequently be finished one by one until all tasks are finished.
• Parameter Passing: It is possible to pass parameters to functions, subroutines, and procedures
via the parameter passing mechanism. The phrases "pass by value," "pass by reference," "pass
by result," "pass by value-result," and "pass by name" are among the many ways to pass
parameters.

Principles of Programming and Web Technologies 23


kn Unäv

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.

Figure 1.4 : Object Oriented Programming


24 Principles of Programming and Web Technologies
kn Unäv

Characteristics or Concepts of OOPs


• Object - An instance of a Class and the basic unit of OOPs concept. Both functions and
properties are present. They resemble things from the real world. For instance, out home, car,
laptop, and other things all come under objects. They have a few unique characteristics and
ways to carry out certain tasks.
• Class - A class is a model or prototype from which new objects can be made. This section
describes a class that simulates the state and actions of a real-world object. It intentionally
emphasizes on the fundamentals to demonstrate how even a simple class can accurately
capture state and behaviour.
• Inheritance - A strong and effective approach for organising and structuring your software is
inheritance. An object can be based on another object through the object-oriented programming
concept of inheritance. The mechanism for reusing code is inheritance. The object that is being
inherited is referred to as the superclass, and the object that does so is referred to as a subclass.
• Abstraction - It refers to, providing only essential or important information to the outside world
and hiding their background details. In other words, it refers to hiding distracting aspects and
only displaying the essential information to the user.
• Encapsulation - Data variables and methods are connected in a class through encapsulation.
It is the process of combining member functions (methods) and data members (variables,
properties) into a single entity. It also serves as a means of limiting access to particular
components or features. Then, access to these things could be restricted to objects belonging
to the class. This is referred to as data concealing and aids in the insulation of data.
• Polymorphism - Multiple forms are referred to as polymorphism. Polymorphism typically
happens when there is a hierarchy of classes and they are connected by inheritance. The idea
of polymorphism describes how an object will act differently depending on the circumstances.
Compile-time polymorphism and run-time polymorphism are the two types of polymorphism.

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.

Let's compare procedural programming vs object-oriented programming.

Principles of Programming and Web Technologies 25


kn Unäv

Table 1.4: Procedural Programming vs OOPs

Procedural Programming Object-Oriented Programming


Program is divided into small parts called Program is divided into small parts called
functions. objects
Follows top-down approach Follows bottom-up approach
Accessing modes that include protected,
No specific accessing mode for accessing
private, and public are used to access
functions or attributes in a program.
functions of attributes.
Does not give importance to data. It prioritizes Gives importance to the data rather than
the functions along with the sequence of functions or procedures. It is because it works
actions that needs to follow. on the basis of the real world.
Adding new data and functions is not easy. Adding new data and function is easy.
Does not offer any method of hiding data. Hiding data is possible due to the abstraction.
Hence less secure Hence more secure
Achieves inheritance in three modes-
Does not provide any inheritance.
protected, private, and public.
Overloading concepts is possible in the
No overloading concepts form of operator overloading and function
overloading
Code reusing not possible Reuse of any existing codes via inheritance
Function over data is prioritized Data over function is given importance
Not suitable for solving any large or complex
Suitable for solving any complex problems
problems
Data moves freely within the system from one Objects can move and communicate with each
function to another. other via member functions
Execution order of statements is not the Order of execution of the statements is very
primary focus important
Supports parallel programming Not suitable for parallel programming
Some common examples include C, Fortran, Examples are Java, C++, VB.NET, Python,
VB, and Pascal. and C#.NET.

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.

Introduction to Microprocessor & Microcontroller programming


A microprocessor or processor is a programmable electrical chip with processing and
decision-making abilities comparable to those of a computer's central processing unit. It is a small
chip that resides in computers and other electronic devices. Microprocessor is a programmable, clock

26 Principles of Programming and Web Technologies


kn Unäv

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.

Important features of Microprocessor:


• Offers built-in monitor/debugger program with interrupt capability
• Large amount of instructions each carrying out a different variation of the same operation
• Offers Parallel I/O
• Instruction cycle timer
• External memory interface
Microprocessors are mainly used in devices like:
• Calculators
• Accounting system

Principles of Programming and Web Technologies 27


kn Unäv

• 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:

28 Principles of Programming and Web Technologies


kn Unäv

Table 1.5: Microprocessor vs Microcontroller

Microprocessor Microcontroller

Heart of Computer system. Heart of an embedded system.

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.

Can’t use it in compact systems Can use it in compact systems.

High cost Cost is low

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.

It is a by-product of the development of


It is a CPU on a single silicon-based integrated chip. microprocessors with a CPU along with other
peripherals.

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.

Uses an external bus to interface to RAM, ROM, and


Uses an internal controlling bus.
other peripherals.

Used for general purpose applications that handle


Used for application-specific systems.
loads of data.

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.

Principles of Programming and Web Technologies 29


kn Unäv

Figure 1.5 : Machine Cycle


Four steps of the machine cycle
1. Fetch - Retrieve an instruction from memory. The instruction is fetched from the memory address
that is currently present in the PC and stored into the instruction register. At the end of the fetch
operation, the PC points to the next instruction that will be read at the next cycle.
2. Decode - Translate the retrieved instruction into computer commands. The decoder in the control
unit decodes the instruction. Each CPU is designed to understand a specific set of commands.
These commands are known as instruction set. These instruction sets function by sending machine
code to the CPU.
3. Execute - Execute the computer commands. The ALU then executes the decoded instructions.
The instructions can be either an arithmetic processes or logical processes . The data from the
fetch phase of the operation cycle is manipulated according to the instructions received from the
program.
4. Store - Send and write the results back in memory. The freshly processed data is then transferred
through the data bus back into the memory where it was originally stored. The information can be
used for reporting and other outputs or resubmitted for subsequent processing.
An important process in a computer system that deals with fundamental activities in the CPU
is the instruction fetching decode cycle. The looping scenario continues forever until the system
enters the shutdown phase. The instruction fetch and decode cycle is used to carry out all operations
via computer processor system instructions.

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

30 Principles of Programming and Web Technologies


kn Unäv

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.

Principles of Programming and Web Technologies 31


kn Unäv

• 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

Figure 2.1: Structure of C Program


Documentation : The program's description, name, and creation date and time are all included in this
section. It is stated in the form of comments at the beginning of the programme. Documentation is
highlighted by:
// title, name of the software, name of the programmer, date, time, etc.
or
/*
description, program's name, programmer's name,
date, time, etc.
*/
Anything that is written in comments will be regarded as programme documentation and
won't affect the provided code. In essence, it provides the reader with a summary of the programme.
Preprocessor Section - The preprocessor portion of the programme will declare each of the program's
header files. We can incorporate better code from others into our own code with the use of header
files. Before the compilation process, we incorporate a copy of each of these several files into our
software. Example:
#include<stdio.h>
#include<math.h>
Preprocessor directives are lines that begin with a #, such as #include. Any line that begins with a #
instructs the preprocessor that it needs to take some action. In fact, it indicates that another line should
be immediately substituted for that one. This procedure takes place in the background; we are not
aware to it.

Principles of Programming and Web Technologies 33


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;

Body printf(“%d”, a) This command prints the output on the


screen.

34 Principles of Programming and Web Technologies


kn Unäv

Return return 0; This command is used to terminate a C program


(main function) and it returns 0.
} It is used to indicate the end of the main
function.

The steps involved in a complete program execution are as follows:


• Create a program – write the program using any text editors
• Compile a program - process of checking the errors in the code. The computer displays all the
errors if found in written C code.
• Run or execute a program - once the program is complied without any error, program is
assembled and linked. The computer performs different operations, like decoding, ALU
operations to run a program.
• Output of the program - after the execution, the result is obtained

Compilation process in C

The several steps that make up C compilation and execution process is given in Figure 2.2 :

Figure 2.2: : Phases of compilation


• Preprocessing - The source code file extension is ".c," and it refers to code that has been
written in a text editor. The preprocessor receives this source code first, and extends it after
that. The code is extended after which it is passed to the compiler for further processing.
• Compilation - The preprocessor passes extended code to the compiler for further processing.
This code is converted into assembly language by the compiler.

Principles of Programming and Web Technologies 35


kn Unäv

• 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

Figure 2.3 : Compilation Process

Basic guidelines for writing C program


• The semicolon symbol must be used to conclude each executable statement (;).
• There must be exactly one main method in every C programme (Starting point of the
programme execution).
• All of the words (keywords) that the system defines must be written in lowercase.
• It is not possible to use keywords as user-defined names (identifiers).
• There must be a corresponding closing brace () for each open brace ().
• Before being used, each variable needs to be declared.
Tokens Variable, Datatypes, Constants
The simplest elements or building blocks used to create a C program are known as tokens.
There are six categories of C tokens: Identifiers, Keywords, Constants, Operators, Special Characters,
and String literals.
Identifiers are names given to different entities such as constants, variables, structures,
functions, etc. A variable is nothing more than a name given to a storage space that the programs

36 Principles of Programming and Web Technologies


kn Unäv

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.

Principles of Programming and Web Technologies 37


kn Unäv

• 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

Symbol Name Description

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.

38 Principles of Programming and Web Technologies


kn Unäv

Table 2.2: Keywords in C


auto break case char const continue default
do double else enum extern float for
goto if int long register return short
signed sizeof static struct switch typedef union
unsigned void volatile while

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.

Principles of Programming and Web Technologies 39


kn Unäv

6 \’ Inserts a single quote character in the text at this point.


7 \” Inserts a double quote character in the text at this point.
8 \\ Inserts a backslash character in the text at this point.
9 \a Inserts an alert or beep sound when inserted
10 \v Inserts a vertical tab
11 \? Displays a question mark
12 \0 Null Character. Marks the end of the string

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() {

40 Principles of Programming and Web Technologies


kn Unäv

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

42 Principles of Programming and Web Technologies


kn Unäv

printf("You name is : ");


puts(string);
return(0);
}
The output of the above program is as follows:
// Enter your name : kannan
// You name is : kannan

Operators and Expressions


C provides in with large number of operators that may fall under various categories. In this
section, we shall look into C operators and expressions. Operators are symbols that are used to
perform mathematical, conditional or logical calculations. Without these operators, the functionality
of all programming languages would be essentially meaningless. These are highly powerful and act
as useful features of all programming languages. C language is rich in built-in operators and provides
the following types of operators:
a) Arithmeic Operators
b) Logical Operators
c) Relational Operators
d) Assignment Operators
e) Increment Decrement Operators
f) Conditional Operators
g) Bitwise Operators
h) Special Operators
Arithmetic operators – these are operators that are used to perform various mathematical calculations
such as like addition, subtraction, multiplication, division and percentage modulo. Suppose that
variable A contains 15 and variable B contains 10.
Table 2.4 : Arithmetic Operators
Operator Name Description Example
+ Addition Adds two operands A + B = 25
- Subtraction Subtracts any two operands A-B=5
* Multiplication Multiplies and gives the product among A * B = 150
/ Division Divides the numerator with denominator A/B=1
% Modulus Returns remainder of division of any two operands A % B = 5
Both character data types and numerical data types can be handled with the addition operator.
It performs mathematical addition when used with numerical values, and concatenation or appending
when used with character data type values.
Principles of Programming and Web Technologies 43
kn Unäv

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

Operator Name Description Example


To determine whether the operand value on the left is
If A > B
> Greater than comparatively higher than the operand value on the
returns TRUE
right.
To determine whether the operand value on the left
If A < B
< Less than is comparatively lower than the operand value on the
returns FALSE
right.
To determine whether the operand value on the left
Greater than or If A >= B
>= is equal to or substantially greater than the operand
equal to returns TRUE
value on the right.
To determine whether the operand value on the left is
Less than or If A <= B
<= equal to or substantially lower than the operand value
equal to returns FALSE
on the right.
Checks whether the given two operands are equal
If (A==B)
== Equal to to each other. If the condition is true returns 1 and if
is FALSE
false it returns 0.
Checks whether the given two operands are unequal
If (A!=B)
!= Not equal to to each other. If the condition is true returns 1 and if
is TRUE
false it returns 0.

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.

44 Principles of Programming and Web Technologies


kn Unäv

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

Operator Description Example


= Assigns the values from the right operand to the left operand. A=B
Adds or sum the value of the right operand with the value of the A += B is same as
+=
left operand. After that, assign sthe resultant value to the left one. A=A+B
Subtracts the right operand value from the value of the left oper- A -= B is same as
-=
and. After that, assigns the result obtained to the left one. A=A-B
Multiplies right operand value with the value of the left operand. A *= B is same as
*=
After that, assigns the result obtained ie product to the left one. A=A*B
Divides the value of the right operand with the left operand value. A /= B is same as
/=
After that, assigns the result obtained ie quotient to the left one. A=A/B
Calculate the modulus of the values of the right operand and the
A %= B is same as
%= left operand. After that, assigns the resultant value i.e. remainder
A=A%B
to the left one.

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.

Principles of Programming and Web Technologies 45


kn Unäv

Depending on how many bits the right operand


<< Binary Left Shift specifies, it moves the value of the left operand to A<<2
the left.
Depending on how many bits the right operand
Binary Right
>> specifies, it moves the value of the left operand to B>>2
Shift
the right.

Increment Decrement Operators - To increase or decrease a value of an operand (constant or variable)


by one, C offers two operators: increment ++ and decrement. While decrement operator reduces the
value by 1, increment operator increases it by 1. These two operators are unary, which means that they
only operate with one operand.
Table 2.10: Increment/Decrement Operators
Operator Name Description Example
Let A = 25, then
++ Increment Adds one to the existing value
A++ = A+1= 26
Let A = 25, then
-- Decrement Subtracts one from the existing value
A-- = A-1= 24
The increment and decrement operators can be used either before the operand (++a) or after
the operand (a++). It is referred to as a pre-increment or pre-decrement if it is used before the operand,
and a post-increment or post-decrement if it is used after the operand.
Conditional Operators - Due to the fact that it requires three operands, the conditional operator is
sometimes known as a ternary operator. Making decisions is done with this operator. In this operator,
we first check a condition, and then, depending on the outcome of the condition, we carry out one
of the two actions. If the criterion is TRUE, the first option is carried out; if it is FALSE, the second
option is carried out. The following syntax is used with the conditional operator.
Condition ? TRUE Exp1 : FALSE Exp2;
(number>=18) ? ( larger) : (smaller) ;
Special Operators – Besides the operators described above, there are some other important operators.
Table 2.11 shows the same.
Table 2.11: Special Operators
Operator Description Example
Return the actual size of any data be a constant or If A is an integer, then the
sizeof ()
variable size of(A) will return 4.
Comma (,) Used to link related expressions together. Let A = 25, B=15
&A; would return the actual
& Returns the address of any given variable.
address for given variable.
* Pointer to the variable *A

46 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 47


kn Unäv

Type Casting and Type Conversion


The expression in a programming language might have data values of the same data type or of
different data types. When an expression contains values of a comparable datatype, it can be evaluated
without any issues. The expression must be converted to the single datatype of the destination datatype
if it comprises two or more values of different datatypes. The data conversion is performed in two
different methods as follows: Type Conversion and Type Casting
Type conversion process is the automatic mechanism by which the compiler converts a data
value from one data type to another. Implicit type conversion is another name for type conversion.
The compiler automatically executes the implicit type conversion. Example:
int main()
{
int x = 15;
char y = 'a';
// y implicitly converted to int. ASCII & value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 5.0;
printf("x = %d, z = %f", x, z);
return 0;
}
The output will be obtained as : x = 112, z = 117.000000
Typecasting is also referred to as an explicit type conversion. Data is implicitly converted by the
compiler from one data type to another. Data loss could occur during implicit conversions performed
by compilers. In this situation, we use explicit type conversion to change the data's data type from one
to another. We use the unary cast operator to carry out this. When converting data between types, the
target data type is prefixed to the data value that needs to be converted in parenthesis. The following
is a general syntax for typecasting.
(Target Datatype) data_value
Example to demonstrate typecasting using program
#include <stdio.h>
void main() {
int sum = 27, count = 6;
double mean;
mean = (double) sum / count;

48 Principles of Programming and Web Technologies


kn Unäv

printf("Value of mean : %f\n", mean );


}
The output will be obtained as Value of mean : 4.500000. In the given example, you can see
that sum and count are integer datatypes while mean is double. Since the result is stored in the mean
variable, during the execution type, the result is typecast to double as shown.
Programming Errors
Errors are problems or faults that arise in the program which cause the behaviour of the
program to be abnormal. Even skilled developers are capable of making these faults. Debugging is the
process of eliminating problems, which are sometimes referred to as faults or bugs in programming.
Either during compilation or execution, these mistakes are found. In order for the program to run
successfully, the errors must be fixed. Different types of errors that exsists in C are following:
• Syntax Error - As they occurred during compilation, syntax errors are also referred to as
compilation errors. Alternatively, we may say that syntax errors are thrown by compilers.
These issues typically result from typing errors or from failing to adhere to the syntax of the
stated programming language. Beginners normally make these errors as they are unfamiliar
with the language. These mistakes are simple to debug or fix.
For example: int num instead of int m
Common syntax mistakes include: failing to include a parenthesis () when writing the code, showing
a variable's value without declaring it, if the statement's end semicolon (); is omitted.
• Logical Error - An undesirable outcome results from this error. These errors, sometimes
referred to as logical errors, are error-free but result in the erroneous output. Most beginners
make mistakes of this nature. The developer's logical reasoning is mostly responsible for the
occurrence of these errors. These errors will be less likely to occur if the programmers are
logically correct.
• Run-time Error – These errors can occur during execution even after a successful compilation.
Run-time errors typically occur when a programme is running and is unable to complete an
operation. The most typical example of a run-time error is division by zero. Since the compiler
does not flag these problems, they are particularly challenging to identify.
For example: int m=9/0
• Linker Error - These errors are commonly generated when the program's executable file is not
created. This may have occurred as a result of using the incorrect header file or the incorrect
function prototype.
For example: void Main()
• Semantic Error – These errors are those that happen when the compiler is unable to comprehend
the statements.

Principles of Programming and Web Technologies 49


kn Unäv

Table 2.13: Compile-time errors Vs Run-time errors

Compile-time Errors Run-time Errors


The errors that are produced at compile time The errors that are produced at execution
and the compiler can identify them. time and are not produced by the compiler.
In this scenario, if the compiler finds a Since the compiler in this instance is
programming error, it stops the code from unable to recognise the problem, the code
running. execution cannot be stopped.
It has grammatical and semantic flaws, It contains mistakes like finding the square
including a missing semicolon at the end of root of a negative value and dividing by
the sentence. zero.

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

if ((year%4 == 0) && ((year%100 !=0) || (year%400==0)))


printf("Yes. The entered year is a leap year!!!");
else
printf ("No. The entered year is not a leap year!!!");
}
The output of the above program will be obtained as follows
// Enter a year to check :2015
// No. The entered year is not a leap year!!!
// Enter a year to check :2020
// Yes. The entered year is a leap year!!!

Nested if....else statement


When an if statement is nested with another if statement or an else statement, it is referred to
as a nested if statement. Syntax is as follows:
if ( test expression 1)
{
if ( test expression 2)
{ Verify True statements of 2nd condition; }
else
{ Verify False statements of 2nd condition; }
else
{
Verify False statements of 1st condition;
}
When a user wants to examine a variety of circumstances, the nested if statement can be quite
helpful. The if block is used to specify a condition in this case (or an expression). The result of this
expression will determine how the resultant statement is performed (when the condition is TRUE or
FALSE).
# Program to check whether user entered year is leap year
#include<stdio.h>
void main(){
int n ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n <500 )

52 Principles of Programming and Web Technologies


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

Using else if statement/ Elseif ladder


The only difference between an if-else statement and else if is that an if-else statement is used
by when one or two options need to be examined, whereas else if is helpful when a multipath decision
is needed. Because of the way this statement is structured, it is also known as the "else if ladder." The
general syntax of the if-else-if statement is as follows:
if(test expression1)
{ statement block1; }
else if(test expression2)
{ statement block2; }
else if(test expression3 )
{ statement block3; }
else
default statement;
The expression is tested from the top to downwards. As soon as a TRUE condition is found,
the statement associated it with gets executed.
# Program to find largest among 3 numbers
#include<stdio.h>
void main(){
int a, b, c ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;
Principles of Programming and Web Technologies 53
kn Unäv

if( a>=b && a>=c)


printf("%d is the largest number", a) ;
else if (b>=a && b>=c)
printf("%d is the largest number", b) ;
else
printf("%d is the largest number", c) ;
}
The output obtained for the above program will be as follows:
// Enter any three integer numbers: 45
// 88
// 90
// 90 is the largest number

Using Ternary operator


This is considered as a shorthand way or writing an if-else statement. We have seen about it
when we have learnt about conditional operators. Here we shall look how this can be applied in a
program.
# Program to print the either sum or difference based on operator assigned
#include <stdio.h>
int main() {
char operator = '+';
int num1 = 8;
int num2 = 7;
int result = (operator == '+') ? (num1 + num2) : (num1 - num2);
printf("Result : %d", result);
return 0;
}
Output obtained as follows
// Result : 15
Decision making using switch
A switch statement is a form of selection control mechanism used in computer programming
languages to allow the value of a variable or expression to change the control flow of programme
execution through search and map. Instead of using many if..else statements, switch statement can be
used. The "switch" statement is a control statement that enables us to select just one option from the
various provided options. The integral value obtained from the expression in switch is then compared
to the values present in the various situations. When the case value matches, the block of code is
executed. If no match is found, the default block is carried out (if present). The switch statement's
54 Principles of Programming and Web Technologies
kn Unäv

basic structure is,


switch(expression)
{
case 1: block-1;
break;
case 2: block-2;
break;
case 3: block-3;
break;
case 4: block-4;
break;
:
default: default-block;
break;
}
This is how the above syntax works:
• The switch expression is evaluated once
• The expression's value is compared against the values in each case.
• If there is a match, the associated block of code is executed
• The switch block's execution is halted by the break statement.
• The default statement, which is optional, specifies some code to execute if there is no case
match.
# Program calculate the weekday name using number
#include<stdio.h>
void main(){
int day ;
printf("Enter any digit: ") ;
scanf("%d", &day) ;
switch (day) {
case 1: printf("Monday");
break;
case 2: printf("Tuesday");
break;
case 3: printf("Wednesday");
break;
Principles of Programming and Web Technologies 55
kn Unäv

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.

Using while loop


The ‘while’ clause is used to repeatedly run a single statement or a block of statements when
the specified condition is TRUE. If the condition yields an incorrect result, the loop structure is not
executed. Syntax is given below:
56 Principles of Programming and Web Technologies
kn Unäv

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

Using for loop


Use the ‘for’ loop rather than the while loop when you are sure exactly how many times you
want to iterate over a block of code. As long as the specified condition is TRUE, the for statement is
used to repeatedly execute a single statement or a block of statements. The syntax of the for statement
is as follows:
for (initialization; condition; increment) {
// code block to be executed
}
The ‘for’ clause first carries out initialization before evaluating conditions. The single
statement or block of statements in the for statement are performed if the condition is interpreted as
TRUE. After the execution is finished, the increment statement is carried out, and the condition is
once more assessed. The same sentences are once again carried out if it is TRUE. The same procedure

Principles of Programming and Web Technologies 57


kn Unäv

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

58 Principles of Programming and Web Technologies


kn Unäv

printf("Outer loop : %d\n", i); // Executes 2 times


// Inner loop
for (j = 1; j <= 3; ++j) {
printf(" ---- Inner loop executing : %d\n", j); // Executes 6 times (2 * 3)
}
}
}
The output for the above program is as follows:
// Outer loop : 1
// ---- Inner loop executing : 1
// ---- Inner loop executing : 2
// ---- Inner loop executing : 3
// Outer loop : 2
// ---- Inner loop executing : 1
// ---- Inner loop executing : 2
// ---- Inner loop executing : 3

Using do while loop


In some cases, before testing the condition it is necessary to execute body of the loop atleast
once. The "do-while" loop is useful in handling such circumstances. The while statement is used to
check the condition after the do statement has finished evaluating the loop's body. While the starting
condition inside while is initially set to FALSE, it signifies that the body of the loop will be executed
at least once. General syntax is,
do
{
statements
}while(condition);
The single statement or block of statements which are defined inside the do block will be
executed. After the execution of do block, the given condition gets checked. If the condition is
found to be TRUE, the single statement or block of statements of do block are executed again. Once
the execution gets completed again the condition is checked and this process takes place repeatedly
until the condition is found to be FALSE. Whenever the condition is observed FALSE, the execution
control moves out of the while block. Example program to understand the working of for loop.
// Program to display even numbers upto 20.
#include<stdio.h>
void main(){
int n = 0;
Principles of Programming and Web Technologies 59
kn Unäv

printf("Using do-while, Even numbers upto 20\n");


do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 20 ) ;
}
The output is as follows:
// Using do-while, Even numbers upto 20
// 0 2 4 6 8 10 12 14 16 18 20

break, continue and goto in C


A loop may occasionally need to skip a section or end as soon as a given condition is met.
There are several control statements that can regulate how the programme is executed without the
requirement for any conditions. These are referred to as unconditional control statements or jumping
out of loop. The following unconditional control statements are available in C.
• break
• continue
• goto
The ‘break’ statement is used to perform the following two things. Either it is used to terminate
the switch case statement or to terminate looping statements like while, do-while and for. While
learning the ‘switch’ statement, we have already used ‘break’ statement. Now, here in the given
program, we shall look the usage of break statement in loops.
// Program to demonstrate usage of break in control statements
#include <stdio.h>
void main()
{
int n;
printf("Enter the number of times you want to execute the for loop:");
scanf("%d", &n);
char name[25];
printf("\nEnter your name:");
scanf("%s", name);
printf(" The loop begins \n");
for(int i = 1; i <= n; i++) {

60 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 61


kn Unäv

The output is obtained as follows:


// Enter the number of times you want to print your name:13
// Enter your name: kannan
// Loop begins ---
// 1 : kannan
// 3 : kannan
// 5 : kannan
// 7 : kannan
// 9 : kannan
// 11 : kannan
// 13 : kannan
In the above example, whenever we come across an even index, we move on to the next index
because of the continue statement.
The ‘goto’ statement is used in programming to jump from one line to another. We can jump
from top to bottom or bottom to top using the goto statement. The goto statement needs a label
in order to jump from one line to another. Label is the name given to the line or instruction in the
programme. A goto statement causes the execution control to immediately jump to the line with the
provided label when it is used in a programme.
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print : ");
scanf("%d",&num);
product: // label name
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=5)
goto product;
}
The output is as follows:
// Enter the number whose table you want to print : 5
// 5 x 1 = 5
// 5 x 2 = 10
// 5 x 3 = 15
// 5 x 4 = 20
// 5 x 5 = 25
62 Principles of Programming and Web Technologies
kn Unäv

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

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. http://markburgess.org/CTutorial/C-Tut-4.02.pdf

Principles of Programming and Web Technologies 63


kn Unäv

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)

64 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 65


kn Unäv

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

The different ways to initialize two-dimensional array


int A[2][3] = {{1, 1, 0}, {-1,3, 5}};
int A[][3] = {{1, 1, 0}, {-1,3, 5}};
int A[2][3] = {1, 1, 0, -1,3, 5};
Lets look to a program to print an 2-D array
#include <stdio.h>
void main () {
/* an array with 3 rows and 2 columns*/
int a[3][2] = { {1,2}, {2,4}, {3,6}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 3; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[r%d][c%d] = %d ", i,j, a[i][j] );

66 Principles of Programming and Web Technologies


kn Unäv

}
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

68 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 69


kn Unäv

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

• function without arguments and without return value


• function without arguments and with return value
• function with arguments and without return value
• function with arguments and with return value
We shall look into each of the above mentioned categories with same example. The output
obtained will be same but the approach is different
Example for function without arguments and without return value
// Program to check a number is prime or not
#include <stdio.h>
void checkPrimeNumber(); // function prototype
int main() {
checkPrimeNumber(); // argument is not passed
return 0;
}
void checkPrimeNumber() {
int n, i, flag = 0;
printf("Enter any positive number : ");
scanf("%d",&n);
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);
}
The output obtained is as follows:
// Enter any positive number : 7
// The entered number 7 is a prime.
Principles of Programming and Web Technologies 71
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.

72 Principles of Programming and Web Technologies


kn Unäv

Example for function with arguments and without return value


// Program to check a number is prime or not
#include <stdio.h>
void checkPrime(int n);
int main() {
int n;
printf("Enter any positive number : ");
scanf("%d",&n);
checkPrime(n); // n is passed to the function
return 0;
}
// return type is void meaning doesn't return any value
void checkPrime(int n) {
int i, flag = 0;
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);
}
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 takes a value and checks whether the argument
passed is a prime number or not and then displays the appropriate message.

Principles of Programming and Web Technologies 73


kn Unäv

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.

Types of Function Calls


If a function doesn't take any parameters, you can simply use its name to call it. However,
depending on how we define the arguments, we can call a function in one of two ways for functions
that accept arguments. These are:
Call by Value - This technique transfers an argument's actual value into the function's formal parameter.
Changes made to the parameter inside the function in this instance have no impact on the argument.
Call by Reference - With this technique, an argument's address is copied into the formal parameter.
The address is used to obtain the actual parameter used in the call inside the function. This implies
that modifications to the parameter have an impact on the argument.
When we call a function by value, we send the arguments' values that have been copied or
saved into the formal parameters of the function. Thus, only the arguments within the function change
while the initial values remain constant. But when we return a value and the function is called to a
variable, the initial value changes. Let’s demonstrate this with an example.
// Program to demonstrate the call by value working
#include<stdio.h>
void main() {
int x=100;
printf("Before change() call, value of x =%d \n", x);
change(x);//passing value in function
printf("After change() call, value of x =%d \n", x);
printf("\n Before changing() call, value of x=%d \n", x);
x=changing(x);
printf("After changing() call, when function is assigned to a variable, value of x =%d \n", x);
}
Principles of Programming and Web Technologies 75
kn Unäv

void change(int num) {


printf("Before adding value inside function 'change' num =%d \n",num);
num=num+100;
printf("After adding value inside function 'change' num =%d \n", num);
}
int changing(int num) {
printf("Before adding value inside changing() num =%d \n",num);
num=num+100;
printf("After adding value inside changing() num =%d \n", num);
return(num);
}
The output generated from the above program is follows:
// Before change() call, value of x =100
// Before adding value inside function 'change' num =100
// After adding value inside function 'change' num =200
// After change() call, value of x =100
//
// Before changing() call, value of x=100
// Before adding value inside changing() num =100
// After adding value inside changing() num =200
// After changing() call, when function is assigned to a variable, value of x =200
In the above program, we have written 2 functions namely change() and changing (). In
change(), we are passing the argument by value; as a result, a copy of x is provided to the function,
where it is updated during function execution and destroyed when goes out of scope. As a result, the
value of the variable x inside the main() method remains at 10. But in the changing(), we modify the
value of x by making the function changing() return a value, and storing that value in x.
The function will have access to our variable because it now knows where it is stored and
can thus easily change its value when we supply the address of any variable as an argument. In this
situation, the formal parameter can be viewed as either a reference or a pointer; in either case, the
values of the original variable will be altered.
// Program to demonstrate the call by reference working
#include<stdio.h>
void main() {
int x=100;

76 Principles of Programming and Web Technologies


kn Unäv

printf("Before change() call, value of x =%d \n", x);


change(&x);//passing reference in function
printf("After change() call, value of x =%d \n", x);
}
void change(int *num) {
printf("Before adding value inside function 'change' num =%d \n",*num);
(*num) += 100;
printf("Before adding value inside function 'change' num =%d \n", *num);
}
The output obtained is as follows:
// Before change() call, value of x =100
// Before adding value inside function 'change' num =100
// Before adding value inside function 'change' num =200
// After change() call, value of x =200
Call by value is the default method of passing parameters in C. It generally indicates that a
function's code cannot change the arguments passed to the function during callbacks.

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

Header Files Purpose Examples

stdio.h Functions to perform standard I/O operations printf(), scanf()


conio.h Functions to perform console I/O operations clrscr(), getch()
math.h Functions to perform mathematical operations sqrt(), pow()
string.h Functions to handle string data values strlen(), strcpy()
stdlib.h Functions to perform general functions calloc(), malloc()
time.h Functions to perform operations on time and date time(), localtime()
Functions to perform - testing and mapping of character
ctype.h isalpha(), islower()
data values
setjmp.h Functions that are used in function calls setjump(),
signal.h Functions to handle signals during program execution signal(), raise()
Provides Macro used to verify assumptions made by pro-
assert.h assert()
gram
Defines the location specific settings such as date formats
locale.h setlocale()
and currency symbols
Used to get the arguments in a function if the arguments va_start(), va_end(),
stdarg.h
are not specified by the function va_arg()
errno.h Provides macros to handle the system calls Error, errno
graphics.h Functions to draw graphics. circle(), rectangle()
float.h Provides constants related to floating point data values
stddef.h Defines various variable types
Defines the maximum and minimum values of various
limits.h
variable types like char, int and long
Principles of Programming and Web Technologies 79
kn Unäv

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.

char str[] = “Kannan”

0 1 2 3 4 5 6
Indices

String K a n n a n

Address

There are two ways to create or declare Strings:


Using character array of 1D
Using string literal
Declaring a string is as simple as declaring a 1D array. Basic syntax for declaring a string:
char string_name[size];
In above syntax string_name is any name given to the string variable and size is used to define
the string length, i.e the number of characters string will store.
Example: char str[7]=”Kannan”
char str[7] ={‘K’,’a’,’n’,’n’,’a’,’n’,’\0’} // NULL character '\0' is required at end in this
type of declaration
We can also define the string by the string literal method. For example:
char str[]="Kannan";
In this case, ‘\0’ will be appended by the compiler
Let's look into asimple example where a string is declared and being printed. The '%s' is used
as a format specifier used for the string values.
#include<stdio.h>
#include <string.h> // header files for string
int main(){
char ch[7]={'K','a','n','n','a','n','\0'};
char ch2[7]="Kannan";
80 Principles of Programming and Web Technologies
kn Unäv

printf("Char Array Value is: %s\n", ch);


printf("String Literal Value is: %s\n", ch2);
return 0;
}
The output obtained for the above program is as follows:
// Char Array Value is: Kannan
// String Literal Value is: Kannan

Manipulating Strings of Characters


Strings are character arrays. Typically, we use library methods to read and output entire
strings, but here you may see instances of manipulating strings. Playing with the strings will allow us
to create all programmes without using the string.h header file. Here, each character in the character
array (string) will be accessed and modified before the string is printed using a custom method.
// Simple string manipulation program
#include<stdio.h>
int main()
{
char word[6]="HELLO";
printf(" Original word : %s\n",word); //printing unchanged string
word[3] = '*'; //changing word index 4 as '*'.
printf("Hello with * in between : %s\n",word);
word[1] = '#'; //changing word index 1 as '#'.
printf("Hello with # in between : %s\n",word);
return 0;
}
The result obtained is as follows :
// Original word : HELLO
// Hello with * in between : HEL*O
// Hello with # in between : H#L*O

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>

Principles of Programming and Web Technologies 81


kn Unäv

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[])

82 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 83


kn Unäv

strdup() string1 = strdup(string2) Duplicated value of string2 is assigned to string1


Returns a pointer to the first occurrence of character
strchr() strchr(string1, 'b')
'b' in string1
Returns a pointer to the last occurrence of character
strrchr() 'strrchr(string1, 'b')
'b' in string1
Returns a pointer to the first occurrence of string2 in
strstr() strstr(string1, string2)
string1
strset() strset(string1, 'B') Sets all characters of string1 to given character 'B'.
Sets first 5 characters of string1 to given character
strnset() strnset(string1, 'B', 5)
'B'.
strrev() strrev(string1) It reverses the value of string1

Following program depicts the use of some string functions


// Program using string functions
#include<stdio.h>
#include <string.h>
int main(){
char str[100]="Welcome to the world of Programming";
char *sub;
char str1[12] = "Welcome!! ";
char str2[25] = "Hello World Programmes";
char str3[50];
int len ;
strcpy(str3, str1);
printf("After copying string 1 to string 3 : %s\n", str3 );
strcat( str1, str2);
printf("Concatinating 2 strings : %s\n", str1 );
sub=strstr(str,"world");
len = strlen(str1);
printf("strlen(str1) : %d\n”, len );
printf("Original String is : %s",str);
printf("\nSubstring is: %s",sub);
return 0;
}

84 Principles of Programming and Web Technologies


kn Unäv

The output obtained after running the code is as follows:


// After copying string 1 to string 3 : Welcome!!
// Concatinating 2 strings : Welcome!! Hello World Programmes
// strlen(str1) : 32
// Original String is : Welcome to the world of Programming
// Substring is: world of Programming
Through the functions defined in the "math.h" header file, we can execute mathematical
operations using the C programming language. The Table 3.3 below shows the list of commonly sed
mathematical functions.
Table 3.3: String Functions

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.

// Program to illustrate some math functions


#include <stdio.h>
#include <math.h>
int main() {
double x = 10.0;
double y = 1000.0;
printf("natural log of %.1f is %.4f. \n", y, log(y));
printf("log10 of %.1f is %.4f. \n", y, log10(y));
printf("cosine of π is %.4f. \n", cos(M_PI));
printf("arc cosine of cos(π) is %.4f. \n", acos(cos(M_PI)));
printf("hyperbolic tangent of %.1f is %.4f. \n", x, tanh(x));
return 0;
}
The output obtained is as follows:
// natural log of 1000.0 is 6.9078.
// log10 of 1000.0 is 3.0000.
Principles of Programming and Web Technologies 85
kn Unäv

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

86 Principles of Programming and Web Technologies


kn Unäv

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=&num;//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];

88 Principles of Programming and Web Technologies


kn Unäv

} 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

Principles of Programming and Web Technologies 89


kn Unäv

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

90 Principles of Programming and Web Technologies


kn Unäv

// 112, Kannan, 94.849998%


// 109, Deepa, 86.650002%

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.

92 Principles of Programming and Web Technologies


kn Unäv

Table 3.4: File Functions


Function Description
fopen() opens new or existing file
fprintf() write data into the file
fscanf() reads data from the file
fputc() writes a character into the file
fgetc() reads a character from file
fclose() closes the file
fseek() sets the file pointer to given position
fputw() writes an integer to file
fgetw() reads an integer from file
ftell() returns current position
rewind() sets the file pointer to the beginning of the file

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

Principles of Programming and Web Technologies 93


kn Unäv

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.

Figure 4.1: Web Programming Triangle

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,

94 Principles of Programming and Web Technologies


kn Unäv

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:

Principles of Programming and Web Technologies 95


kn Unäv

Figure 4.2: Web Application Workflow


Through the application's user interface, the user would make a connection to the Internet and
submit a request to the web server. The request would be processed by the web server and sent to
the appropriate web app server. The required task would be completed by the web application server,
which would also produce the proper data returns. The data would be sent back to the web server by
the web app server. The web server would deliver the requested data to the client's computer, phone,
or other devices. The user gets the required result on the screen.
Server
A server is a computer, device, or software application that is solely responsible for controlling
network resources. In simple words, a server is any kind of computer that distributes data with other
computers. They receive functionality from another computer, device, or application known as a
"client," for which they are referred to as such. Different server types provide diverse services to
networks of varying sizes. In other words, a server can act and appear in a variety of ways. Hard discs,
software, or computers all fall under this category. They come in a variety of forms, but they all do
the same thing. Different types of servers include database servers, application servers, cloud servers,
web servers, stand-alone servers, proxy servers, mail servers, file servers, etc.
Web-based apps can be created and managed by an Application server. Application servers
come in a variety of forms, such as Java, PHP, and .NET Framework application servers. They ensure
data and code integrity by enabling a more centralised method for program updates and upgrades.
By centralising the control of data access and the authentication procedure, they offer security. By
reducing network traffic, performance for applications with high usage can be enhanced.
The computer that stores online material is known as a Web server. In general, web servers are
used to host websites, but there are other types of web servers as well, including gaming, storage, FTP,
email, and others. Web servers store and distribute website content, including text, photos, videos,
and application data, to clients who request it. In order to communicate with one another, Hypertext

96 Principles of Programming and Web Technologies


kn Unäv

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

Application Server Web Server


Dynamic content is delivered Static content is delivered
Can serve web and enterprise-based
Only web based applications.
applications.
Only HTTP protocol is used for content
Supports HTTP as well as RPC/RMI protocols.
delivery
High fault tolerance. Low fault tolerance.
Uses the concept of multi-threading to support
No multi-threading supports
multiple requests in parallel.
Facilitates longer running processes that are Facilitates web traffic that is not very
very resource-intensive​. resource intensive.
Examples include JBoss , Glassfish, Weblogic. Examples are Apache HTTP Server , Nginx.

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.

Figure 4.3: Client Server System

Principles of Programming and Web Technologies 97


kn Unäv

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.

Examples include desktops, tablets, smart


Example includes web servers, data server etc.
phones.

Scripting Languages (scripts)


It is a high-level programming language which is interpreted rather than compiled. It is used
to manipulate, customize and automate the existing system. These are basically languages where the
instructions are written for the run-time environment. It is translated to machine code when the code
is run and is often used for short scripts over a full computer program.
Advantages of Using Scripting languages
• Easy to learn and implement
• Portable and platform independent
• Lesser memory requirement
• Free and open source
• Highly efficient as limited data structures and variables in use
• Can be easily embedded into existing programs and applications
The Scripting language can be broadly classified into two classes – server-side scripting
language and client-side scripting language. The former creates the scripts that usually run on the
server thereby reducing the workload of the browser. These types are often used to create dynamic
websites and platforms, handle user queries, and generate and provide data and others. The latter
creates the scripts that normally run on the client side. These are sent from the server by server-side
98 Principles of Programming and Web Technologies
kn Unäv

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

Table 4.3: Difference between Scripting & Programming Languages

Scripting Languages Programming Languages


Interpreter based languges Compiler based languages
No executable file is generated during execution
Executable file is generated when code runs
of the script
Easy to learn and use Comparatively difficult to use and learn
Codes are large and has larger number of
Small piece of code
lines in the code
Faster to write as they are written to automate Time consuming as it involves developing the
specific task within a main program whole program
Always runs inside a parent program Runs or executes independently
Low maintenance cost High maintenance cost
Used to assist programming languages and
Full fledged programs
make coding easier
All scripting languages are programming lan- All programming languages are not scripting
guage languages
Examples: PHP, Javascript, Perl, bash Examples: C, C++, Python, Java

A scripting language can be applied in many different situations to accomplish a variety of


functionalities. These are what they are:
1. Web applications primarily employ scripting languages. It can be applied to client-side and server-
side applications.
2. System administration makes use of them. For instance: Shell, Python, and Perl scripts.
3. It is applicable to multimedia and has a significant impact on the creation of video games.
4. It can be used to create extensions and plug-ins for currently available web applications.
5. By using a scripting language, we can dynamically change a web page's content as it downloads.
6. Scripts can be used to process user-provided data or input to verify the accuracy of the data.
7. These can be invoked by an event.
8. They are useful for authenticating anything. For instance, a script can verify the validity of the
username and password entered by a user upon login.
9. Using scripts, we may quickly develop elements for graphical user interfaces.

100 Principles of Programming and Web Technologies


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.

Advantages of using HTML


• It's simple to learn and has flexible syntax.
• HTML Language is supported by every browser.
• HTML is quick to load and light in weight.
• The application cache function enables the storage of large files.
• Because it comes installed by default in every window, you don't need to buy any additional
software.
• Since HTML is just plain text, editing it is easy.
• It is simple to interact with other languages like JavaScript, CSS, etc.
• Even for new programmers, HTML is simple to code.

Principles of Programming and Web Technologies 101


kn Unäv

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

Disadvantages of using HTML


• Being a static language, it is unable to produce dynamic output on its own.
• It becomes difficult to understand the HTML document's structure.
• Making lists, tables, and forms requires the same amount of time as maintaining a page's
colour scheme.
• Simply building a simple webpage requires writing a lot of code.
• HTML doesn't offer many security options.
• Complexity results if lengthy code must be written in order to create a webpage.
• If we want dynamic pages, HTML is useless as it can only produce static & plain pages.
• Since web page editing is not centralised,

Features of HTML5 over HTML


• With the use of <audio> and <video> tags, it has added new multimedia features that support
audiovisual controls.
• There are new graphic components, like tags and vector graphics.
• By adding a <header, <footer>, <article>, <section>, and <figure>, you can enrich the content's
semantics.
• The user has the option to pick up an object and move it to a different spot by dragging it.
• They assist in determining a client's geographical location.
• Data storage on the web browser is made possible by a web storage facility that offers web
application approaches.
• Enables the drawing of many forms, including circles, triangles, and rectangles.
• Able to deal with improper syntax.
• <!doctype html> is a simple DOCTYPE declaration.
• Using the simple character encoding <meta charset="UTF-8">

102 Principles of Programming and Web Technologies


kn Unäv

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>

Lets look into a simple example:


<!DOCTYPE html>
<html>
<head>
<title>This is document title</title>
</head>
<body>
<h1> Heading Section</h1>
<p> Contents of the Document ....... </p>
</body>
</html>
Below diagram given in Figure 4.4 shows how an HTML page is put together. It comprises the
fundamental building blocks from which all web pages are constructed.

Principles of Programming and Web Technologies 103


kn Unäv

Figure 4.4 :Basic Structure of HTML page


A doctype, also known as a document type declaration, is a directive that informs the web
browser of the markup language used to create the current page. It's neither an element nor a tag.
There is no case distinction in the declaration of the doctype. The <html> tag is used to specify the
HTML document's root element. This tag informs the browser that it is an HTML document. It is
the second outer container element that holds every other element. The head section of an HTML
document, which contains information about the document, is defined by the header element. On
the front end of a website, elements within the head tag are hidden. The whole visible content of a
webpage is contained within the body element. In other words, the body content is what the front-end
user of the browser will see. The head and body sections are the two primary sections of an HTML
page. The head section contains the metadata, or data, that describes the page, whereas the body
section contains all the tags required to represent the visible content of the web page. Because HTML
is a platform-independent language, it may be used on any operating system, including Windows,
Linux, Mac OS, and others.

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:

104 Principles of Programming and Web Technologies


kn Unäv

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.

Principles of Programming and Web Technologies 105


kn Unäv

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

Attribute Value Description

accesskey Shortcut key Describes a keyboard shortcut to trigger or locate an element.


Gives an element a class name or a space-separated list of
class classname
class names.
contenteditable true/false Whether a user can edit the content of an element is indicated.
Specifies the context menu for the specified element. When the
contextmenu menu-id user presses the right mouse button on an element, a context
menu is displayed.
Specified on any HTML element to store unique information
data-* data
unique to the page.
dir ltr/rtl Specifies the text's base direction of directionality.
draggable true/false Specifies whether or not a particular element is draggable.
copy/move Indicates whether the dragged data is copied, relocated, or
dropzone
link linked when dropped.
hidden hidden Indicates that element is not yet, or is no longer, relevant.

106 Principles of Programming and Web Technologies


kn Unäv

Gives an element a unique ID that must be the only one for


id name
that element across the entire document.
Indicates main language in which element's text will be
lang language-code
written.
Indicates if or not element may be checked for spelling
spellcheck true/false
mistakes.
style style Specifies an element's inline style information.
tabindex number Defines the order in which elements are tabbed.
Gives advisory details on the element. A tooltip would be
title text
appropriate for it.
yes Specifies whether or not a text element's content should be
translate
no translated.
In XHTML documents, specifies the language that will be
xml:lang language-code
used as the main text content for the element.

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 &nbsp;, <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:

108 Principles of Programming and Web Technologies


kn Unäv

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

Table 4.5: Tag list


Tags Description
<b> Physical tag used to bold the text between the tags.
<strong> Logical tag that tells the browser that text is important.
<i> Physical tag used to make italic text.
<em> Logical tag used to display the content in italics.
<mark> Highlight the text.
<u> Underline the text that has been written between them.

Principles of Programming and Web Technologies 109


kn Unäv

<tt> UText may appear in a teletype. (not in HTML5)


<sup> Displays the contents just slightly above the usual line.
<sub> Displays the contents just slightly below the usual line.
<del> Display the deleted contents.
<strike> Draw a strikethrough on a text line. (not in HTML5)
<ins> Shows the added contents.
<big> Used with one conventional unit to increase font size.
<small> Used to reduce font size by one unit from the base font size.

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

<p><a href="https://cdit.org/what-we-are/" target="_top" >About Us</a></p>


<p><a href="https://www.google.com/" target="_blank">Google</a></p>
<a href = "https://cdit.org/"> Click here</a> for our website

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

Principles of Programming and Web Technologies 111


kn Unäv

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 &lt;basefont&gt; 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>

112 Principles of Programming and Web Technologies


kn Unäv

Image Insertion into Webpages


Images are crucial for both beautifying as well as clearly illustrating numerous complicated ideas on
your website. Images are inserted using the tag into HTML texts. Only attributes are present and it is
an empty element. The tag's syntax can be specified using:
<img src="url" alt="some_text">
The src attribute and an alt attribute are required to be included on every image. The image's
location is specified for the browser using the src property. The picture file's URL serves as its
value. When an image is missing or unable to be displayed for some reason, the alt attribute offers
a replacement text. It's worth ought to serve as an adequate replacement for the image. An image's
width and height are specified using the width and height attributes. By default, these properties'
values are translated into pixels. The style element can also be used to define the images' width and
height. Since inline style has top precedence, it prevents style sheets from accidentally modifying the
image size.
The <img> tag has following attributes:
• src: It's used to define the image's path.
• alt: This keyword is used to specify an alternative text for a picture. It is helpful because it
explains to the user what the image represents and because it serves as an alternative text in
case the image cannot be displayed due to a network issue.
• crossorigin: This feature enables the usage of canvas with cross-origin access images imported
from external websites.
• height: It is utilized to specify the image's height.
• width: It is utilized to specify the image's width.
• ismap: It is used to specify an image as a server-side image map.
• loading: It is used to tell a browser whether to load an image right away or wait until certain
requirements are met.
• longdesc: This attribute is used to specify a URL to an image's detailed description.
• referrer-policy: It is used to indicate which referrer information, such as no-referrer, no-
referrer-when-downgrade, origin, origin-when-cross-origin, and unsafe-url, to use when
requesting an image.
• sizes: It's used to determine the dimensions of images for various page layouts.
• srcset: It is used to indicate a collection of picture files to use in certain circumstances.
usemap: It is used to specify an image as a client-side image map.
Unexpected results can occur when an image is scaled up or down to fit various devices (or
screen sizes). Additionally, shrinking the image's dimensions using the width and height attribute
or property does not reduce the size of the original file. To solve these issues, the <picture> tag
in HTML5 allows you to specify several variants of an image to target various device types. The
<picture> element has one or more <img> elements at the end in addition to zero or more <source>
elements, each of which points to a distinct image source. Additionally, each <source> element has

Principles of Programming and Web Technologies 113


kn Unäv

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.

Using Tables in HTML


Data can be organized into rows and columns using an HTML table. An HTML table is a set
of data that is organized into rows and columns, or even a more complicated structure. Tables are
frequently used in data analysis, research, and communication. Tables are helpful for a variety of
activities, including the presentation of text and numerical data. In the tabular form arrangement, it
can be used to compare two or more objects. Databases are built using tables. The <table> element
can be used to build a table. The <tr> elements in the <table> element can be used to construct rows,
and the <td> elements can be used to build columns within a row. Using the "th" element, you may
also designate a cell as the header for a collection of table cells.
Lets look with an example:
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<h2>Books and Authors</h2>
<table>
<tr>
<th>No.</th>
<th>Book Name</th>
<th>Author</th>
<th>Year</th>
</tr>
<tr>
<td>1</td>
<td>The God of Small Things</td>
<td>Arundhati Roy</td>
<td>1997</td>
</tr>
<tr>
114 Principles of Programming and Web Technologies
kn Unäv

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

Principles of Programming and Web Technologies 115


kn Unäv

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.

Using Lists in HTML


A list of information can be presented in a well-organized and coherent way
using HTML lists. Unordered lists, ordered lists, and description lists are the three
types of lists that can be used in HTML, and each has a distinct use and significance.
A list of related things in no particular order is created using an unordered list. Each list item
begins with the <li> element, and the <ul> element is used to build the list. A list of related things can
be made in a certain order using an ordered list. The <ol> element is used to build this kind of list, and
the <li> element is used to begin each list item. When the order of the items in the list matters, ordered
lists are utilized. Numbers are used to identifying the list elements in an ordered list. In an ordered list,
the item numbers normally begin with 1. The start attribute can be used to adjust that, though.
A description list consists of a list of things, each of which has a description or definition.
This was created by using the dl element. Along with the <dt> element, which identifies a term,
and the <dd> element, which specifies the term's definition, the <dl> element is utilized. The terms
and definitions are typically displayed in the definition lists in separate lines with a small amount of
indentation around each term's definition.
<!DOCTYPE html>
<html lang="en">
<body>
<h4>Example for Unordered List</h4>
<ul>
<li>Chocolate Cake</li>
<li>Black Forest Cake</li>
<li>White Forest Cake</li>
</ul>
<h4>Example for Ordered and Nested Unordered List </h4>
<ol>
<li>Chocolate Cake
<ul>
<li>Chocolate Velvet Cake</li>
<li>Chocolate Lava Cake</li>
</ul>

116 Principles of Programming and Web Technologies


kn Unäv

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

Using Forms in HTML


HTML forms are necessary to gather various user inputs, including contact
information like name, email address, and phone number, as well as information like
payment card data, etc. The specific components known as controls included in forms
include input boxes, check boxes, radio buttons, submit buttons, and more. Users typically
finalize a form by changing its controls, such as entering text or selecting options and
sending it to a web server for processing. To build an HTML form, use the <form> tag.
The input element is the one that HTML forms use the most frequently. Depending on the
type attribute, it enables you to specify different kinds of user input fields. A text field, password
field, checkbox, radio button, submit button, reset button, or file select box can all be used as input
elements. HTML5 introduces the following input elements too: color, date, datetime-local, e-mail,
month, number, range, search, tel, time, url, and week.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple HTML Form</title>
</head>
<body>
<form action="/examples/actions/confirmation.php" method="post">
<label>Username: <input type="text" name="username"></label>
<label>Password: <input type="password" name="userpass"></label><br>
Principles of Programming and Web Technologies 117
kn Unäv

<label>Gender: <input type="radio" name="gender" id="male">


<label for="male">Male</label>
<input type="radio" name="gender" id="female">
<label for="female">Female</label></label><br>
<label>Academics: <input type="checkbox" name="academics" id="sslc">
<label for="sslc">SSLC</label>
<input type="checkbox" name="academics" id="degree">
<label for="cricket">Degree</label>
<input type="checkbox" name="academics" id="pg">
<label for="baseball">Post Graduate</label> </label><br>
<label for="file-select">Upload Biodata:</label>
<input type="file" name="upload" id="file-select"> <br>
<label for="address">Address:</label>
<textarea rows="3" cols="30" name="address" id="address"></textarea><br>
<label for="city">City:</label>
<select name="city" id="city">
<option value="sydney">TVM</option>
<option value="melbourne">Thrissur</option>
<option value="cromwell">Kannur</option>
</select><br>
<fieldset>
<legend>Contact Details</legend>
<label>Email:<input type="email" id="myemail" required></label>
<label for="myphone">Phone:</label>
<input type="tel" id="myphone" placeholder="xx-xxxx-xxxx" required>
</fieldset><br>
<label for="mydate">Select Date:</label>
<input type="date" value="2023-02-15" id="mydate"> <br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>

118 Principles of Programming and Web Technologies


kn Unäv

Table 4.6: Lists of most frequently used form element's attribute

Attribute Description

name specifies the form's name.


A list of content types that the server allows, separated by commas. HTML lacks
accept
functionality for

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.

Indicates whether or not a form's browser autofill capability is active. Only in


autocomplete
HTML5

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.

Principles of Programming and Web Technologies 119


kn Unäv

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>

120 Principles of Programming and Web Technologies


kn Unäv

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>

Principles of Programming and Web Technologies 121


kn Unäv

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.

Benefits of using CSS


• CSS reduces time - Once CSS is created, it can be used repeatedly in other HTML pages. Each
HTML element has a style that you can specify and use on as many web pages as you like.
• Pages load more quickly - You do not need to write HTML tag attributes every time if CSS
is being used. You only need to create one CSS rule per tag, and it will be applied to every
instance of that element. As a result, downloading takes less time with less code.
• Simple to maintain - Simply changing the style will cause all the elements across all web
pages to be altered at once, allowing you to make broad changes.
• Superior to HTML styles - CSS provides a far wider range of properties than HTML, so you
can give your HTML page a much better look than you can using HTML attributes.
122 Principles of Programming and Web Technologies
kn Unäv

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

Three Types of CSS


External Style Sheets - The CSS instructions for external style sheets are contained in different files
(with the file extension .css). This CSS file will govern the look and feel of any web page that uses
an external stylesheet. This is how an entire website may be changed at once. And that's perfect if
you want to keep up with the newest trends in web pages without having to rewrite each one! Due
to the ease of maintaining the code, external CSS is the ideal method for changing a website's style
and overall appearance and feel. Instead of making changes to numerous HTML files, we can make
changes directly to one file. It lessens the amount of code lines. This type of CSS uses the style
attribute of an HTML element. Using the <link> element that points to an external CSS file.
<head>
<meta charset="utf-8">
<title>Example of CSS External Style Sheet</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<h1>Heading section</h1>
<p>Paragraph of text.</p>
</body>
Internal Style Sheets – Otherwise known as Embedded Style Sheets. Before any text is listed,
internal styles are positioned at the top of each web page document. This is the next best thing to
external since you can easily identify them and "override" an external style sheet for that one unique
page that wants to violate convention. Internal CSS is typically used when every element on the page
has its own distinct style. This is usually defined in the <head> section of an HTML page, within a
<style> element.
<head>
<title>My HTML Document</title>
<style>
body { background-color:purple; }
p { color: #abb; }

Principles of Programming and Web Technologies 123


kn Unäv

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

Figure 4.5: Defining Header Tag


124 Principles of Programming and Web Technologies
kn Unäv

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.

Table 4.7 : CSS Selectors


CSS
Description & CSS
Selector

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.

Principles of Programming and Web Technologies 125


kn Unäv

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

126 Principles of Programming and Web Technologies


kn Unäv

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.

Table 4.8 : Color Property

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

Principles of Programming and Web Technologies 127


kn Unäv

Hexadecimal is a six-digit system for representing colours. The # sign precedes


the six characters in this notation, which range from 0 to F. The first two digits in
Hexadecimal hexadecimal notation stand for the red (RR) colour value, following two digits for
Notation the green (GG), and final two digits for blue (BB) colour value.
Syntax: tag_name {color:#(0-F)(0-F)(0-F)(0-F)(0-F)(0-F); }
Example: h1{c o l o r : # f f 0 0 0 0 ; t e x t - a l i g n : c e n t e r ; }
It is a short form of Hue, Saturation, and Lightness. The cylindrical coordinate
system is used in this format. The degree of the colour wheel is called hue. Its value
ranges from 0 to 360, with 0 being red, 120 denoting green, and 240 denoting blue.
Saturation is expressed as a percentage, with 100% denoting complete saturation
HSL and 0% denoting complete desaturation . Lightness is measured as a percentage,
with 100% being white and 0% denoting black.
Syntax: tag_name { color: hsl(H, S, L);}
Example: h1{color:rgb (120, 100%, 30%); text-align:center;}
While the HSLA colour property is identical to the HSL property, it differs in that it
contains the letter A (Alpha), which designates an element's transparency.
HSLA
Syntax: tag_name { color: hslA(H, S, L, A);}
Example: h1{color:rgba(20,50%,50%,0.5); 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.

Figure 4.6 : Setting Border Property

128 Principles of Programming and Web Technologies


kn Unäv

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

Formatting Text with CSS


CSS offers a number of properties that make it simple and efficient to specify different
text styles, including colour, alignment, spacing, decoration, transformation, etc. Text-align, text-
decoration, text-transform, text-indent, line-height, letter-spacing, word-spacing, and other text
attributes are frequently used. You have precise control over how the characters, words, spaces, and
other elements look because to these attributes.
The horizontal alignment of a text can be changed using the text-align attribute. A text can be
justified, centred, or aligned to the left or right. Text decorations can be added or removed using the
text-decoration property. For a text to have uppercase and lowercase letters, use the text-transform
attribute. The initial line of a text's indentation can be set using the text-indent property. The distance

Principles of Programming and Web Technologies 129


kn Unäv

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

Styling using Fonts


For text to be readable on a page, the proper font and style must be used. For styling the
text's font, CSS offers a number of attributes, such as changing the font's face, adjusting its size and
boldness, managing variants, etc.
The fonts to be used to render the text is specified by the font-family attribute. Serif, Sans-
serif, Monospace, Cursive, and Fantasy are among the five generic font families in CSS. An element's
text content can have its font face style changed using the font-style property. There are three font
styles: normal, italic, and oblique. The normal value is the default. The font-size attribute is used to
specify the font size for an element's text content. Font size values can be specified in a number of
ways, including with keywords, percentages, pixels, ems, etc. Font-size can also be carried out using
keywords. One of the following keywords can be used to specify an absolute font size: xx-small,
x-small, small, medium, large, x-large, or xx-large. Whereas, the keywords smaller or larger might
be used to specify a relative font size. The font's weight or boldness is specified via the font-weight
property. The following possible values for this attribute include inherit, normal, bold, bolder, lighter,
100, 200, 300, 400, 500, 600, 700, 800, and 900. The specific small-caps form of the text can be
displayed thanks to the font-variant property. Sample code:
p.normal {
font-style: italic;
font-family: Arial, Helvetica, sans-serif;
font-size: 24px;
font-weight: bold;
font-variant: small-caps;
}

130 Principles of Programming and Web Technologies


kn Unäv

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>

Horizontal and Vertical Align


The align property of CSS is used to position the elements as well as control how much space
is left around and between content items. The components might be vertically or horizontally aligned.
Principles of Programming and Web Technologies 131
kn Unäv

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

132 Principles of Programming and Web Technologies


kn Unäv

.down { background: #b0d878;


position: absolute;
right: 0;
}

Outline Properties of CSS


You can specify an outline area around the box of an element using the CSS outline attributes.
A line that is drawn just outside the border edge of the elements is called an outline. The focus or
active states of items like buttons, links, form fields, etc. are typically indicated by outlines. The
outline-style property can have one of the following values: none, solid, dashed, dotted, double, inset,
outset, groove, and ridge. Borders and outlines both differ from each other in following ways:
Because they are always positioned on top of the element's box, outlines do not occupy any more
space on the page even though they may otherwise overlap adjacent elements.
Contrary to borders, outlines do not permit us to set the width, colour, or style of each edge individually.
On all sides, an outline is the same.
Beyond overlapping, outlines have no effect on the components around them.
Outlines, as opposed to borders, do not alter the size or location of the element.
Although outlines can be non-rectangular, circular outlines cannot be made.
Sample code is as follows:
p.dashed {
outline-style: dashed;
outline-color: #0000ff;
}

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

Principles of Programming and Web Technologies 133


kn Unäv

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

134 Principles of Programming and Web Technologies


kn Unäv

elliptical pattern. The syntax for generating a radial gradient is as follows:


radial-gradient(shape size at position, color-stop1, color-stop2, ...);
Example:
.gradient {
width: 450px;
height: 380px;
background: radial-gradient(red, yellow, green);
}
The final shape of the radial gradient is specified using the shape argument of the radial-
gradient() function. Circle or ellipse values are acceptable. Here is an example:
.gradient {
width: 480px;
height: 360px;
background: radial-gradient(circle, red, yellow, lime);
}

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.

Advantages of using JavaScript


• A website that uses JS is more dynamic and interactive.
• In order to avoid having to compel the user to reload the page, JS can be used to make your
website deliver immediate feedback.
• JS can be used to execute commands based on user interactions with your website, including
mouse clicks, form submissions, button clicks, and many more.
• By ensuring that user inputs are legitimate before any data is sent to the server, JS can reduce
server traffic.
• JS can be used to store client-side cookies so that users can view/remove the data afterwards.
• Async HTTP requests can be used in JS to load data from the server.

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

• The appearance of dialogue boxes and pop-up windows.


• Displaying clocks, calendar, etc.

There are two ways to add JavaScript to your HTML file:


• Internal JS: - By placing the JS code inside the <script> & </script> tags, we can easily add
it to our HTML file. Depending on the situation, the <script> tag may be inserted either inside
the <head> or the <body> tags.
• External JS: - The JS code can be pasted into a file that has an extension .(dot)js. After creating
the file, include it in the <script src="file name.js"> tag so that it may be imported inside the
HTML file's <head> or <body> tags. JavaScript files that have already been cached can speed
up page loading. External JS makes HTML and JavaScript simpler to read and manage.
The HTML and JavaScript codes are separated by these external JS. It also emphasises code
reusability by allowing JavaScript Code to be used in numerous HTML files.
Simple example to demonstrate the JS programming:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("V learn about scripting")
//-->
</script>
</body>
</html>
You should put the script in the head as shown if you want it to run when a certain event
occurs, such as when a user clicks anywhere.
<html>
<head>
<script type="text/javascript">
<!--
function firstProgram() {
alert("Welcome to the Programming world")
}
//-->
</script>
</head>

Principles of Programming and Web Technologies 137


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.

Statements in JS are made up of Values, Operators, Expressions, Keywords, and Comments.


// is used for single line comment while /*---*/ is used for commenting multiline or block of codes.
JS comments describe the structure of the code. If necessary, they can also be used to stop a piece
of code from running. While the compiler is running the code, comments are ignored. Because they
provide users with code explanations, comments are user-friendly. A JS variable simply refers to the
name of the storage space where data will be kept. In JS, there are two different kinds of variables:
local variables and global variables. JS has three kinds of variable declarations.
• var - Declares a variable, optionally initializing it to a value. example:- var name, place.
Depending on the execution context, this syntax can be used to declare both local and global
variables.
• let - Declares a block-scoped, local variable, optionally initializing it to a value. example:- let
a=15. Local variables with a block scope can be declared using this syntax.
• const - Declares a block-scoped, read-only named constant. example:- const f = 5.6 ; A block-
scope local variable may be declared using this syntax. Const variables cannot be redefined
or assigned again.

138 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 139


kn Unäv

result = (c && d);


document.write(result);
document.write(linebreak);
document.write ("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>You may give different values and then try yourself...</p>
</body>
</html>
A collection of elements can be stored in an object called an array. When you need to store
a lot of the same type of data in one place, arrays come in incredibly handy. Numerous attributes
and methods provided by the Array object enable developers to work with arrays quickly and
effectively. You can obtain a property's value by specifying arrayname.property and a method's output
by specifying arrayname.method. The following program shows the working of different methods
available in array:
<html>
<head>
<title>Arrays Demonstrations </title>
<script type="text/javascript">
var namevalues = new Array("Ram", "Vaiga", "Ravija", "Kannan", "Arunima", "Sradha");
Array.prototype.displayItems=function(){
for (i=0;i<this.length;i++){
document.write(this[i] + "<br />");
}
}
document.write(" The array containes following names : <br />");
namevalues.displayItems();
document.write("<br /> No. of items using length() in array " + namevalues.length + "<br
/>");
document.write("<br />The array in the SORTED format using sort() <br />");
namevalues.sort();

140 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 141


kn Unäv

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.

142 Principles of Programming and Web Technologies


kn Unäv

for (initialization; test condition; increment/decrement)  {    


//code to be executed  
}  
Even before the looping code is started, the initialization is executed first. In order to assign
values to variables that will be used inside the loop, this statement is typically used. The loop's
execution condition is stated in test condition. The very time the looping code is performed, the
increment/decrement is also operate.
<html>
<head>
<script type="text/javascript">
var namevalues = new Array("Ram", "Vaiga", "Ravija", "Kannan", "Arunima", "Sradha")
document.write("<b>Using for loops </b><br />");
for (i=0;i<namevalues.length;i++)
{
document.write(namevalues [i] + ", ");
}
</script>
</head>
<body></body>
</html>
while loop :- This loop iterates the elements for the infinite number of times. It is normally used when
the number of iteration is unknown. The syntax is given below.
while(condition)  {    
code to be executed  
}  
Lets look to an example:
<html>
<body>
<script type = "text/javascript">
var count = 0;
document.write("Loop begins <br />");

while (count < 15) {


document.write("Current value: " + count + "<br />");
Principles of Programming and Web Technologies 143
kn Unäv

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

144 Principles of Programming and Web Technologies


kn Unäv

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 }

Principles of Programming and Web Technologies 145


kn Unäv

An evaluation of a JS expression occurs here. The specified statement(s) are performed if


the result is true. No statement would be executed if the expression were false. Lets look to a simple
example :
<html>
<body>
<script type = "text/javascript">
<!--
var num= 25;
if( num > 23) {
document.write("<b> less than the num declared</b>");
}
//-->
</script>
<p> try with number less than 25...</p>
</body>
</html>
The next type of control statement that enables JavaScript to execute statements in a more
controlled manner is the "if...else" statement. The general syntax is as follows:
if (expression) {
// statements to execute if true
} else {
// statements to execute if false
}
To understand how to use an if-else statement in JS, try the following code.
<html>
<body>
<script type = "text/javascript">
<!--
var num= 25;
if( num > 45) {
document.write("<b> less than the number declared</b>");
}
else

146 Principles of Programming and Web Technologies


kn Unäv

{document.write("<b> greater than the number declared</b>");}


//-->
</script>
</body>
</html>
The "if...else if..." statement is an improved version of the if...else statement that enables
JavaScript to correctly choose amongst a number of conditions. The general syntax is as follows:
if (expression 1) {
// statements to executed if expression 1 is true
} else if (expression 2) {
// statements to executed if expression 2 is true
} else if (expression 3) {
// statements to executed if expression 3 is true
} else {
//statements to be executed if no expression is true
}
Let's have a look at a basic example of a JS if else statement.
<html>
<body>
<script>
var a=30;
if(a==10){
document.write("a is equal to 10");
} else if(a==15){
document.write("a is equal to 15");
} else if(a==20){
document.write("a is equal to 20");
} else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
Principles of Programming and Web Technologies 147
kn Unäv

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:

148 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 149


kn Unäv

Mouse click onclick When mouse click on an element


mouseover onmouseover When cursor of the mouse comes over an element
mouseout onmouseout When the cursor of the mouse leaves any element
mousedown onmousedown When the mouse button is pressed over an element
mouseup onmouseup When the mouse button is released from an element
mousemove onmousemove When the movement of the mouse takes place.
Form focus onfocus When the user focuses on any element
submit onsubmit When the user submits the form
blur onblur When the focus is away from a form element
change onchange When user modifies/changes value of a form
element
reset onreset Script runs when the form is reset
select onselect Script runs when the element is selected
Window Load onload Script runs when any HTML document loads

unload onunload Script runs when a visitor leaves current HTML


document
resize onresize When the visitor resizes the window of the browser

Lets look to an example:


<html>
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#AD4A98;width:200px;height:20px;padding:40px;">
Place the Mouse Over Me</div>
<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}
function mOut(obj) {
obj.innerHTML = "Again place Mouse over me"
}
</script>
</body>
</html>
The above example demonstrates the working of mouse event. You may try with other events
that are given in above table yourself for understanding each events and how it makes the webpage
interactive.

150 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 151


kn Unäv

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

152 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 153


kn Unäv

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

154 Principles of Programming and Web Technologies


kn Unäv

<table cellspacing = "2" cellpadding = "2" border = "1">


<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr> <tr>
<td align = "right">E-Mail</td>
<td><input type = "text" name = "EMail" /></td>
</tr> <tr>
<td align = "right">PinCode</td>
<td><input type = "text" name = "Pin" /></td>
</tr><tr>
<td align = "right">State</td>
<td>
<select name = "State">
<option value = "-1" selected>[select yours]</option>
<option value = "1">AndraPradesh</option>
<option value = "2">Andaman & Nicobar</option>
<option value = "3">Goa</option>
<option value = "4">Karnataka</option>
<option value = "5">Kerala</option>
<option value = "6">Lakshadweep</option>
<option value = "7">Tamilnadu</option>
<option value = "8">Telangana</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>

Principles of Programming and Web Technologies 155


kn Unäv

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

156 Principles of Programming and Web Technologies


kn Unäv

Module V
Introduction to PHP and Python Programming

Introduction to PHP Programming


A computer language called PHP enables site designers to build dynamic content that
communicates with databases. The acronym PHP, which originally stood for "Personal Home Pages,"
has been changed to "Hypertext Preprocessor". Rasmus Lerdorf first developed PHP in 1994. PHP
is mostly used to create web-based software programs. PHP is a server-side scripting language for
HTML embedded pages. Open source software like PHP is free to use and the scripts are run on
the server. Numerous well-known databases, such as MySQL, PostgreSQL, Oracle, Microsoft SQL
Server, Sybase, and others, can be integrated with PHP. Multiple platforms like Unix, Linux, Windows
support PHP. PHP is compatible with nearly all modern web servers like Apache, IIS, etc. HTML tags,
scripts, and plain text can all be found in PHP files. PHP, php3, or phtml are all acceptable extensions
for PHP files. The most widely used web backend programming language is PHP. A PHP script can
be executed via the command line or as a web server module. PHP 7 is the most recent major version.
• Server-side scripting – PHP is a good choice for creating dynamic websites and web application
• Command-line scripting –Similar to Python and Perl, PHP scripts may be executed from
the command line to carry out administrative operations like creating PDF files and sending
emails.
We mostly use PHP in three different areas:
• Server-side Scripting– This is PHP's most established and primary application area. A PHP
parser, a web server, and a web browser are needed for this to function. The web server runs
with a connected PHP installation. With a web browser and a server-based PHP page, you may
view the output of the PHP application.
• Command line Scripting– PHP script can function independently of a server or browser. For
command line scripting, only the PHP parser is required. This kind of application is perfect for
scripts that are run on a regular basis by cron on Linux or Task Scheduler on Windows. Simple
text processing tasks can also be accomplished with these programmes.
• Writing desktop applications – To create a desktop application with a graphical user interface,
PHP is probably not the best language to employ. However, if you are knowledgeable about
PHP, you can develop client-side programmes that employ PHP-GTK and certain sophisticated
PHP features. In this way, you can also create cross-platform applications.

Why use PHP


Actually, PHP can perform any task associated with server-side scripting, also referred to as
the backend of a website. For instance, PHP can send emails, create sessions, deal with databases,
Principles of Programming and Web Technologies 157
kn Unäv

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.

How PHP Works


PHP needs to be installed on your server in order for it to interpret PHP scripts. On your PC
through your web browser, you employ PHP as a server-side language for local website activities.
Accessing PHP programs requires a web browser. Your web browser sends requests to the server is
known as server-side activity. JavaScript, CSS, or HTML will provide instructions to your browser so
it can translate the content you see on the screen. Your web browser then follows these instructions
and performs them. Your web server sends requests to the server using hardware or software. Your
request will produce HTML code, which your browser will then translate into content to display
on your screen. Your content is saved on your web servers as follows: Site pages or media or other
resources. The working of PHP is depicted in the following diagram Figure 5.1:

158 Principles of Programming and Web Technologies


kn Unäv

Figure 5.1 : Php Work flow


Working:
• The web browser first sends an HTTP request, such as index.php, to the web server.
• Second, the web server's PHP preprocessor works with PHP code to create the HTML content.
• Third, the HTML file is returned to the web browser by the web server.

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.

Principles of Programming and Web Technologies 159


kn Unäv

• Access cookie variables and create cookies.


• PHP enables you to limit user access to specific web pages.
• Data can be encrypted.

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>

The figure below illustrates the structure of a PHP code.

Let’s look into a simple program


<html>
<head>
<title>PHP - First Example</title>
</head>
<body>
Principles of Programming and Web Technologies 161
kn Unäv

<?php echo "Welcome to world of PHP Programming";?>


</body>
</html>

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

Case Sensitivity in PHP


PHP takes case into account when naming variables. As a result, $colour, $Color, and $COLOR
are all regarded as separate variables. Let’s look into an example:-
<?php // Assign value to variable
$colour = "red";
// Try to print variable value
echo "Rose is " . $Colour;
echo "Rose is " . $COLOR ;
echo "Rose is " . $colour ; ?>
The "Undefined variable" warning will be displayed for the variables $Colour and $COLOUR
and just the value of the variable $colour will be displayed if you try to run the example code from
above.

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.

162 Principles of Programming and Web Technologies


kn Unäv

• 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

Principles of Programming and Web Technologies 163


kn Unäv

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

Data Types in PHP


PHP variables can have values of a variety of data kinds, from straightforward string and
numeric types to more complicated data types like arrays and objects. Eight primitive data types are
supported by PHP in total:
• integer
• float (floating point number or double)
• string
• boolean
• array
• object
• resource
• NULL

164 Principles of Programming and Web Technologies


kn Unäv

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)

Principles of Programming and Web Technologies 165


kn Unäv

$e = 0123; // octal number


var_dump($e); # output = int(83)
?>
var_dump() function returns the data type and value.
Float- A float (floating point number or double) is a number with either a decimal point or a number
in exponential form.
<?php
$a = 12.2467;
var_dump($a); # output - float(12.2467)
echo "<br>";
$b = 11.4e2;
var_dump($b); # output - float(1140)
echo "<br>";
$c = 5E-16;
var_dump($c); # output - float(5.0E-16)
?>
Boolean- A Boolean represents two possible states: TRUE or FALSE.
<?php
// Assign the value TRUE to a variable
$a = true;
var_dump($a); # Output - bool(true)
?>
Array - A variable that can store multiple values at once is called an array. In other words, in a single
variable, an array stores several values. It is useful to group together a number of comparable items,
such as a list of nation or city names. A formal definition of an array is an indexed grouping of data
items. An array's indexes, which are often referred to as keys, are all distinct and point to the same
value.
<?php
$fruits = array("Mango", "Apple", "Orange");
var_dump($fruits); # array(3) { [0]=> string(5) "Mango" [1]=> string(5) "Apple" [2]=> string(6)
"Orange" }
echo "<br>";
echo "<br>";

166 Principles of Programming and Web Technologies


kn Unäv

$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" }

Principles of Programming and Web Technologies 167


kn Unäv

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

168 Principles of Programming and Web Technologies


kn Unäv

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

Operator Name Example Result


+ Addition $a+ $b Sum of $a and $b
- Subtraction $a- $b Difference of $a and $b
* Multiplication $a* $b Product of $a and $b
/ Division $a/ $b Quotient of $a and $b
% Modulus $a% $b Remainder of $a divided by $b

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

Principles of Programming and Web Technologies 169


kn Unäv

Assignment operators-To write a value to a variable, these operators are combined with numeric
values.
Table 5.2 : Assignment Operators

Operator Name Example Result

= Assign $a= $b $a= $b

+= Add and assign $a+= $b $a= $a+ $b

-= Subtract and assign $a-= $b $a= $a- $b

*= Multiply and assign $a*= $b $a= $a* $b

/= Divide and assign quotient $a/= $b $a= $a/ $b

%= Divide and assign modulus $a%= $b $a= $a% $b

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

170 Principles of Programming and Web Technologies


kn Unäv

Comparison Operators- To compare two values, use the PHP comparison operators (number or string).
Table 5.3 : Comparison Operators

Operator Name Example Result

== Equal $a== $b True if $a is equal to $b


True if $a is equal to $b, and they are of the same
=== Identical $a=== $b
type
!= Not equal $a!= $b True if $a is not equal to $b

<> Not equal $a<> $b True if $a is not equal to $b


True if $a is not equal to $b, or they are not of the
!== Not identical $a!== $b
same type
< Less than $a< $b True if $a is less than $b

> Greater than $a> $b True if $a is greater than $b


Greater than or
>= $a>= $b True if $a is greater than or equal to $b
equal to
Less than or
<= $a<= $b True if $a is less than or equal to $b
equal to

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

Principles of Programming and Web Technologies 171


kn Unäv

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

Operator Name Example

++$a Pre-increment Increments $a by one, then returns $a

$a++ Post-increment Returns $a, then increments $a by one

--$a Pre-decrement Decrements $a by one, then returns $a

$a-- Post-decrement Returns $a, then decrements $a by one

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

172 Principles of Programming and Web Technologies


kn Unäv

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

Operator Name Example Result

and Logical AND $x and $y True if both the operands are true else false

or Logical OR $x or $y True if either of the operands is true else false


True if either of the operands is true and false if
xor Logical XOR $x xor $y
both are true
&& Logical AND $x && $y True if both the operands are true else false

|| Logical OR $x || $y True if either of the operands is true else false

! Logical NOT !$x True if $x is false

You may look at the given example for better understanding.


<?php
$x = 50;
$y = 30;
if ($x == 50 and $y == 30)
echo "and Success \n"; # ouputs - and Success
if ($x == 50 or $y == 20)
echo "or Success \n"; # ouputs - or Success
if ($x == 50 xor $y == 20)
echo "xor Success \n"; # ouputs - xor Success
if ($x == 50 && $y == 30)
echo "&& Success \n"; # ouputs - && Success
if ($x == 50 || $y == 20)
echo "|| Success \n"; # ouputs - || Success
if (!$a)
echo "! Success \n"; # ouputs - Undefined variable $a, ! Success
?>

Principles of Programming and Web Technologies 173


kn Unäv

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

Operator Name Example Result


+ Union $x + $y Union of both
== Equality $x == $y Returns true if both has same key-value pair
!= Inequality $x != $y If both are not equal, it returns True.
Returns True if the key-value pairs for both are
=== Identity $x === $y the same, are in the same order, and are of the
same type.
N o n - If neither of the two is the same as the other, it
!== $x !== $y
Identity returns True.
<> Inequality $x <> $y It returns True if neither is equal.

Let’s look into a simple example:


<?php
$x = array("k" => "Car", "l" => "Bike");
$y = array("a" => "Train", "b" => "Plane");
var_dump($x + $y);
# array(4) {
# ["k"]=>
# string(3) "Car"
# ["l"]=>
# string(4) "Bike"
# ["a"]=>
# string(5) "Train"
# ["b"]=>
# string(5) "Plane"
#}
var_dump($x == $y); # outputs - bool(false)
var_dump($x != $y); # outputs - bool(true)
var_dump($x <> $y); # outputs - bool(true)
var_dump($x === $y); # outputs - bool(false)
var_dump($x !== $y); # outputs - bool(true)
?>
174 Principles of Programming and Web Technologies
kn Unäv

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

$x < $y ($x <=> $y) === -1

$x <= $y ($x <=> $y) === -1 || ($x <=> $y) === 0

$x == $y ($x <=> $y) === 0

$x != $y ($x <=> $y) !== 0

$x >= $y ($x <=> $y) === 1 || ($x <=> $y) === 0

$x > $y ($x <=> $y) === 1

Principles of Programming and Web Technologies 175


kn Unäv

Lets consider an example:-


<?php
// Comparison of Integers
echo 1 <=> 1; # outputs: 0
echo 1 <=> 2; # outputs: -1
echo 2 <=> 1; # outputs: 1
// Comparison of Floats
echo 1.5 <=> 1.5; # outputs: 0
echo 1.5 <=> 2.5; # outputs: -1
echo 2.5 <=> 1.5; # outputs: 1
// Comparison of Strings
echo "a" <=> "a"; # outputs: 0
echo "a" <=> "b"; # outputs: -1
echo "b" <=> "a"; # outputs: 1
?>

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.

176 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 177


kn Unäv

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

178 Principles of Programming and Web Technologies


kn Unäv

4) Nested if...else statements


When you find if...else statements inside an if...else statement the statements are nested.
With this statement, you can get alternatives results when a condition is true or false.
Syntax:
if (condition 1 )
{
if (condition 2 )
{
// code1 to be executed
}
else
{
// code 2 to be executed
}
}
else
{
// code 3 to be executed
}
<?php
$number1 = 40;
$number2 = 12;
if ($number1 != $number2) {
echo 'number1 is different from number2';
echo '<br>';
if ($number1 > $number2) {
echo 'number1 is greater than number2';
} else {
echo 'number2 is greater than number1';
}
} else {
echo 'number1 is equal to number2';
} ?>

Principles of Programming and Web Technologies 179


kn Unäv

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;

180 Principles of Programming and Web Technologies


kn Unäv

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

Null Coalescing Operator


The null coalescing operator (??) is a binary operator that is used to return the first operand
if it exists and is not null or undefined; otherwise, it returns the second operand. It is also known
as a double question mark operator. To use the null coalescing operator in PHP, simply use
the ?? between two expressions or variables. The syntax is as follows:
$anyVariable = $firstOperand ?? $secondOperand
In cases where a ternary operator is required in conjunction with the isset() function, PHP
7 adds a new null coalescing operator (??) that can be used as a shorthand. Consider the following
code example to better understand this. If $_GET['name'] is null or empty, anonymous is returned.
Otherwise, it retrieves the value of $_GET['name'].
<?php $name = isset($_GET['name']) ? $_GET['name'] : 'anonymous'; ?>
The same code could be expressed as follows when using the null coalescing operator:
<?php $name = $_GET['name'] ?? 'anonymous';?>
Principles of Programming and Web Technologies 181
kn Unäv

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

182 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 183


kn Unäv

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

184 Principles of Programming and Web Technologies


kn Unäv

Introduction to Python

Python is a powerful, object-oriented, high-level programming language. It is a general-


purpose programming language that is frequently used for scripting. Python has the same interface
across all hardware platforms and can be executed on a variety of them. Python is therefore both a
programming language and a scripting language. It is also known as an interpreted language.
It is used for:
• Web Development (server-side)
• Software Development
• Mathematics
• System Scripting
In several fields, like Automation, Big Data, Artificial Intelligence, etc., it is an extremely
popular language. Python is extensively used in advanced computer science disciplines such as
Artificial Intelligence, Natural Language Generation, Neural Networks, and others.
Python's features include −
• Easy to learn − it has a minimal set of keywords, a simple structure, and a concise syntax.
This allows the learner to catch up with the language quickly. The primary goal of every
programming language is to bridge the communication gap between programmers and
computers. Python, with its clear and simple rules, is even closer to English. Due to its ease of
use, Python programming has been nicknamed "programming at the speed of thought."
• Easy to read − the code is more readable and well-defined. It is a simple and minimalistic
language. It almost seems like reading English with very rigid English grammar while reading
a good Python program. One of Python's most advantageous features or strength is that it is a
pseudo-code language. Instead of focusing on the language itself, it enables one to concentrate
on finding a solution to the issue.
• Easy-to-maintain − source code is fairly easy-to-maintain.
• Interpreted language − you don't need to compile the program before running it because the
interpreter, like in the case of PHP or PERL, processes the language during runtime.
• A broad standard library − most of the Python library runs smoothly on UNIX, Windows, and
Macintosh platforms and is extremely portable.
• Interactive Mode − supports an interactive mode that enables real-time testing and debugging
of code fragments.
• Portable − is a cross-platform programming language, which means it may be used on many
different operating systems, including Windows, Mac OS X, Linux, and Unix. It is free and
open source.
• Objected Oriented - supports both object-oriented and procedure-oriented programming. In
procedure-oriented languages, the program is built around procedures or functions which are
nothing but reusable pieces of programs whereas in object-oriented languages, the program
Principles of Programming and Web Technologies 185
kn Unäv

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.

Figure 5.2 : Python Shell

186 Principles of Programming and Web Technologies


kn Unäv

Running Python programs


You can run python programs from files, just like perl or shell scripts, by typing “python
program.py” at the command line. The file can contain just the python commands. Even, one can
invoke the program directly by typing the name of the file, “program.py”, if it has as a first line
something like “#!/usr/bin/python”. Alternatively, you can enter a python shell and run python
commands interactively, by typing “python”

Compiling and Interpreting


Many languages require you to compile (translate) your program into a form that the machine
understands. In Python the application need not be compiled and built into an executables to run. Python
interpreter takes each line of code, interprets & executes it. Python is instead directly interpreted into
machine instructions.
Here's an example of a python program run as a script:
#!/usr/bin/python
print (“Hello, world”)

Figure 5.3 : Python Workflow


If this is saved to a file hello.py, then run from it as python hello.py When this program is executed,
prints the output as :
# Hello, world

Taking input from console in Python


Console (also called Shell) is basically a command line interpreter that takes input from the
user i.e one command at a time and interprets it. If it is error free then it runs the command and gives
required output otherwise shows the error message. A Python Console looks like this.

Figure 5.4 : Console Window

Principles of Programming and Web Technologies 187


kn Unäv

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

188 Principles of Programming and Web Technologies


kn Unäv

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.

Figure 5.5 : Keyword List – Python 3.10

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

Principles of Programming and Web Technologies 189


kn Unäv

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

Python Variables and Datatypes


Variables are memory locations that store some data. Any type of value, including numeric,
textual, and Boolean (true/false) values, can be stored in a variable. Python is not a strongly typed
language. In Python, everything is an object, including variables, functions, and modules. Python
automatically detects a literals type at runtime based on its grammar. The value is what the type is
connected to. As a result, different Python data types can have different values associated with the
same variable's label. As a result, the label of the same variable can refer to values of various Python
data types. When declaring a variable in the majority of programming languages, such as C, C++,
JAVA, etc., the data type of the variable must be specified. For instance, defining an integer variable
called "n" doesn't need you to say int n = 10. The type of the variable "n" will be implicitly known
at runtime when we write n = 10 in Python. Python also supports multiple variable assignment other
than single variable assignment. A variable can have a short name or a more descriptive name. Rules
for variables:
• Variable name must start with a letter or an underscore character
• Variable name cannot start with a number
• It can only contain alpha-numeric characters & underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• Keywords cannot be used as a variable name.
A data type defines the format of the data so that a program could use it appropriately.
However, Python data types are just more than that. In Python, the declaration of a variable explicitly

190 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 191


kn Unäv

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.

Principles of Programming and Web Technologies 193


kn Unäv

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

float(x) Converts x to a floating point number

str(x) Converts x to a string. x can be of the type float. integer or long.

hex(x) Converts x integer to a hexadecimal string

chr(x) Converts x integer to a character

ord(x) Converts character x to an 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

Principles of Programming and Web Technologies 195


kn Unäv

Table 5.10 : Type codes for datatype


Type code Type Datatype Byte size
'B' unsigned integer int 1
'b' signed char int 1
'u' Py_UNICODE Unicode character 2
'h' signed short int 2
'H' unsigned short int 2
'i' signed int int 2
'I' unsigned int int 2
'l' signed long int 4
'L' unsigned long int 4
'f' float float 4
'd' double float 8


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)

196 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 197


kn Unäv

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

The len() function to determine the size of an array.


from array import *
array1 = array('i', [2,3,6,8,10])
array2 = [[1,2],[1,2,3,4]]
print('size of array1 -- > ',len(array1)) # size of array1 -- > 5
print('size of array2 -- > ',len(array2)) # size of array2 -- > 2
print('size of first element array2 -- > ',len(array2[0])) # size of first element array2 -- > 2
print('size of second array2 -- > ',len(array2[1])) # size of second array2 -- > 4

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]

198 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 199


kn Unäv

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

Operator Functionality Example

AND Returns true of the all the conditions are true (o1 and o2) is false

OR Returns true if any of the condition is true (o1 or o2) is true

NOT Return the reverse of the actual logical state Not(o1) is false

a=int(input()) #take user input as int


# logical AND operation
if a%4==0 and a%3==0:
print("divided by both 4 and 3")
# logical OR operation
if a%4==0 or a%2==0:
print("either divided by 4 or 3")
# logical NOT operation
if not(a%4==0 or a%3==0):
print("neither divided by 4 nor 3")

Comparison operators - In Python programming, comparison operators allow us to determine whether


two values are equal or if one is greater than the other and then make a decision based on the result.
Table 5.13 : Comparison Operators

Operator Purpose Usage


if the left operand is greater than the right, then it returns
> Greater than a >b
true.
if the left operand is less than the right, then it returns
< Less than a<b
true.
== Equal to if two operands are equal, then it returns true. a==b
!= Not equal to if two operands aren’t equal, then it returns true. a!=b
>= Greater than if the left operand is greater than or equal to the right, a>=b
or equal then it returns true.
<= Less than or if the left operand is less than or equal to the right, then
a<=b
equal it returns true.

200 Principles of Programming and Web Technologies


kn Unäv

# create two variables


a=15
b=25
print(a==b)# False
print(a!=b)# True
print(a>b)# False
print(a<b)# True
print(a>=b) # False
print(a<=b) # True

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

Operator Description Usage

Bitwise AND – compares two operands on a bit level


& a&b
and returns 1 if both the corresponding bits are 1

| Bitwise OR – compares two operands on a bit level and


a|b
returns 1 if any of the corresponding bits is 1

~
Bitwise NOT – inverts all of the bits in a single operand ~a

^ Bitwise XOR – compares two operands on a bit level


and returns 1 if any of the corresponding bits is 1, but a^b
not both

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

Principles of Programming and Web Technologies 201


kn Unäv

#create two variables


a=10 # binary 1010
b=8 # binary 1000
print(a&b) # 8
print(a|b) # 20
print(a^b) #2
print(~a) #11
print(a<<1)
#20
print(a>>1) # 5

Assignment operators- Assignment operators are used in Python to assign values to variables.
Table 5.15: Assignment Operators

Operator Description Usage


Assigns values from right side operands to left side c = a + b assigns value
=
operand of a + b into c
It adds right operand to the left operand and assign the c += a is equivalent to
+=
result to left operand c=c+a
It subtracts right operand from the left operand and c -= a is equivalent to c
-=
assign the result to left operand =c-a
It multiplies right operand with the left operand and c *= a is equivalent to c
*=
assign the result to left operand =c*a
c /= a is equivalent to c
It divides left operand with the right operand and
/= = c / ac /= a is equiva-
assign the result to left operand
lent to c = c / a
It takes modulus using two operands and assign the c %= a is equivalent to
%=
result to left operand c=c%a
Performs exponential (power) calculation on operators c **= a is equivalent to
**=
and assign value to the left operand c = c ** a
It performs floor division on operators and assign value c //= a is equivalent to
//=
to the left operand c = c // a

202 Principles of Programming and Web Technologies


kn Unäv

# take two variable, assign values with assignment operators


a=6
b=8
print("a: "+str(a)) # 6
print("b: "+str(b)) # 8
a+=b
print("a: "+str(a)) # 14
a*=b
print("a: "+str(a))# 112
a/=b
print("a: "+str(a)) # 14.0
a%=b
print("a: "+str(a)) # 6.0
a**=b
print("a: "+str(a)) # 1679616.0
a//=b
print("a: " +str(a))# 209952.0

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

Operator Description Usage

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)

X1 = 'Python Programming !!!!'


X2 = 34567
Y1 = 'Python Programming !!!!'
Y2 = 34646

Principles of Programming and Web Technologies 203


kn Unäv

print(X1 is Y1) # True


print(X1 is not Y1) # False
print(X1 is not Y2) # True
print(Y1 is X2) # False
print(X2 is Y2) # False

Membership operators- Membership operators enable us to test whether a value is a member of


another Python objects such as strings, lists, or tuples.
Table 5.17 : Membership Operators

Operator Description Usage

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x

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)

Operator Precedence and Associativity


The order in which operations are computed is known as operator precedence. The Python
interpreter prioritises operators and executes them in a predefined sequence. Depending on whom you
speak with, this is referred to as the operator precedence or the order of operations. The order in which
the expressions are evaluated is specified by well-defined rules in Python. When two operators share
an operand, the higher precedence operator will take precedence. However, parentheses ( ) can be
used to override the operator's precedence. An operator's precedence is increased when it is enclosed
in parenthesis with its operands.

204 Principles of Programming and Web Technologies


kn Unäv

Table 5.18: Operator Precedence

Operator Meaning Precedence


() Parentheses Highest
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
Multiplication, Division, Floor division,
*, /, //, %
Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, Comparisons, Identity, Membership
in, not in operators
not Logical NOT
and Logical AND
or Logical OR Lowest

Conditional Statements ( Decision Making)


Conditional Statements in Python perform different computations or actions depending on
whether a specific Boolean constraint evaluates to true or false. Decision-making is an anticipation
of conditions occurring while executing the program and specifying actions taken according to the
conditions. Conditional statements are handled by IF statements. Python programming language
assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed
as a FALSE value.
if statement
The if statement is one of the most basic forms of logic that can be introduced into program.
The idea of the if statement is to assess whether something is the case, and, if it is, then to perform the
following block of code within the statement.
Syntax:
if Logical_Expression :
Indented Code Block
The if statement evaluates a test, and if it is True, performs the following indented statements;

Principles of Programming and Web Technologies 205


kn Unäv

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

206 Principles of Programming and Web Technologies


kn Unäv

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

# Program to illustrate if-elif-else ladder


i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
# i is 20

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

Principles of Programming and Web Technologies 207


kn Unäv

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

208 Principles of Programming and Web Technologies


kn Unäv

Using Not Operator with If Else


The ‘not’ is a negation logical operator. It reverses the result of its operand and converts to a
boolean outcome, i.e., True or False. The operand could be a variable or an expression evaluating to
a numeric type. Let’s look into a simple example:
i=0
if not i :
print("i is not %d" %(i))
else :
print("i is %d" %(i))

Using And Operator with Python If Else


By using the ‘and’ operator, you can join multiple expression in a if condition. It is also a
logical operator. Let’s look into a simple example:
a = 10
b = 20
avg = (a + b ) / 2
print("avg =", avg) # ('avg =', 15)
if avg > a and avg > b :
print("%d is higher than %d, %d, %d" %(avg, a, b))
elif avg > a:
print("%d is just higher than %d" %(avg, a))
elif avg > b:
print("%d is just higher than %d" %(avg, b))

Using In Operator with If Else


Python “in” operator allows comparing a variable against multiple values in a single line. It
makes decision making more comfortable by reducing the use of many if-elif statements. Let’s look
into a simple example:
num_list = [1, 10, 2, 20, 3, 30]
for num in num_list:
if not num in (2, 3):
print ("Allowed Item:", num)

Principles of Programming and Web Technologies 209


kn Unäv

Switch Case Statement


Switch case is a powerful decision-making construct commonly used in modular programming.
When a conditional block is cluttered with multiple if conditions are not needed, then, a switch case
can give a cleaner way to implement control flow in a program. A switch statement is a multi-way
branch statement that compares the value of a variable to the values specified in case statements.
Python language doesn’t have a switch statement. Python uses dictionary mapping to implement
switch statements in Python. The following steps are used in implementing a switch case statement :
First, define individual functions for every case.
Make sure there is a function/method to handle the default case.
Next, make a dictionary object and store each of the function beginning with the 0th index.
After that, write a switch() function accepting the day of the week as an argument.
The switch() calls the get() method on the dictionary object which returns the function matching the
argument and invokes it simultaneously.

# Implement Switch Case Statement using Dictionary


def monday():
return "monday"
def tuesday():
return "tuesday"
def wednesday():
return "wednesday"
def thursday():
return "thursday"
def friday():
return "friday"
def saturday():
return "saturday"
def sunday():
return "sunday"
def default():
return "Incorrect day"
switcher = {
1: monday,
2: tuesday,

210 Principles of Programming and Web Technologies


kn Unäv

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.

Principles of Programming and Web Technologies 211


kn Unäv

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

212 Principles of Programming and Web Technologies


kn Unäv

for index in range(len(books)):


print('Book (%d):' % index, books[index])
# Book (0): C
# Book (1): C++
# Book (2): Java
# Book (3): Python
# Book (4): 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.

Else Clause with For Loop


Python allows using an optional else statement along with the “for” loop. The code under the
else clause executes after the completion of the “for” loop. The else part is executed if the items in
the sequence used in for loop exhausts. The break statement can be used to stop a for loop. In such
case, the else part is ignored.
Syntax:
for item in sequence:
statement 1
statement 2
if <condition>:
break
else:
statements

Look into the given example:


digits = [2, 4, 6]
for i in digits:
print(i)
else:
print("No items left in list ")

Let’s have a look to another example:


fruits = ['Apple', 'Banana', 'Chikku', 'Gauva', 'Mango', 'Orange']
ignoreElse = False
Principles of Programming and Web Technologies 213
kn Unäv

for thefruit in fruits:


print(thefruit)
if ignoreElse and thefruit is 'Orange':
break
else:
print("No fruits left.")
ignoreElse = True
for thefruit in fruits:
print(thefruit )
if ignoreElse and thefruit is 'Orange':
break
else:
print("No fruits left.")

Break, Continue and Pass Statement in for loop


The break statement is used to exit a loop. The purpose of this statement is to end the execution
of the loop immediately and the program control goes to the statement after the last statement of the
loop. If there is an optional else statement in a loop it skips the optional clause also.
Syntax:
for variable_name in sequence :
statement_1
statement_2
if expression3 :
break
Let’s have a look to an example-
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
num_sum = 0
count = 0
for x in numbers:
num_sum = num_sum + x
count = count + 1
if count == 7:
break
print("Sum of first ",count,"integers is: ", num_sum)

214 Principles of Programming and Web Technologies


kn Unäv

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

#increment the position after printing the letter of that position


pos+=1
Let’s have a look to the given example :-
# add natural numbers upto n
n = 10
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum)

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

216 Principles of Programming and Web Technologies


kn Unäv

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

Syntax for using For Loop:


for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
Let’s look to an example given below:-
words= ["Apple", "Banana", "Chikku" ]
for word in words:
print ("Print each letters of '"+word+"'")
for letter in word:
print (letter)
print("") #This print is used to print a blank line
Syntax for using While Loop:
while expression:
while expression:
statement(s)
statement(s)

Let’s look to an example given below:-


i=2
while(i < 25):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1

Looping Techniques in Python


Python provides built-in functions that allow a variety of looping techniques in various
sequential containers. These methods are primarily very useful in competitive programming and
various project which require a specific technique with loops maintaining the overall structure of

218 Principles of Programming and Web Technologies


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 : ")

Principles of Programming and Web Technologies 219


kn Unäv

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

220 Principles of Programming and Web Technologies


kn Unäv

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

Let’s take an example :


# Program to Access characters of String
var = “PYTHON-PROGRAMMING”
print(var) # PYTHON-PROGRAMMING
print(var[0]) # P
print(var[-1]) # G
Slicing strings
To access a range of characters in the String, method of slicing is used. Slicing in a String is
done by using a ‘slicing operator,’ the colon ‘:’ sign. With the slicing operator, we define the range as
[a:b].
print(var[3:12]) # Prints 3rd to 12th character ie HON-PROGR
print(var[3:-4]) # Printing between 3rd and 4th last character ie HON-PROGRAM

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

new_string = old_string.replace('like', 'love')


print("old string : "+old_string) # old string : I like flowers
print("new string : "+new_string) # new string : I love flowers

Changing case of strings


Case of string can be changed using appropriate methods. Look into following examples:-
string_value="i like flowers"
print(string_value.upper()) # I LIKE FLOWERS
string_value="i like flowers"
string_value="I LOVE FLOWERS"
s=string_value.lower()
print(s) # i love flowers
string_value="i like flowers"
print(string_value.capitalize()) # I like flowers

Unicode String support in Python


Regular Strings stores as the 8-bit ASCII value whereas Unicode String follows the 16-bit
ASCII standard. This extension allows the strings to include characters from the different languages
of the world. In Python, the letter ‘u’ works as a prefix to distinguish between Unicode and usual
strings.
print (u' Hello Python!!') # Hello Python

Table 5.19 : String Operators in Python


Operator Operation Description Examples
a = ‘Hello’
+ Concatenation Combining two Strings into one. b = ‘World’
print (a+b) # HelloWorld
a = ‘Hello’
Creates new String by repeating the
* Repetition print (a*3) # Hello Hello
String a given number of times.
Hello
a = ‘Hello’
[] Slicing Prints the character at a given index.
print (a[3]) # l
Prints the characters present in the a = ‘Hello’
[:] Range Slicing
given range. print (a[1:3]) # el
Returns ‘True’ value if the character a = ‘Hello’
in Membership
is present in the given String. print (‘e’ in a) # True

222 Principles of Programming and Web Technologies


kn Unäv

Returns ‘True’ value if the character a = ‘Hello’


not in Membership
is not present in the given String. print (‘N’ not in a) # True
a = ‘Hello’
Using for we can iterate through all
for Iterating for var in a:
the characters of the String.
print (var)

Used to ignore the actual meaning


of Escape characters inside a string. print (r’\n’) # \n
r/R Raw String
For this we add ‘r’ or ‘R’ in front of print (R’\n’) # \n
the String.

List of Escape Characters


An “escape character” gets interpreted; in a single quoted as well as double quoted strings.
The purpose of this is to escape various characteristics for characters.
Table 5.20 : Escape characters

Escape Character Desciption


\\ Backslash (\)
\” Double-quote (“)
\a ASCII bell (BEL)
\b ASCII backspace (BS)
\cx or \Cx Control-x
\f ASCII Form feed (FF)
\n ASCII linefeed (LF)
\N{name} Character named name in the Unicode database (Unicode only)
\r Carriage Return (CR)
\t Horizontal Tab (TAB)
\uxxxx Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only)
\v ASCII vertical tab (VT)
\ooo Character with octal value ooo
Character with hex value nn where n can be anything from the
\xnn
range 0-9, a-f or A-F

Principles of Programming and Web Technologies 223


kn Unäv

Table 5.21: Built-in String Functions


Function Name Description Example
Returns the String with first character var = ‘HELLO’
capitalize() capitalized and rest of the characters in print (var.capitalize())
lower case. # Hello
ar = ‘HELLOWorld’
Converts all the characters of the String
lower() print (var.lower())
to lowercase.
# helloworld
var = ‘HelloWorld’
Converts all the characters of the String
upper() print (var.upper())
to uppercase.
# HELLOWORLD
Swaps the case of every character in the
var = ‘HelloWorld’
String means that lowercase characters
swapcase() print (var.swapcase())
are changed to uppercase and vice-
# hELLOwORLD
versa.
var = ‘welcome to Python
Returns the ‘titlecased’ version of String
programming’
which means that all words start with
title() print (var.title())
uppercase and rest of the characters in
# Welcome To Python
the words are in lowercase.
Programming
var=’HelloWorld’
Returns the number of times substring str=’e’
‘str’ occurs in range [beg, end] if beg print (var.count(str)) # 2
count(str[,begin [,end]]) and end index are given. If it is not var1=’Eagle Eyes’
given then substring is searched in print (var1.count(‘e’)) # 2
wholeString. Search is case-sensitive. var2=’Eagle Eyes’
print (var2.count(‘E’,0,5)) # 1

Returns a space-padded string with the var='This is an example'


center(width, fillchar) original string centered to a total of print var.center(25,'*')
width columns. #****This is an example***

Table 5.22 :String Comparison Functions

Function Name Description Example


var=’Hello’
Returns ‘True’ if all the characters in the String
print (var.islower()) # False
islower() are in lowercase. If any one character is in
var=’hello’
uppercase it will return ‘False’.
print (var.islower()) # True
var=’Hello’
Returns ‘True’ if all the characters in the String
print (var.isupper()) # False
isupper() are in uppercase. If any one character is in
var=’HELLO’
lowercase it will return ‘False’.
print (var.isupper()) # True

224 Principles of Programming and Web Technologies


kn Unäv

Returns ‘True’ if all the characters in String


are decimal. If anyone character in the String
num=u’2016′
isdecimal() is of other data-type, it will return ‘False’.
print (num.isdecimal()) # True
Decimal characters are those from the Unicode
category ‘Nd’ ie Number, Decimal Digit.
Returns ‘True’ for any character for which
isdecimal() would return ‘True and some
characters in ‘No’ category.
If there are any characters other than these, it print (‘2’.isdigit())
will return ‘False’. # True
isdigit()
Digits are the characters for which Unicode print (‘²’.isdigit())
property includes: # True
Numeric_Type=Digit or Numeric_
Type=Decimal. For example, superscripts are
digits but fractions not.
Returns ‘True’ if all the characters of the
num=u’2016′
Unicode String lie in any one of the category
print (num.isnumeric())
‘Nd’, ’No’ and ‘NI’. If there are any characters
# True
isnumeric() other than these, it will return ‘False’. Numeric
num=u’year2016′
characters are those for which Unicode property
print (num.isnumeric())
includes Numeric_Type = Digit, Numeric_
# False
Type = Decimal or Numeric_Type = Numeric.
print (‘python’.isalpha())
Returns ‘True’ if String contains at least one
# True
isalpha() character (non-empty String) and all the
print (‘python3’.isalpha())
characters are alphabetic, ‘False’ otherwise.
# False
Returns ‘True’ if String contains at least one print (‘python’.isalnum())
character (non-empty String) and all the # True
isalnum()
characters are either alphabetic or decimal print (‘python3’.isalnum())
digits, ‘False’ otherwise. # True

Table 5.23 : Other String Functions


Function Name Description Example
find(str [,i [,j]]) Searches for ‘str’ in complete var=”Hello World”
String (if i and j not defined) or in str=”World”
a sub-string of String (if i and j are print (var.find(str)) # 5
defined).This function returns the var="Hello Worlds"
index if ‘str’ is found else returns str="World"
‘-1’. print (var.find(str,5)) # 6
where, var="Hello Worlds"
i = search starts from this index str="World"
j = search ends at this index. print (var.find(str,8)) # -1

Principles of Programming and Web Technologies 225


kn Unäv

index(str[,i [,j]]) This is same as ‘find’ method. The var='Python Programming'


only difference is that it raises s='Program'
‘ValueError’ exception if ‘str’ is not print (var.index(s)) # 7
found. var='Python Programming'
s='Program'
print (var.index(s,4)) # 7
var='Python Programming'
s='Program'
print (var.index(s,8))

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

count(str[,i [,j]]) Returns the number of occurrences of var=’This is an example’


substring ‘str’ in the String. Searches str=’an’
for ‘str’ in complete String (if i and print (var.count(str)) # 2
j not defined) or in a sub-string of print (var.count(str,4,10)) # 1
String (if i and j are defined).
where,
i=search starts from this index
j=search ends at this index.

replace(old,new[,count]) Replaces all the occurrences of var=’This is an example’


substring ‘old’ with ‘new’ in the str=’was’
String. print (var.replace(‘is’,str))
If ‘count’ is defined then only ‘count’ # Thwas was an example
number of occurrences of ‘old’ will print (var.replace(‘is’,str,1))
be replaced with ‘new’. # Thwas is an example
where,
old =substring to be replaced, new
=substring that will replace the old
count =number of occurrences of old
that will be replaced with new.
split([sep[,maxsplit]]) Returns a list of substring obtained var = “This is an example”
after splitting the String with ‘sep’ as print (var.split())
delimiter. # ['This', 'is', 'an', 'example']
where, print (var.split(‘ ‘, 2))
sep= delimiter, default is space # ['This', 'is', 'an example']
maxsplit= number of splits to be done

226 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 227


kn Unäv

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

encode(encoding='UTF- Returns encoded string version of var='This is an example'


8',errors='strict') string; on error, default is to raise a print(var.encode('base64','strict'))
ValueError unless errors is given with # VghpcyBpcyBhbiBleGFtcGxl
'ignore' or 'replace'.
endswith(suffix, beg=0, Determines if string or a substring var='This is an example'
end=len(string)) of string (if starting index beg and suffix='example'
ending index end are given) ends print var.endswith(suffix)
with suffix; returns true if so and print var.endswith(suffix,10)
false otherwise. print var.endswith(suffix,3,18)
print var.endswith(suffix,3,7)
expandtabs(tabsize=8) Expands tabs in string to multiple var = "this is\tan example.";
spaces; defaults to 8 spaces per tab if print "Original : " + var
tabsize not provided. print "Defualt : " + var.
expandtabs()
print "Double : " + var.
expandtabs(16)

ljust(width[, fillchar]) Returns a space-padded string with var="This is an example";


the original string left-justified to a print var.ljust(30, '$')
total of width columns.
max(str) This method returns the max var="This is an example";
alphabetical character from the string print max(var) # x
str.
min(str) This method returns the min var="This:is-an_example";
alphabetical character from the string print min(var) # -
str.

228 Principles of Programming and Web Technologies


kn Unäv

String Formatting Operators


String ‘%’ operator is used for formatting Strings. This operator is used with print() function.
For example :-
print "My name is %s and age is %d years!" % ('Avanika', 21)
# My name is Avanika and age is 21 years!
Following Table 5.24 gives the list of complete set of symbols which can be used along with %.
Table 5.24 : String formatting Operators

Formatting Symbol Description

%c character

%s string conversion via str() prior to formatting

%i Signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer lowercase letters

%X hexadecimal integer UPPER-case letters

%e exponential notation with lowercase ‘e’

%E exponential notation with UPPER-case ‘E’

%f floating point real number

%g the shorter of %f and %e

%G the shorter of %f and %E

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

Accessing Lists Values


List apply the standard interface sequence in which len(L) returns the number of items present
in the list and L[i] represents the item at index i. Also L[i:j] returns new list containing objects within
'i' and 'j'. You may look at the given example :-
lst1 = [“Python”, “Java”, ”Perl”, ”C”];
print lst1 # [“Python”, “Java”, ”Perl”, ”C”]
print len(lst1) # returns total number of elements in the list
#4
print lst1[1] # accessing list using index operator
# Java
print lst1[-1] # Indexing the list with “-1” will return the last element of the list
# C
lst3 = [2, 4, 6, ‘Java’, ‘Python’, ‘C’, 4.5];
print ("lst3[2:4]", lst3[2:4]) # 6, ‘Java’

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.

230 Principles of Programming and Web Technologies


kn Unäv

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]

Add/Update elements to a list


Since list is a mutable object, the values at each index can be modified. The assignment
operator (=) is used to update an element or a range of items. You may look at the given example :
prog_lang=['Basic','C','C++','Java','Perl','Python','VB','.NET']
prog_lang[7]='Fortran'
print (prog_lang)
# ['Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'VB', 'Fortran']
prog_lang[1:3]=["Ruby","Lisp"]
print (prog_lang)
# ['Basic', 'Ruby', 'Lisp', 'Java', 'Perl', 'Python', 'VB', 'Fortran']

Principles of Programming and Web Technologies 231


kn Unäv

Modifying a List using Insert Method


The insert() method pushes one item at the target location. You can go through the example
given below for better understanding:-
prog_lang=['Basic','C','C++','Java','Perl','Python','VB','.NET']
prog_lang.insert(0,'Ada')
print (prog_lang)
# ['Ada', 'Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'VB', '.NET']
By using the slice assignment, multiple items can be inserted into a list.
prog_lang[9:2]=['Basic','.Net']
print (prog_lang)
# ['Ada', 'Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'VB', '.NET', 'Basic', '.Net']
Python allows lists to re-size in many ways such as just by adding two or more of them. ou
can go through the example given below:-
L1 = ['a', 'b']
L2 = [1, 2]
L3 = ['Python','Programming']
L4=L1+L2+L3
# ['a', 'b', 1, 2, 'Python', 'Programming']
By using extend() and append() method, a list can be appended / joined. For example:-
L1 = [1, 2]
L2 = ['Python','Programming']
L1.extend(L2) # extend method usage
print (L1)
# [1, 2, 'Python', 'Programming']
L1 = [1, 2]
L1.append(['Python','Programming']) # append method usage
print (L1)
# [1, 2, ['Python', 'Programming']]
L1 = [1, 2]
L2 = ['Python','Programming']
L1.append(L2)
print (L1)
# [1, 2, ['Python', 'Programming']]

232 Principles of Programming and Web Technologies


kn Unäv

Remove/Delete elements from a list


To remove an element from the list, we can use the del-statement. The syntax for deleting an
element from a list is:
Syntax :
del list_name[index_val];
For example :-
prog_lang=['Ada', 'Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'VB', '.NET', 'Basic', '.Net']
del prog_lang[2] # remove one item
print (prog_lang)
# ['Ada', 'Basic', 'C++', 'Java', 'Perl', 'Python', 'VB', '.NET', 'Basic', '.Net']
del prog_lang[1:3] # remove multiple items
prog_lang
# ['Ada', 'Java', 'Perl', 'Python', 'VB', '.NET', 'Basic', '.Net']
del prog_lang # remove the entire list
prog_lang
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# NameError: name 'prog_lang' is not defined
The remove() method is used to delete the given element. Let’s see the example below:-
vowels = ['a','e','i','o','u']
vowels.remove('a')
print(vowels)
# ['e', 'i', 'o', 'u']
The pop() method to take out an item from the desired index. This deletes and sends back the
last item in the absence of the index value. Example below shows the working of this method:-
vowels = ['a','e','i','o','u']
print(vowels.pop(1))
#e
print (vowels)
# ['a', 'i', 'o', 'u']
print(vowels.pop())
#u

Principles of Programming and Web Technologies 233


kn Unäv

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

Sorting a list in Python


Python list implements the sort() method for ordering (in both ascending and descending
order) its elements in place.
Syntax :
List.sort()
In places, sorting algorithms are more efficient as they don’t need temporary variables (such
as a new list) to hold the result. By default, the function sort() performs sorting in the ascending
sequence.
vowels=['a','u','e','o','i']
vowels.sort()
print(vowels) # ['a', 'e', 'i', 'o', 'u']

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

Built-in sorted() function


The built-in sorted() function is used to return a copy of the list with its elements ordered.
vList = sorted(vowels)
By default, it also sorts in an ascending manner.
vowels=['a','u','e','o','i']
vList = sorted(vowels)
234 Principles of Programming and Web Technologies
kn Unäv

print("Original list:", vowels, "Memory addr:", id(vowels))


print("Copy of the list:", vList, "Memory addr:", id(vList))
# ('Original list:', ['a', 'e', 'i', 'o', 'u'], 'Memory addr:', 41464496)
# ('Copy of the list:', ['a', 'e', 'i', 'o', 'u'], 'Memory addr:', 41442560)
You can turn on the “reverse” flag to “True” for enabling the descending order.
vowels = ['a','e','i','o','u']
vList = sorted(vowels, reverse=True)
print("Original list:", vowels, "Memory addr:", id(vowels))
print("Copy of the list:", vList, "Memory addr:", id(vList))
# ('Original list:', ['a', 'e', 'i', 'o', 'u'], 'Memory addr:', 41466296)
# ('Copy of the list:', ['u', 'o', 'i', 'e', 'a'], 'Memory addr:', 41464496)

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

Principles of Programming and Web Technologies 235


kn Unäv

Table 5.25 : List Methods

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.

Table 5.26: List Built-in Functions

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

236 Principles of Programming and Web Technologies


kn Unäv

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

# pop() to multidimensional list


n_sets = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
n_sets[1].pop(3) # 12
print(n_sets) # [[2, 4, 6, 8, 10], [3, 6, 9, 15], [4, 8, 12, 16, 20]]

# reverse() , extend() to multidimensional list


n_sets = [[2,4,6,8,10], [3,6,9,12,15], [4,8,12,16,20]]
n_sets[2].reverse()
print(n_sets[2].reverse()) # None
n_sets[0].extend([12, 14, 16, 18])
print(n_sets) # [[2,4,6,8,10,12,14,16,18], [3,6,9,12,15], [4,8,12,16,20]]

Principles of Programming and Web Technologies 237


kn Unäv

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 of mixed data types


set_mix = {11, 1.1, "11", (1, 2)}
print(set_mix) # set([(1, 2), '11', 11, 1.1])

# set can't store duplicate elements


set_num = {3, 7, 11, 15, 3, 7}
# it'll automatically filter the duplicates
print(set_num) # set([15, 11, 3, 7])

# 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])

# creating set with dynamic elements


py_list = [11, 1.1, "11", (1, 2)]
py_list.append(12)
print(py_list) # [11, 1.1, '11', (1, 2), 12]
set_mix = set(py_list)
print(set_mix) # set(['11', (1, 2), 11, 12, 1.1])

238 Principles of Programming and Web Technologies


kn Unäv

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

Principles of Programming and Web Technologies 239


kn Unäv

# File "C:/Users/jisha/Desktop/b.py", line 18, in <module>


# frozen_set.add("h")
# AttributeError: 'frozenset' object has no attribute 'add'

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

print (x) # set(['c', 'b', 'e', 'd', 'f', 'h'])


# clear()
x = {"a","b","c","d","e","f","h"}
x.clear()
print (x) # set([])
# using del keyword
x = {"a","b","c","d","e","f","h"}
del (x)
print (x) # this will raise an error because the set no longer exists
# NameError: name 'x' is not defined

Membership Operation in Python


This operation is performed to check if a set contains a particular element or not using the
“in” keyword. Let’s take an example:-
x = {"a", "b", "c"}
y = {"f", "d", "a",'i'}
print ("a" , "a" in x) # ('a', True)
print ("c", "c" in y) # ('c', False)

Table 5.27 : Set Built-in methods

Function Description Usage

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

Returns a set containing the difference x = {"a","b","c","d","e"}


between two or more sets. y = {"b","c"}
z = {"c","d"}
difference() Syntax: print x.difference(y)
set.difference(set) # set(['a', 'e', 'd'])
The operator "-" can also be used for print x.difference(y).difference(z)
finding the difference between the sets. # set(['a', 'e'])

Principles of Programming and Web Technologies 241


kn Unäv

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)

x = {"a", "b", "c"}


Removes the items that is not present in
y = {"c", "d", "e"}
intersection_ both sets.
z = {"f", "g", "c"}
update() Syntax:
x.intersection_update(y, z)
set.intersection_update(s1,s2)
print(x) # set(['c'])

Returns True if none of the items are


x = {"a", "b", "c"}
present in both sets, otherwise it returns
y = {"c", "d", "e"}
isdisjoint() False.
z = x.isdisjoint(y)
Syntax:
print(z) # False
set.isdisjoint(set)

x = {"a", "b", "c"}


Returns True if all items in the set exists
x1= {"a"}
in the specified set, otherwise it returns
y = {"c", "d", "e"}
False.
issubset() z = x.issubset(y)
print(z) # False
Syntax:
z = x1.issubset(x)
set. issubset (set)
print(z) # True

x = {"a", "b", "c"}


Returns True if all items in the specified
x1= {"a"}
set exists in the original set, else it
y = {"c", "d", "e"}
returns False.
issuperset() z = x.issuperset(x1)
print(z) # True
Syntax:
z = x.issuperset(y)
set. issuperset (set)
print(z) # False

242 Principles of Programming and Web Technologies


kn Unäv

x = {"a", "b", "c"}


Calculate the length of the set.
y=len(x)
len() Syntax:
print y
len(set)
# 3

x = {"a", "b", "c"}


x1= {"a"}
Return a set that contains all items from
y = {"c", "d", "e"}
both sets, except items that are present
z = x.symmetric_difference(y)
symmetric_ in both sets.
print(z)
difference()
# set(['a', 'b', 'e', 'd'])
Syntax:
z = x.symmetric_difference(x1)
set.symmetric_difference(s)
print(z)
# set(['c', 'b'])

x = {"a", "b", "c"}


x1= {"d"}
y = {"c", "d", "e"}
Updates the original set by removing
x.symmetric_difference_update(y)
symmetric_ items that are present in both sets, and
print(x)
difference_ inserting the other items.
# set(['a', 'b', 'e', 'd'])
update() Syntax:
x.symmetric_difference_
set. symmetric_difference_update (s)
update(x1)
print(x)
# set(['a', 'b', 'e'])

x = {"a", "b", "c"}


y = {"f", "d", "a",'i'}
Returns a set that contains all items z = {"c", "d", "e"}
from the original set, and all items from result = x.union(y, z)
the specified sets. print(result)
Syntax: # set(['a', 'c', 'b', 'e', 'd', 'f', 'i'])
union()
set.union(s1,s2,..) x = {"a", "b", "c"}
y = {"f", "d", "a",'i'}
The “|” operator is the one to perform print ('union x | y is ')
the union operation on the sets print( x | y)
# union x | y is
# set(['a', 'c', 'b', 'd', 'f', 'i'])

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')])

Accessing Elements from a Dictionary


The elements of a dictionary can be accessed with the help of keys by using them as index to
the array operator ([]) or passing as argument to the get() method. The former will return a KeyError
while the latter returns None if the element is not available in the dictionary. Let’s look to a simple
example:-
dict = {'Student Name': 'Krishna', 'Roll No.': 12, 'Subject': 'Malayalam'}
print("dict['Student Name']: ", dict['Student Name']) # dict['Student Name']: Krishna
print("dict['Roll No.']: ", dict['Roll No.']) # dict['Roll No.']: 12
print("dict['Subject']: ", dict['Subject']) # dict['Subject']: Malayalam

# Accessing an element with a non-existent key


dict = {'Student Name': 'Krishna', 'Roll No.': 12, 'Subject': 'Malayalam'}
print("dict['Name']: ", dict['Student Name'])
# Traceback (most recent call last):

244 Principles of Programming and Web Technologies


kn Unäv

# File "<stdin>", line 1, in <module>


# KeyError: 'Name'

# Accessing elements using get function


dict = {'Student Name': 'Krishna', 'Roll No.': 12, 'Subject': 'Malayalam'}
print(dict.get('Student Name')) # Krishna
print(dict.get('Roll No.')) # 12
print(dict.get('Subject')) # Malayalam

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

Removing/Deleting Elements from a Dictionary


The deletion of keys can be done by using the del keyword. Using del keyword, specific
values from a dictionary as well as whole dictionary can be deleted. Other functions like pop() and
popitem() can also be used for deleting specific values and arbitrary values from a Dictionary. All the
items from a dictionary can be deleted at once by using clear() method. Items in a Nested dictionary
can also be deleted by using del keyword and providing specific nested key and particular key to be
deleted from that nested Dictionary. Let’s take an example:
# Initial Dictionary
Dict = { 5:'Welcome', 6:'To', 7:'World', 8: Of', 9:'Python',
'A' : {1 : 'Python', 2 : 'Programming', 3 : 'Language'},

Principles of Programming and Web Technologies 245


kn Unäv

'B' : {1 : 'Python', 2 : 'Language'}}


print(Dict)
# {'A': {1: 'Python', 2: 'Programming', 3: 'Language'}, 'B': {1: 'Python', 2: 'Language'}, 5: 'Welcome',
6: 'To', 7: 'World', 8: 'Of', 9: 'Python'}

# Deleting a Key value


del Dict[6]
print(Dict)
# {'A': {1: 'Python', 2: 'Programming', 3: 'Language'}, 'B': {1: 'Python', 2: 'Language'}, 5: 'Welcome',
7: 'World', 8: 'Of', 9: 'Python'}

# Deleting a Key from Nested Dictionary


del Dict['A'][2]
print(Dict)
# {'A': {1: 'Python', 3: 'Language'}, 'B': {1: 'Python', 2: 'Language'}, 5: 'Welcome', 7: 'World', 8: 'Of',
9: 'Python'}

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.

# Deleting a Key using pop()


Dict = { 5:'Welcome', 6:'To', 7:'World', 8: Of', 9:'Python',
'A' : {1 : 'Python', 2 : 'Programming', 3 : 'Language'},
'B' : {1 : 'Python', 2 : 'Language'}}
Dict.pop(5) # Welcome
print(Dict)

246 Principles of Programming and Web Technologies


kn Unäv

# {'A': {1: 'Python', 2: 'Programming', 3: 'Language'}, 'B': {1: 'Python', 2: 'Language'}, 6: 'To', 7:
'World', 8: 'Of', 9: 'Python'}

# Deleting a Key using popitem()


Dict.popitem() # ('A', {1: 'Python', 2: 'Programming', 3: 'Language'}
print(Dict) # {'B': {1: 'Python', 2: 'Language'}, 6: 'To', 7: 'World', 8: 'Of', 9: 'Python'}
# Deleting entire Dictionary
Dict.clear()
print(Dict) # {}
Table 5.28 : Dictionary Functions

Function Name Description Example


copy() Returns a shallow copy of the dictionary. dict1 = {1: 'a', 2:'e' };
Syntax: dict2=dict1.copy()
dict.copy() print dict2 # {1: 'a', 2: 'e'}

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

fromkeys() Creates a new dictionary with keys from seq vowels=('A','E','I','O','U')


and values set to value. dict.fromkeys(vowels)
Syntax: # {'A': None, 'I': None, 'E': None,
dict.fromkeys(seq[, value]) 'U': None, 'O': None}
where : dict.fromkeys(vowels,15)
seq − This is the list of values which would # {'A': 15, 'I': 15, 'E': 15, 'U': 15,
be used for dictionary keys preparation. 'O': 15}
value − This is optional, if provided then
value would be set to this value
has_key(key) Returns true if a given key is available in the dict1 = {1: 'a', 2:'e' };
dictionary, otherwise it returns a false. dict1.has_key(1) # True
Syntax: dict1.has_key(4) # False
dict.has_key(key)

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)

Principles of Programming and Web Technologies 247


kn Unäv

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.

248 Principles of Programming and Web Technologies


kn Unäv

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

Creating and Accessing Tuples


The elements of a tuple can be of any valid data types ranging from numbers, strings,
lists, etc. Creating an empty tuple would be pointless, since they can't be changed. Tuple assignment
feature which enables to assign more than one variable at a time.
# create an empty tuple
sample_tuple = ()
print(sample_tuple) # ()
# create a tuple without using round brackets
sample_tuple = 33, 55, 77
print( sample_tuple) # (33, 55, 77)
# create a tuple of numbers
sample_tuple = (33, 55, 77)
print(sample_tuple) # (33, 55, 77)

# create a tuple of mixed numbers such as integer, float, imaginary


sample_tuple = (33, 3.3, 3+3j)
print(sample_tuple) # (33, 3.3, (3+3j))
# create a tuple of mixed data types such as numbers, strings, lists
sample_tuple = (33, "33", [3, 3])
print(sample_tuple) # (33, 3.3, (3+3j))
# create a nested tuple
sample_tuple = (('x', 'y', 'z'), ('X', 'Y', 'Z'))
print(sample_tuple) # (('x', 'y', 'z'), ('X', 'Y', 'Z'))

A tuple can be created by using built-in function Tuple().


# creating a tuple from a set
py_tuple = tuple({33, 55 , 77})
type(sample_tuple) # <class 'tuple'>
print(sample _tuple) # (33, 77, 55)
Principles of Programming and Web Technologies 249
kn Unäv

# creating a tuple from a list


sample _tuple = tuple([33, 55 , 77])
type(sample _tuple) # <class 'tuple'>
sample _tuple
# (33, 55, 77)

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',))

# Indexing with a non-integer index will raise the TypeError


try:

250 Principles of Programming and Web Technologies


kn Unäv

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',))

# Indexing in a tuple of tuples


month_days = (('jan', 'feb', 'mar'), ('sun', 'mon', 'wed'))
print("month_days[0][2]:", month _days[0][2]) # Accessing elements from first sub tuple
# ('month_days[0][2]:', 'mar')
# Accessing elements from the second sub tuple
print("month_days[1][2]:", month _days[1][2])
# ('month_days[1][2]:', 'wed')

Slice Operations in Tuples


More than one element can be accessed from a tuple via a slicing operator colon ‘:’. Let’s look
into some examples.
prog_lang=('Ada', 'Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'VB', '.NET')
print (prog_lang)
# ('Ada', 'Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'VB', '.NET')
# accessing elements leaving the first one
print (prog_lang[1:])
# ('Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'VB', '.NET')
# accessing elements between the first and fifth positions
# excluding the ones at the first and fifth position
print (prog_lang[1:5])
# ('Basic', 'C', 'C++', 'Java')
# accessing elements after the fifth position
print (prog_lang[5:])
# ('Perl', 'Python', 'VB', '.NET')

# accessing the first five elements


print (prog_lang[:5])
# ('Ada', 'Basic', 'C', 'C++', 'Java')
Principles of Programming and Web Technologies 251
kn Unäv

# 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')

Packing and Unpacking Tuples


Tuples can be packed and unpacked. Packing deals with assignment of new values to the tuple
while unpacking deals with the extraction of those values into the variables. You may look to the
given example:-
x=('Krishna','1023','Malayalam','First') # Packing
(Name,Rollno,Subject,Grade)=x # Unpacking
print(Name,Rollno,Subject,Grade)
# ('Krishna', '1023', 'Malayalam', 'First')

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

# modify tuple will return a TypeError


try:
num_tuple[0] = 11
except Exception as ex:
print("Error Message", ex)
# ('Error Message', TypeError("'tuple' object does not support item assignment",))

252 Principles of Programming and Web Technologies


kn Unäv

# 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]))

# assigning a tuple with new data


num_tuple = ('mon', 'tue', 'wed')
print("after reassignment:", num_tuple)
# (' after reassignment:', ('mon', 'tue', 'wed'))

Concatenate and Repeat Operations in Tuple


The plus operator helps you join the two distinct tuples. You may look to the given example:-
prog_lang1=('Ada', 'Basic', 'C', 'C++', 'Java', 'Perl', 'Python')
prog_lang2=('Ruby', 'Fortran', 'Cobol')
prog_lang = prog_lang1 + prog_lang2
print (prog_lang)
# ('Ada', 'Basic', 'C', 'C++', 'Java', 'Perl', 'Python', 'Ruby', 'Fortran', 'Cobol')
The star operator helps you repeat the elements in a tuple for a specified number of times. You
may look to the given example:-
prog_lang=('Python ')
prog_lang=prog_lang*5
print(prog_lang)
# Python Python Python Python Python

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

Principles of Programming and Web Technologies 253


kn Unäv

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

Membership Operations in Tuples


This operation is done by using the keyword ‘in’. You may look to the given example:-
py_tuple = ('p', 'y', 't', 'h', 'o', 'n')
print("Does 'p' exist?", 'p' in py_tuple)
# ("Does 'p' exist?", True)
print("Does 'a' exist?", 'a' in py_tuple)
# ("Does 'a' exist?", False)
print("Does 'p' not exist?", 'p' not in py_tuple)
# ("Does 'p' not exist?", False)
print("Does 'a'not exist?", 'a' not in py_tuple)
# ("Does 'a'not exist?", True)

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

254 Principles of Programming and Web Technologies


kn Unäv

Table 5.29 : Built-in functions of tuple

Function name Description Example


t1, t2 = (123, 'xyz'), (456, 'abc')
Compares elements of both tuples.
print (cmp(t1, t2)) # -1
cmp() Syntax:
print( cmp(t2, t1)) # 1
cmp(tuple1, tuple2)
print (cmp(t2, t3)) # -1
Returns the elements from the tuple
t1 = (123, 'xyz', 'zara', 'abc')
with maximum value.
print( "Max value: ", max(t1))
max() Syntax:
t2 = (456, 700, 200)
max(tuple)
print( "Max value: ", max(t2))

Returns the elements from the tuple


t1 = (123, 'xyz', 'zara', 'abc')
with minimum value.
print ("Min value: ", min(t1))
min() Syntax:
t2 = (456, 700, 200)
min(tuple)
print *"Min value: ", min(t2))

aList = [123, 'xyz', 'zara', 'abc']


Converts a list of items into tuples.
aTuple = tuple(aList)
tuple() Syntax:
print (aTuple)
tuple( seq )
# (123, 'xyz', 'zara', 'abc')

References

1. PHP A Beginner’s Guide, Vikram Vaswani, The McGraw-Hill Companies.


2. https://www.tutorialrepublic.com/
3. Python Basics: A Practical Introduction to Python 3, David Amos, Dan Bader, Joanna Jablonski, Fletcher Heisler, Real
Python (realpython.com)
4. Computer Science with Python Textbook, Sumita Arora ,Dhanpat Rai & Co
5. https://www.gacbe.ac.in/images/E%20books/core%20PHP%20Programming%20bbbb.pdf
6. http://web-algarve.com/books/MySQL%20&%20PHP/Programming%20PHP,%203rd%20Edition.pdf

Principles of Programming and Web Technologies 255


kn Unäv

Abbreviation

1D : One Dimensional

2D : Two Dimensional

ALU : Arithmetic Logical Unit

ASCII : American Standard Code for Information Interchange

BPCL : Basic Combined Programming Language

CISC : Complex Instruction Set Computer

CSS : Cascading Style Sheets

FTP : File Transfer Protocol

HTML : HyperText Markup Language

HTTP : Hypertext Transfer Protocol

IDE : Integrated Development Environment

JS : JavaScript

OOP : Object-Oriented Programming

PC : Program Counter

PHP : Hypertext Preprocessor

POP : Procedural Oriented Programming

SMTP : Simple Mail transfer Protocol

WAMP : Windows. Apache, MySQL, PHP

WWW : World Wide Web Consortium

XAMPP : Cross-Platform, Apache, MariaDB & MySQL, PHP/Perl

IIS : Internet Information Server

AMP : Apache, MySQL, PHP

LAMP : Linux, Apache, MySQL, PHP.

MAMP : macOS, Apache, MySQL/MariaDB, PHP/Perl/Python

256 Principles of Programming and Web Technologies

You might also like