You are on page 1of 231

Sree Narayana Guru College

SUBJECT NAME : COMPUTER APPLICATIONS – II (4AA)

DEPARTMENT : BIOTECHNOLOGY

CLASS : II BSC BIOTECHNOLOGY

SEMESTER IV

Unit:1 Computer Algorithms and Fundamentals in C


Computer Algorithms:
Basics of Algorithms- Pseudo code-Flowchart-Stack-Queues.
Fundamentals in C:
History of C- Basic Structure of a C program- Simple C Program- Character set - C tokens - Keywords -
Identifiers - Constants – Variables – Data Types -Declaration of Variable - Assigning Values to Variables
–Initialization.

Unit:2 Operators and Expressions: Arrays


Operators and Expressions:
Arithmetic operators – relational operators – logical operators – assignment operators – increment and
decrement operators – conditional operators – special operators – arithmetic expression – evaluation of
expression – Precedence of arithmetic operators – type conversion in expression – operator precedence
and associativity – mathematical functions.
Arrays:
Introduction – One dimensional array – declaration of array – Initiating on two and multidimensional
arrays.

Unit:3 Decision Making , Branching and looping


Decision Making and Branching:
Introduction to if, if...else, nesting of if ...else statements- else if ladder – The switch statement, The ?:
Operator – The goto Statement.
Decision Making and Looping:
Introduction - while loop –do loop –do while lopp –for loop –Nested Loops–break–continue–goto–exit–
return.

Unit:4 Python
Python:
About python, features of python, python set up, fundamentals of python, values and data types,
variables, key word, identifier of python, quotations, indentation, multi line statement, input-output and
import function in python, advantages and disadvantages of python.
Unit:5
Fruitful functions in python:
Defining a function, function call, types of function, python function arguments, composition, python
recursion and python lambda function.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

UNIT I

COMPUTER ALGORITHMS AND FUNDAMENTALS IN C

Computer Algorithms:
Basics of Algorithms- Pseudo code-Flowchart-Stack-Queues.
Fundamentals in C:
History of C- Basic Structure of a C program- Simple C Program- Character set - C tokens -
Keywords - Identifiers - Constants – Variables – Data Types -Declaration of Variable -
Assigning Values to Variables –Initialization.

COMPUTER ALGORITHMS:
BASIC OF ALGORITHMS

The word Algorithm means “a process or set of rules to be followed in calculations


or other problem-solving operations”. Therefore Algorithm refers to a set of
rules/instructions that step-by-step define how a work is to be executed upon in order to
get the expected results.

It can be understood by taking an example of cooking a new recipe. To cook a new


recipe, one reads the instructions and steps and execute them one by one, in the given
sequence. The result thus obtained is the new dish cooked perfectly. Similarly, algorithms
help to do a task in programming to get the expected output.
The Algorithm designed are language-independent, i.e. they are just plain instructions
that can be implemented in any language, and yet the output will be the same, as
expected.

What are the Characteristics of an Algorithm?

 Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of its steps
should be clear in all aspects and must lead to only one meaning.
 Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined
inputs.
 Well-Defined Outputs: The algorithm must clearly define what output will be yielded
and it should be well-defined as well.
 Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite loops
or similar.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

 Feasible: The algorithm must be simple, generic and practical, such that it can be
executed upon with the available resources. It must not contain some future
technology, or anything.
 Language Independent: The Algorithm designed must be language-independent, i.e. it
must be just plain instructions that can be implemented in any language, and yet the
output will be same, as expected.

Advantages of Algorithms:

 It is easy to understand.
 Algorithm is a step-wise representation of a solution to a given problem.
 In Algorithm the problem is broken down into smaller pieces or steps hence, it is
easier for the programmer to convert it into an actual program.

Disadvantages of Algorithms:

 Writing an algorithm takes a long time so it is time-consuming.


 Branching and Looping statements are difficult to show in Algorithms.

How to Design an Algorithm?

1. The problem that is to be solved by this algorithm.


2. The constraints of the problem that must be considered while solving the problem.
3. The input to be taken to solve the problem.
4. The output to be expected when the problem the is solved.
5. The solution to this problem, in the given constraints.
Then the algorithm is written with the help of above parameters such that it solves the
problem.
Example: Consider the example to add three numbers and print the sum.

 Step 1: Fulfilling the pre-requisites


As discussed above, in order to write an algorithm, its pre-requisites must be fulfilled.
1. The problem that is to be solved by this algorithm: Add 3 numbers and print their
sum.
2. The constraints of the problem that must be considered while solving the problem:
The numbers must contain only digits and no other characters.
3. The input to be taken to solve the problem: The three numbers to be added.
4. The output to be expected when the problem the is solved: The sum of the three
numbers taken as the input.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

5. The solution to this problem, in the given constraints: The solution consists of
adding the 3 numbers. It can be done with the help of ‘+’ operator, or bit-wise, or
any other method.
 Step 2: Designing the algorithm
Now let’s design the algorithm with the help of above pre -requisites:
Algorithm to add 3 numbers and print their sum:
1. START
2. Declare 3 integer variables num1, num2 and num3.
3. Take the three numbers, to be added, as inputs in variables num1, num2, and
num3 respectively.
4. Declare an integer variable sum to store the resultant sum of the 3 numbers.
5. Add the 3 numbers and store the result in the variable sum.
6. Print the value of variable sum
7. END
 Step 3: Testing the algorithm by implementing it.
Inorder to test the algorithm, let’s implement it in C language.
1. Priori Analysis: “Priori” means “before”. Hence Priori analysis means checking the
algorithm before its implementation. In this, the algorithm is checked when it is
written in the form of theoretical steps. This Efficiency of an algorithm is measured by
assuming that all other factors, for example, processor speed, are constant and have
no effect on the implementation. This is done usually by the algorithm designer. It is
in this method, that the Algorithm Complexity is determined.
2. Posterior Analysis: “Posterior” means “after”. Hence Posterior analysis means
checking the algorithm after its implementation. In this, the algorithm is checked by
implementing it in any programming language and executing it. This analysis helps to
get the actual and real analysis report about correctness, space required, time
consumed etc.
 Time Factor: Time is measured by counting the number of key operations such as
comparisons in the sorting algorithm.
 Space Factor: Space is measured by counting the maximum memory space required by
the algorithm.
1. Space Complexity: Space complexity of an algorithm refers to the amount of memory
that this algorithm requires to execute and get the result. This can be for inputs,
temporary operations, or outputs.
How to calculate Space Complexity?
The space complexity of an algorithm is calculated by determining following 2
components:
 Fixed Part: This refers to the space that is definitely required by the algorithm.
For example, input variables, output variables, program size, etc.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

 Variable Part: This refers to the space that can be different based on the
implementation of the algorithm. For example, temporary variables, dynamic
memory allocation, recursion stack space, etc.
2. Time Complexity: Time complexity of an algorithm refers to the amount of time that
this algorithm requires to execute and get the result. This can be for normal
operations, conditional if-else statements, loop statements, etc.
How to calculate Time Complexity?
The time complexity of an algorithm is also calculated by determining following 2
components:
 Constant time part: Any instruction that is executed just once comes in this part.
For example, input, output, if-else, switch, etc.
 Variable Time Part: Any instruction that is executed more than once, say n times,
comes in this part. For example, loops, recursion, etc.

PSEUDO CODE

What is Pseudocode?

Pseudocode literally means ‘fake code’. It is an informal and contrived way of


writing programs in which you represent the sequence of actions and instructions (aka
algorithms) in a form that humans can easily understand.

You see, computers and human beings are quite different, and therein lies the problem.

The language of a computer is very rigid: you are not allowed to make any mistakes
or deviate from the rules. Even with the invention of high-level, human-readable languages
like JavaScript and Python, it’s still pretty hard for an average human developer to reason
and program in those coding languages.

With pseudocode, however, it’s the exact opposite. You make the rules. It doesn’t
matter what language you use to write your pseudocode. All that matters is
comprehension.

In pseudocode, you don't have to think about semi-colons, curly braces, the syntax
for arrow functions, how to define promises, DOM methods and other core language
principles. You just have to be able to explain what you're thinking and doing.

Benefits of Writing Pseudocode

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

When you're writing code in a programming language, you’ll have to battle with
strict syntax and rigid coding patterns. But you write pseudocode in a language or form
with which you're very familiar.

Since pseudocode is an informal method of program design, you don’t have to obey
any set-out rules. You make the rules yourself.
Pseudocode acts as the bridge between your brain and computer’s code executor. It allows
you to plan instructions which follow a logical pattern, without including all of the technical
details.

Pseudocode is a great way of getting started with software programming as a


beginner. You won’t have to overwhelm your brain with coding syntax.

In fact, many companies organize programming tests for their interviewees in


pseudocode. This is because the importance of problem solving supersedes the ability to
‘hack’ computer code.

You can get quality code from many platforms online, but you have to learn problem
solving and practice it a lot.

Planning computer algorithms with pseudocode makes you meticulous. It helps you
explain exactly what each line in a software program should do. This is possible because
you are in full control of everything, which is one of the great features of pseudocode.

Example of Pseudocode

Pseudocode is a very intuitive way to develop software programs. To illustrate this, I


am going to refer back to a very simple program I wrote in my last article:
When a user fills in a form and clicks the submit button, execute a ValidateEmail function.
What should the function do?

1. Derive an email regular expression (regex) to test the user's email address against.
2. Access the user's email from the DOM and store it in a variable. Find and use the right DOM
method for that task.
3. With the email value now accessed and stored, create a conditional statement:
 If the email format doesn’t match the rule specified by the regex, access the element with
the myAlert id attribute and pass in the “Invalid Email” message for the user to see.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

 Else, if the above condition isn’t true and the email address format actually matches with
the regex, check to see if the database already has such an email address. If it already does,
access the element with the myAlert id attribute and pass in the “Email exists!” message for
the user to see.
 Now, if both of these conditions aren’t met, (that is the email format matches the regex
and the database doesn’t have such an email address stored yet), push the users email
address into the database and pass in the “Successful!” message for the user to see.

How to Solve Programming Problems with Pseudocode

Solving programming problems can be hard. Not only do you have the logical part to
reckon with, but also the technical (code forming) part as well. I recently uncovered a
brilliant and effective formula for solving tricky coding problems.

Here are the steps you can follow to solving programming problems with
pseudocode:

Step 1: Understand what the function does


First, you need to understand that all a function does is (optionally) accept data as
input, work on the data little by little, and finally return an output. The body of the function
is what actually solves the problem and it does so line by line.

Step 2: Make sure you understand the question


Next, you need to read and understand the question properly. This is arguably the most
important step in the process.

If you fail to properly understand the question, you won’t be able to work through
the problem and figure out the possible steps to take. Once you identify the main
problem to be solved you'll be ready to tackle it.

Step 3: Break the problem down.


Now you need to break down the problem into smaller parts and sub-problems.
With each smaller problem you solve, you'll get closer to solving the main problem.

It helps to represent these problem solving steps in the clearest and most easily
understandable way you can – which is psedocode!

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

 Start solving: open and use tools like Google, Stack Overflow, MDN, and of course
freeCodeCamp! :)
 For every step of the problem that you solve, test the output to make sure you’re on the
right path. Keep solving these small problems until you arrive at the final solution.

FLOWCHART
WHAT IS A FLOWCHART?

Also called: process flowchart, process flow diagram

Variations: macro flowchart, top-down flowchart, detailed flowchart (also called


process map, micro map, service map, or symbolic flowchart), deployment flowchart (also
called down-across or cross-functional flowchart), several-leveled flowchart

A flowchart is a picture of the separate steps of a process in sequential order. It is a


generic tool that can be adapted for a wide variety of purposes, and can be used to describe
various processes, such as a manufacturing process, an administrative or service process,
or a project plan. It's a common process analysis tool and one of the seven basic quality
tools.

Elements that may be included in a flowchart are a sequence of actions, materials or


services entering or leaving the process (inputs and outputs), decisions that must be made,
people who become involved, time involved at each step, and/or process measurements.

History

Flowcharts to document business processes came into use in the 1920s and ‘30s. In
1921, industrial engineers Frank and Lillian Gilbreth introduced the “Flow Process Chart”
to the American Society of Mechanical Engineers (ASME). In the early 1930s, industrial
engineer Allan H. Morgensen used Gilbreth’s tools to present conferences on making work
more efficient to business people at his company. In the 1940s, two Morgensen students,
Art Spinanger and Ben S. Graham, spread the methods more widely. Spinanger introduced
the work simplification methods to Procter and Gamble. Graham, a director at Standard
Register Industrial, adapted flow process charts to information processing. In 1947, ASME
adopted a symbol system for Flow Process Charts, derived from the Gilbreths’ original
work.

Also in the late ‘40s, Herman Goldstine and John Van Neumann used flowcharts to
develop computer programs, and diagramming soon became increasingly popular for
computer programs and algorithms of all kinds. Flowcharts are still used for
programming today, although pseudocode, a combination of words and coding language

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

meant for human reading, is often used to depict deeper levels of detail and get closer to
a final product.

In Japan, Kaoru Ishikawa (1915-1989), a key figure in quality initiatives in


manufacturing, named flowcharts as one of the key tools of quality control, along with
complementary tools such as the Histogram, Check Sheet and Cause-and-Effect Diagram,
now often called the Ishikawa Diagram.

WHEN TO USE A FLOWCHART

 To develop understanding of how a process is done


 To study a process for improvement
 To communicate to others how a process is done
 When better communication is needed between people involved with the same process
 To document a process
 When planning a project

FLOWCHART BASIC PROCEDURE

Materials needed: Sticky notes or cards, a large piece of flipchart paper or newsprint, and
marking pens.

1. Define the process to be diagrammed. Write its title at the top of the work surface.
2. Discuss and decide on the boundaries of your process: Where or when does the process
start? Where or when does it end? Discuss and decide on the level of detail to be included
in the diagram.
3. Brainstorm the activities that take place. Write each on a card or sticky note.
4. Arrange the activities in proper sequence.
5. When all activities are included and everyone agrees that the sequence is correct, draw
arrows to show the flow of the process.
6. Review the flowchart with others involved in the process (workers, supervisors,
suppliers, customers) to see if they agree that the process is drawn accurately.

Flowchart Considerations

 Don’t worry about drawing the flowchart the "right way." Ultimately, the right way is the
way that helps those involved understand the process.
 Identify and involve in the flowcharting process all key people involved with the process.
This includes suppliers, customers, and supervisors. Involve them in the actual

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

flowcharting sessions by interviewing them before the sessions and/or by showing them
the developing flowchart between work sessions and obtaining their feedback.
 Do not assign a "technical expert" to draw the flowchart. People who actually perform the
process should do it.

Types of flowcharts

Different authors describe various types of flowcharts in different terms. These people
include published experts such as Alan B. Sterneckert, Andrew Veronis, Marilyn Bohl and
Mark A. Fryman.

Sterneckert, in his 2003 book Critical Incident Management, listed four popular flowchart
types, framed around the concept of flow controls rather than the flow itself:

 Document Flowcharts: These “have the purpose of showing existing controls over
document-flow through the components of a system. … The chart is read from left to
right and documents the flow of documents through the various business units.”

 Data Flowcharts: These show “the controls governing data flows in a system. … Data
flowcharts are used primarily to show the channels that data is transmitted through
the system rather than how controls flow.”

 System Flowcharts: These “show the flow of data to and through the major components
of a system such as data entry, programs, storage media, processors, and
communication networks.”

 Program Flowcharts: These show “the controls placed internally to a program within a
system.”

Veronis , in his 1978 book Microprocessors: Design and Applications, outlined three
flowchart types based on scope and level of detail:

 System Flowchart: Identifies the devices to be used.

 General Flowchart: Overview.

 Detailed Flowchart: Increased detail.

Bohl, in her 1978 book A Guide for Programmers, listed only two:

 System Flowchart.

 Program Flowchart.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

But Fryman, in his 2001 book Quality and Process Improvement, differentiated the types in
multiple ways from more of a business perspective than a computer perspective:

 Decision Flowchart.

 Logic Flowchart.

 Systems Flowchart.

 Product Flowchart.

 Process Flowchart.

Additional flowchart types defined by others include:

 Swimlane Diagram, a.k.a Swimlane Flowchart: To delineate who does what in cross-
team processes.

 Workflow Flowchart: To document workflows, often involving tasks, documents and


information in offices.

 Event-Driven Process Chain (EPC) Flowchart: To document or plan a business process.

 Specification and Description Language (SDL) Flowchart: To brainstorm computer


algorithms using three basic components: system definition, block and process.

How to plan and draw a basic flowchart

1. Define your purpose and scope. What do you hope to accomplish? Are you studying the
right things with appropriate start and end points to accomplish that purpose? Be
detailed enough in your research but simple enough in your charting to communicate
with your intended audience.

2. Identify the tasks in chronological order. This might involve talking to participants,
observing a process and/or reviewing any existing documentation. You might write out
the steps in note form, or begin a rough chart.

3. Organize them by type and corresponding shape, such as process, decision, data, inputs
or outputs.

4. Draw your chart, either sketching by hand or using a program such as Lucidchart.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

5. Confirm your flowchart, walking through the steps with people who participate in the
process. Observe the process to make sure you haven’t missed anything important to
your purpose.

STACK
Stack is a linear data structure that follows a particular order in which the
operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last
Out).
Mainly the following three basic operations are performed in the stack:
 Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow
condition.
 Pop: Removes an item from the stack. The items are popped in the reversed order in
which they are pushed. If the stack is empty, then it is said to be an Underflow
condition.
 Peek or Top: Returns the top element of the stack.
 isEmpty: Returns true if the stack is empty, else false.

How to understand a stack practically?

There are many real-life examples of a stack. Consider the simple example of plates
stacked over one another in a canteen. The plate which is at the top is the first one to be
removed, i.e. the plate which has been placed at the bottommost position remains in the
stack for the longest period of time. So, it can be simply seen to follow the LIFO/FILO order.

Time Complexities of operations on stack:

push(), pop(), isEmpty() and peek() all take O(1) time. We do not run any loop in any of
these operations.
Applications of stack:
 Balancing of symbols
 Infix to Postfix /Prefix conversion
 Redo-undo features at many places like editors, photoshop.
 Forward and backward feature in web browsers
 Used in many algorithms like Tower of Hanoi, tree traversals, stock span
problem, histogram problem.
 Backtracking is one of the algorithm designing techniques. Some examples of
backtracking are the Knight-Tour problem, N-Queen problem, find your way through
a maze, and game-like chess or checkers in all these problems we dive into someway if
that way is not efficient we come back to the previous state and go into some another

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

path. To get back from a current state we need to store the previous state for that
purpose we need a stack.
 In Graph Algorithms like Topological Sorting and Strongly Connected Components
 In Memory management, any modern computer uses a stack as the primary
management for a running purpose. Each program that is running in a computer
system has its own memory allocations
 String reversal is also another application of stack. Here one by one each character
gets inserted into the stack. So the first character of the string is on the bottom of the
stack and the last element of a string is on the top of the stack. After Performing the
pop operations on the stack we get a string in reverse order.

Implementation:
There are two ways to implement a stack:
 Using array
 Using linked list

Stack in Python
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-
In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is
removed from that end only. The insert and delete operations are often called push and
pop.

The functions associated with stack are:


 empty() – Returns whether the stack is empty – Time Complexity: O(1)
 size() – Returns the size of the stack – Time Complexity: O(1)
 top() – Returns a reference to the topmost element of the stack – Time Complexity:
O(1)
 push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
 pop() – Deletes the topmost element of the stack – Time Complexity: O(1)

Implementation

There are various ways from which a stack can be implemented in Python. This article
covers the implementation of a stack using data structures and modules from the Python
library.
Stack in Python can be implemented using the following ways:
 list
 Collections.deque
 queue.LifoQueue

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Implementation using list:

Python’s built-in data structure list can be used as a stack. Instead of push(),
append() is used to add elements to the top of the stack while pop() removes the element
in LIFO order.
Unfortunately, the list has a few shortcomings. The biggest issue is that it can run
into speed issues as it grows. The items in the list are stored next to each other in
memory, if the stack grows bigger than the block of memory that currently holds it, then
Python needs to do some memory allocations. This can lead to some append() calls taking
much longer than other ones.

Implementation using collections.deque:

Python stack can be implemented using the deque class from the collections
module. Deque is preferred over the list in the cases where we need quicker append and
pop operations from both the ends of the container, as deque provides an O(1) time
complexity for append and pop operations as compared to list which provides O( n) time
complexity.
The same methods on deque as seen in the list are used, append() and pop().

Implementation using queue module

Queue module also has a LIFO Queue, which is basically a Stack. Data is inserted
into Queue using the put() function and get() takes data out from the Queue.
There are various functions available in this module:
 maxsize – Number of items allowed in the queue.
 empty() – Return True if the queue is empty, False otherwise.
 full() – Return True if there are maxsize items in the queue. If the queue was
initialized with maxsize=0 (the default), then full() never returns True.
 get() – Remove and return an item from the queue. If the queue is empty, wait until an
item is available.
 get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
 put(item) – Put an item into the queue. If the queue is full, wait until a free slot is
available before adding the item.
 put_nowait(item) – Put an item into the queue without blocking.
 qsize() – Return the number of items in the queue. If no free slot is immediately
available, raise QueueFull.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

QUEUE
Like Stack, Queue is a linear structure which follows a particular order in which
the operations are performed. The order is First In First Out (FIFO). A good example of
queue is any queue of consumers for a resource where the consumer that came first is
served first.

The difference between stacks and queues is in removing. In a stack we remove


the item the most recently added; in a queue, we remove the item the least recently
added.

Operations on Queue:

Mainly the following four basic operations are performed on queue:


Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow
condition.
Dequeue: Removes an item from the queue. The items are popped in the same order in
which they are pushed. If the queue is empty, then it is said to be an Underflow condition.
Front: Get the front item from queue.
Rear: Get the last item from queue.

Applications of Queue:

Queue is used when things don’t have to be processed immediately, but have to be
processed in First In First Out order like Breadth First Search. This property of Queue
makes it also useful in following kind of scenarios.
1) When a resource is shared among multiple consumers. Examples include CPU
scheduling, Disk Scheduling.
2) When data is transferred asynchronously (data not necessarily received at same rate
as sent) between two processes. Examples include IO Buffers, pipes, file IO, etc.
See this for more detailed applications of Queue and Stack.

Array implementation Of Queue

For implementing queue, we need to keep track of two indices, front and rear. We
enqueue an item at the rear and dequeue an item from the front. If we simply increment
front and rear indices, then there may be problems, the front may reach the end of the
array. The solution to this problem is to increase front and rear in circular manner.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Queue in Python
Like stack, queue is a linear data structure that stores items in First In First Out
(FIFO) manner. With a queue the least recently added item is removed first. A good
example of queue is any queue of consumers for a resource where the consumer that
came first is served first.

 Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an
Overflow condition – Time Complexity : O(1)
 Dequeue: Removes an item from the queue. The items are popped in the same order
in which they are pushed. If the queue is empty, then it is said to be an Underflow
condition – Time Complexity : O(1)
 Front: Get the front item from queue – Time Complexity : O(1)
 Rear: Get the last item from queue – Time Complexity : O(1)

Implementation

There are various ways to implement a queue in Python. This article covers the
implementation of queue using data structures and modules from Python library.
Queue in Python can be implemented by the following ways:

 list
 collections.deque
 queue.Queue

Implementation using list


List is a Python’s built-in data structure that can be used as a queue. Instead of
enqueue() and dequeue(), append() and pop() function is used. However, lists are quite
slow for this purpose because inserting or deleting an element at the beginning requires
shifting all of the other elements by one, requiring O(n) time.

Priority Queue
Priority Queue is an abstract data type, which is similar to a queue, however, in the
priority queue, every element has some priority. The priority of the elements in a priority
queue determines the order in which elements are removed from the priority queue.
Therefore all the elements are either arranged in an ascending or descending order.
So, a priority Queue is an extension of the queue with the following properties.
 Every item has a priority associated with it.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

 An element with high priority is dequeued before an element with low priority.
 If two elements have the same priority, they are served according to their order in the
queue.
In the below priority queue, an element with a maximum ASCII value will have the
highest priority. The elements with higher priority are served first.

A typical priority queue supports the following operations:

1) Insertion: When a new element is inserted in a priority queue, it moves to the empty
slot from top to bottom and left to right. However, if the element is not in the correct place
then it will be compared with the parent node. If the element is not in the correct order, the
elements are swapped. The swapping process continues until all the elements are placed in
the correct position.
2) Deletion: As you know that in a max heap, the maximum element is the root node.
And it will remove the element which has maximum priority first. Thus, you remove the
root node from the queue. This removal creates an empty slot, which will be further filled
with new insertion. Then, it compares the newly inserted element with all the elements
inside the queue to maintain the heap invariant.
3) Peek: This operation helps to return the maximum element from Max Heap or
minimum element from Min Heap without deleting the node from the priority queue.

Types of Priority Queue:

1) Ascending Order: As the name suggests, in ascending order priority queue, the
element with a lower priority value is given a higher priority in the priority list. For
example, if we have the following elements in a priority queue arranged in ascending
order like 4,6,8,9,10. Here, 4 is the smallest number, therefore, it will get the highest
priority in a priority queue.
2) Descending order: The root node is the maximum element in a max heap, as you may
know. It will also remove the element with the highest priority first. As a result, the root
node is removed from the queue. This deletion leaves an empty space, which will be filled
with fresh insertions in the future. The heap invariant is then maintained by comparing
the newly inserted element to all other entries in the queue.

How to Implement Priority Queue?


Priority queue can be implemented using the following data structures:
 Arrays
 Linked list

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

 Heap data structure


 Binary search tree

HISTORY OF C

There are many programming languages in use today, one of which is C. There are
many offshoots of the C programming language, including Objective-C, C++, and C#. None of
these are the same language. So, how did C begin?

The Beginning

The C programming language came out of Bell Labs in the early 1970s. According to
the Bell Labs paper The Development of the C Language by Dennis Ritchie, “The C
programming language was devised in the early 1970s as a system implementation
language for the nascent Unix operating system. Derived from the typeless language BCPL,
it evolved a type structure; created on a tiny machine as a tool to improve a meager
programming environment.” Originally, Ken Thompson, a Bell Labs employee, desired to
make a programming language for the new Unix platform. Thompson modified the BCPL
system language and created B. However, not many utilities were ever written in B due to
its slow nature and inability to take advantage of PDP-11 features in the operating system.
This led to Ritchie improving on B, and thus creating C.

Early Implementations and Language Standard

The development of C was to become the basis for Unix. According to the Bell Labs
paper, “By early 1973, the essentials of modern C were complete. The language and
compiler were strong enough to permit us to rewrite the Unix kernel for the PDP-11 in C
during the summer of the year.” This now meant that C was becoming a strong language
that could, and would be, implemented across many systems. By the middle of the 1970s,
the C-based Unix was used in many projects within the Bell System as well as “a small
group of research-oriented industrial, academic, and government organizations outside
[Bell Labs]".

In 1978, Brian Kernighan and Dennis Ritchie published The C Programming


Language, which would serve as the language reference until a formal standard was
adopted. Five years later, the American National Standard Institute (ANSI) formed the
committee, X3J11, to establish the formal standard of C. The C standard was ratified as
ANSI X3.159-1989 “Programming Language C”. This was the first formal standard of C.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Currently, we are on the fourth standard of C, known as C18 as it was published in June of
2018 JavaTpoint.

Uses Today

According to Toptal, UNIX operating systems are written in C and most of Linux is
also in C. Also databases such as Oracle Database, MySQL, MS SQL Server, and PostgresSQL
are at least partially written in C. C is the basis of many system kernels. Other programming
languages, like Python and Perl, use compilers or interpreters that are written in C.

C has changed over the years and is still a common language to use in lower level
programs, like kernels. But it is also used for many applications ranging from device drivers
to other programming languages’ compilers or interpreters. The language also made way
for C++, Objective-C, C#, and many more C-based languages that each have their own
speciality.

BASIC STRUCTURE OF A C PROGRAM

The components of the basic structure of a C program consists of 7 parts

1. Document section
2. Preprocessor/link Section
3. Definition section
4. Global declaration section
5. Function declaration section
6. Main function
7. User-defined function section
1. Documentation Section

It is the section in which you can give comments to make the program more
interactive. The compiler won’t compile this and hence this portion would not be displyed
on the output screen.

2. Preprocessor directives Section

This section involves the use of header files that are to included necessarily
program.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

3. Definition section

This section involves the variable definition and declaration in C.

4. Global declaration Section

This section is used to define the global variables to be used in the programs, that
means you can use these variables throughout the program.

5. Function prototype declaration section

This section gives the information about a function that includes, the data type or
the return type, the parameters passed or the arguments.

6.Main function

It is the major section from where the execution of the program begins. The main
section involves the declaration and executable section.

7. User-defined function section

When you want to define your function that fulfills a particular requirement, you
can define them in this section.

SIMPLE C PROGRAM

#include <stdio.h>
int main() {
// printf() displays the string inside
quotation printf("Hello, World!");
return 0;
}

Output

Hello, World!

How "Hello, World!" program works?

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

 The #includ is a preprocessor command that tells the compiler to include the contents
of stdio.h (standard input and output) file in the program.
 The stdio.h file contains functions such as scanf() and printf() to take input and display
output respectively.
 If you use the printf( function without writing #include <stdio.h>, the program will not
compile.
 The execution of a C program starts from the main() function.
 printf( is a library function to send formatted output to the screen. In this
program, printf() displays Hello, World! text on the screen.
 The return 0; statement is the "Exit status" of the program. In simple terms, the
program ends with this statement.

CHARACTER SET

In the C programming language, the character set refers to a set of all the valid
characters that we can use in the source program for forming words, expressions, and
numbers.
The source character set contains all the characters that we want to use for the
source program text. On the other hand, the execution character set consists of the set of
those characters that we might use during the execution of any program. Thus, it is not a
prerequisite that the execution character set and the source character set will be the same,
or they will match altogether.

Use of Character Set in C

Just like we use a set of various words, numbers, statements, etc., in any language
for communication, the C programming language also consists of a set of various different
types of characters. These are known as the characters in C. They include digits, alphabets,
special symbols, etc. The C language provides support for about 256 characters.
Every program that we draft for the C program consists of various statements. We
use words for constructing these statements. Meanwhile, we use characters for
constructing these statements. These characters must be from the C language character set.
Let us look at the set of characters offered by the C language.

Types of Characters in C

The C programming language provides support for the following types of characters. In
other words, these are the valid characters that we can use in the C language:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

 Digits
 Alphabets
 Main Characters
All of these serve a different set of purposes, and we use them in different contexts in the C
language.

Alphabets
The C programming language provides support for all the alphabets that we use in
the English language. Thus, in simpler words, a C program would easily support a total of
52 different characters- 26 uppercase and 26 lowercase.

Digits
The C programming language provides the support for all the digits that help in
constructing/ supporting the numeric values or expressions in a program. These range
from 0 to 9, and also help in defining an identifier. Thus, the C language supports a total of
10 digits for constructing the numeric values or expressions in any program

Special Characters
We use some special characters in the C language for some special purposes, such as
logical operations, mathematical operations, checking of conditions, backspaces, white
spaces, etc.
We can also use these characters for defining the identifiers in a much better way.
For instance, we use underscores for constructing a longer name for a variable, etc.

White Spaces

The white spaces in the C programming language contain the following:

 Blank Spaces
 Carriage Return
 Tab
 New Line

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

C TOKENS

Tokens in C is the most important element to be used in creating a program in C. We


can define the token as the smallest individual element in C. For `example, we cannot create
a sentence without using words; similarly, we cannot create a program in C without using
tokens in C. Therefore, we can say that tokens in C is the building block or the basic
component for creating a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:

o Keywords in C
o Identifiers in C
o Strings in C
o Operators in C
o Constant in C
o Special Characters in C

Keywords

Keywords in C can be defined as the pre-defined or the reserved words having its
own importance, and each keyword has its own functionality. Since keywords are the pre-
defined words used by the compiler, so they cannot be used as the variable names. If the
keywords are used as the variable names, it means that we are assigning a different
meaning to the keyword, which is not allowed.

Identifiers in C

Identifiers in C are used for naming variables, functions, arrays, structures, etc.
Identifiers in C are the user-defined words. It can be composed of uppercase letters,
lowercase letters, underscore, or digits, but the starting letter should be either an
underscore or an alphabet. Identifiers cannot be used as keywords. Rules for constructing
identifiers in C are given below:

o The first character of an identifier should be either an alphabet or an underscore,


and then it can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can
say that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to
read.

Strings in C

Strings in C are always represented as an array of characters having null character '\
0' at the end of the string. This null character denotes the end of the string. Strings in C are
enclosed within double quotes, while characters are enclosed within single characters. The
size of a string is a number of characters that the string contains.

Now, we describe the strings in different ways:

char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "javatpoint"; // The compiler allocates the memory at the run time.

char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form of


characters.

Operators in C

Operators in C is a special symbol used to perform the functions. The data items on which
the operators are applied are known as operands. Operators are applied between the
operands. Depending on the number of operands, operators are classified as follows:

Unary Operator

A unary operator is an operator applied to the single operand. For example: increment
operator (++), decrement operator (--), sizeof, (type)*.

Binary Operator

The binary operator is an operator applied between two operands. The following is the list
of the binary operators:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Conditional Operators
o Assignment Operator
o Misc Operator

Constants in C

A constant is a value assigned to the variable which will remain the same throughout the
program, i.e., the constant value cannot be changed.

There are two ways of declaring constant:

o Using const keyword


o Using #define pre-processor

Special characters in C

Some special characters are used in C, and they have a special meaning which cannot be
used for another purpose.

o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in the
opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when
printing the value of more than one variable using a single printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes
that we are using the header file.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

o Asterisk (*): This symbol is used to represent pointers and also used as an operator
for multiplication.
o Tilde (~): It is used as a destructor to free memory.
o Period (.): It is used to access a member of a structure or a union.

KEYWORDS

A keyword is a reserved word. You cannot use it as a variable name, constant name,
etc. There are only 32 reserved words (keywords) in the C language.

Here is a list of all keywords allowed in ANSI C.

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

IDENTIFIERS

C identifiers represent the name in the C program, for example, variables, functions,
arrays, structures, unions, labels, etc. An identifier can be composed of letters such as
uppercase, lowercase letters, underscore, digits, but the starting letter should be either an
alphabet or an underscore. If the identifier is not used in the external linkage, then it is
called as an internal identifier. If the identifier is used in the external linkage, then it is
called as an external identifier.

We can say that an identifier is a collection of alphanumeric characters that begins


either with an alphabetical character or an underscore, which are used to represent various
programming elements such as variables, functions, arrays, structures, unions, labels, etc.
There are 52 alphabetical characters (uppercase and lowercase), underscore character, and

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

ten numerical digits (0-9) that represent the identifiers. There is a total of 63
alphanumerical characters that represent the identifiers.

Rules for constructing C identifiers

o The first character of an identifier should be either an alphabet or an underscore,


and then it can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can
say that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to
read.

Types of identifiers

o Internal identifier
o External identifier

Internal Identifier

If the identifier is not used in the external linkage, then it is known as an internal identifier.
The internal identifiers can be local variables.

External Identifier

If the identifier is used in the external linkage, then it is known as an external identifier.
The external identifiers can be function names, global variables.

CONSTANTS

A constant is a value or variable that can't be changed in the program, for example: 10, 20,
'a', 3.4, "c programming" etc.

There are different types of constants in C programming.

List of Constants in C

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc.

Constant is a value that cannot be changed during program execution; it is fixed.

In C language, a number or character or string of characters is called a constant. And it can


be any data type. Constants are also called as literals.

There are two types of constants −

Primary constants − Integer, float, and character are called as Primary constants.

Secondary constants − Array, structures, pointers, Enum, etc., called as secondary


constants.

ways to define constant in C

There are two ways to define constant in C programming.

1. const keyword
2. #define preprocessor

C const keyword

The const keyword is used to define constant in C programming.

C #define preprocessor

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

The #define preprocessor is also used to define constant. We will learn about #define
preprocessor directive later.

VARIABLES

A variable is a name of the memory location. It is used to store data. Its value can be
changed, and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

type variable_list;

The example of declaring the variable is given below:


1. int a;
2. float b;
3. char c;

Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

4. int a=10,b=20;//declaring 2 variable of integer type


5. float f=20.8;
6. char c='A';

Rules for defining variables

o A variable can have alphabets, digits, and underscore.


o A variable name can start with the alphabet, and underscore only. It can't start with
a digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names:

1. int a;
2. int _ab;
3. int a30;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Invalid variable names:

1. int 2;
2. int a b;
3. int long;

Types of Variables in C

There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Local Variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

void function1(){
int x=10;//local variable
}

You must have to initialize the local variable before it is used

Global Variable

A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

int value=20;//global variable


void function1(){
int x=10;//local variable

Static Variable

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

void function1(){
int x=10;//local variable
tatic int y=10;//static variable
x=x+1;
y=y+1; printf("%d,
%d",x,y);
}

If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented
value in each function call, e.g. 11, 12, 13 and so on.

Automatic Variable

All variables in C that are declared inside the block, are automatic variables by default. We
can explicitly declare an automatic variable using auto keyword.

void main(){
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}

External Variable

We can share a variable in multiple C source files by using an external variable. To declare
an external variable, you need to use extern keyword.

=extern int x=10;//external variable (also global)


#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

DATA TYPES
Each variable in C has an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. Let us briefly
describe them one by one:
Following are the examples of some very common data types used in C:
 char: The most basic data type in C. It stores a single character and requires a single
byte of memory in almost all compilers.
 int: As the name suggests, an int variable is used to store an integer.
 float: It is used to store decimal numbers (numbers with floating point value) with
single precision.
 double: It is used to store decimal numbers (numbers with floating point value) with
double precision.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating
system.

Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range

char 1 byte −128 to 127

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 byte

The types in C can be classified as follows −

Sr.No. Types & Description

1 Basic Types

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

They are arithmetic types and are further classified into: (a) integer types
and (b) floating-point types.

2 Enumerated types
They are again arithmetic types and they are used to define variables that
can only assign certain discrete integer values throughout the program.

3 The type void


The type specifier void indicates that no value is available.

4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d)
Union types and (e) Function types.

The void Type

The void type specifies that no value is available. It is used in three kinds of situations −

Sr.No. Types & Description

1
Function returns as void
There are various functions in C which do not return any value or you can
say they return void. A function with no return value has the return type as
void. For example, void exit (int status);

2 Function arguments as void


There are various functions in C which do not accept any parameter. A
function with no parameter can accept a void. For example, int rand(void);

3 Pointers to void

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

A pointer of type void * represents the address of an object, but not its type.
For example, a memory allocation function void *malloc( size_t size
); returns a pointer to void which can be casted to any data type.

DECLARATION OF VARIABLE

A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and layout of
the variable's memory; the range of values that can be stored within that memory; and the
set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase letters
are distinct because C is case-sensitive. Based on the basic types explained in the previous
chapter, there will be the following basic variable types −

Sr.No. Type & Description

1 char
Typically a single octet(one byte). It is an integer type.

2 int
The most natural size of integer for the machine.

3 float
A single-precision floating point value.

4 double
A double-precision floating point value.

5 void
Represents the absence of type.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

C programming language also allows to define various other types of variables, which we
will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc.
For this chapter, let us study only basic variable types.

Variable Definition in C

A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of one or more
variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;

The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler
to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables are
undefined.

Variable Declaration in C

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

A variable declaration provides assurance to the compiler that there exists a variable with
the given type and name so that the compiler can proceed for further compilation without
requiring the complete detail about the variable. A variable definition has its meaning at
the time of compilation only, the compiler needs actual variable definition at the time of
linking the program.
A variable declaration is useful when you are using multiple files and you define your
variable in one of the files which will be available at the time of linking of the program.
You will use the keyword extern to declare a variable at any place. Though you can declare
a variable multiple times in your C program, it can be defined only once in a file, a function,
or a block of code.

Example

Try the following example, where variables have been declared at the top, but they
have been defined and initialized inside the main function −
#include <stdio.h>

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {

/* variable definition: */
int a, b;
int c;
float f;

/* actual initialization */
a = 10;
b = 20;

c = a + b;
printf("value of c : %d \n", c);

f = 70.0/3.0;
printf("value of f : %f \n", f);

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

return 0;
}
When the above code is compiled and executed, it produces the following result
− value of c : 30
value of f : 23.333334
The same concept applies on function declaration where you provide a function name at
the time of its declaration and its actual definition can be given anywhere else. For
example −
// function declaration
int func();

int main() {

// function call
int i = func();
}

// function definition
int func() {
return 0;
}

Lvalues and Rvalues in C

There are two kinds of expressions in C −


 lvalue − Expressions that refer to a memory location are called "lvalue" expressions.
An lvalue may appear as either the left-hand or right-hand side of an
assignment.
 rvalue − The term rvalue refers to a data value that is stored at some address in
memory. An rvalue is an expression that cannot have a value assigned to it which
means an rvalue may appear on the right-hand side but not on the left-hand side of
an assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment.
Numeric literals are rvalues and so they may not be assigned and cannot appear on the
left-hand side. Take a look at the following valid and invalid statements −
int g = 20; // valid statement

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

10 = 20; // invalid statement; would generate compile-time error

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

ASSIGNING VALUES TO VARIABLES


Within an SPL routine, use the LET statement to assign values to the variables you
have already defined.

If you do not assign a value to a variable, either by an argument passed to the


routine or by a LET statement, the variable has an undefined value.

An undefined value is different from a NULL value. If you attempt to use a variable
with an undefined value within the SPL routine, you receive an error.

You can assign a value to a routine variable in any of the following ways:

 Use a LET statement.


 Use a SELECT INTO statement.
 Use a CALL statement with a procedure that has a RETURNING clause.
 Use an EXECUTE PROCEDURE INTO or EXECUTE FUNCTION INTO statement.

 The LET statement


 Other ways to assign values to variables

INITIALIZATION
In computer programming, initialization (or initialisation) is the assignment of an
initial value for a data object or variable. The manner in which initialization is performed
depends on programming language, as well as type, storage class, etc., of an object to be
initialized. Programming constructs which perform initialization are typically
called initializers and initializer lists. Initialization is distinct from (and preceded
by) declaration, although the two can sometimes be conflated in practice. The complement
of initialization is finalization, which is primarily used for objects, but not variables.
Initialization is done either by statically embedding the value at compile time, or
else by assignment at run time. A section of code that performs such initialization is
generally known as "initialization code" and may include other, one-time-only, functions
such as opening files; in object-oriented programming, initialization code may be part of
a constructor (class method) or an initializer (instance method). Setting a memory location
to hexadecimal zeroes is also sometimes known as "clearing" and is often performed by
an exclusive or instruction (both operands specifying the same variable), at machine
code level, since it requires no additional memory access.
Initializer

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

In C/C99/C++, an initializer is an optional part of a declarator. It consists of the '='


character followed by an expression or a comma-separated list of expressions placed in
curly brackets (braces). The latter list is sometimes called the "initializer list" or
"initialization list" (although the term "initializer list" is formally reserved for initialization
of class/struct members in C++; see below). A declaration which creates a data object,
instead of merely describing its existence, is commonly called a definition.
Many find it convenient to draw a distinction between the terms "declaration" and
"definition", as in the commonly seen phrase "the distinction between
a declaration and definition...", implying that a declaration merely designates a data object
(or function). In fact, according to the C++ standard, a definition is a declaration. Still, the
usage "declarations and definitions", although formally incorrect, is common. [1] Although
all definitions are declarations, not all declarations are definitions.
C examples:

int i = 0;
int k[4] = {0, 1};
char tx[3] = 'a';
char ty[2] = 'f';
struct Point {int x; int y;} p = { .y = 13, .x = 7 };

C++ examples:

int i2(0);
int j[2] = {rand(), k[0]};
MyClass* xox = new MyClass(0, "zaza");
point q = {0, i + 1};

Initializer list[edit]
In C++, a constructor of a class/struct can have an initializer list within the definition but
prior to the constructor body. It is important to note that when you use an initialization list,
the values are not assigned to the variable. They are initialized. In the below example, 0 is
initialized into re and im. Example:

struct IntComplex
{ IntComplex() : re(0), im(0)
{}

int re;
int im;
S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College

};

Here, the construct : re(0), im(0) is the initializer list.

Sometimes the term "initializer list" is also used to refer to the list of expressions in the
array or struct initializer.
C++11 provides for a more powerful concept of initializer lists, by means of a template,
called std::initializer_list.
Default initialization[edit]
Data initialization may occur without explicit syntax in a program to do so. For example,
if static variables are declared without an initializer, then those of primitive data types are
initialized with the value of zero of the corresponding type, while static objects of class type
are initialized with their default constructors.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

UNIT II

OPERATORS AND EXPRESSIONS: ARRAYS

Operators and Expressions:


Arithmetic operators – relational operators – logical operators – assignment operators –
increment and decrement operators – conditional operators – special operators –
arithmetic expression – evaluation of expression – Precedence of arithmetic operators –
type conversion in expression – operator precedence and associativity – mathematical
functions.
Arrays:
Introduction – One dimensional array – declaration of array – Initiating on two and
multidimensional arrays.

C OPERATORS

An operator is simply a symbol that is used to perform operations. There can be


many types of operations like arithmetic, logical, bitwise, etc.

There are following types of operators to perform different types of operations in C


language.

o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator

Precedence of Operators in C

The precedence of operator species that which operator will be evaluated first and next.
The associativity specifies the operator direction to be evaluated; it may be left to right or
right to left.

int value=10+20*10;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

The value variable will contain 210 because * (multiplicative operator) is evaluated before
+ (additive operator).

The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Comma , Left to right

ARITHMETIC OPERATORS

• You can use an arithmetic operator with one or two arguments to add, subtract,
multiply, and divide numeric values.

Operator Name Description

+ Addition to add two numbers together

- Subtraction to subtract one number from


another

* Multiplication to multiply one number by


another.

/ Division to divide one number by another.

% Modulus (Remainder) to find the remainder from dividing one


number by another

Arithmetic Operators Example:

i. 5 + 3 = 8

ii. 5 – 3 = 2

iii. 5 * 3 = 15

/3

=1

v. 5

%3

=2

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

• *, / and % will be performed before + or - in any expression.

• Brackets can be used to force a different order of evaluation to this.

Example

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

i. 2+5*4–3=?
ii. ii. (2 + 5) * (4 – 3) = ?

• Here are some arithmetic expressions used within assignment statements:

i. z=x+y
ii. no1 = x – y
iii. age = a * b + c
iv. velocity = distance / time
v. force = mass * acceleration
vi. count = count + 1

Integer Arithmetic
• When an arithmetic operation is performed on two whole numbers or integers than
such an operation is called as integer arithmetic.

• It always gives an integer as the result.

Example

Let x = 27 and y = 5 be two integer numbers. Then the integer operation leads to the
following results:

i. x + y = 32
ii. x – y = 22
iii. x * y = 115
iv. x%y=2
v. x/y=5

Floating-point Arithmetic

• When an arithmetic operation is preformed on two real numbers or fraction numbers


such an operation is called floating-point arithmetic.

Floating-point Arithmetic
Example

Let x = 14.0 and y = 4.0 then

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

i. x + y = 18.0
ii. x – y = 10.0
iii. x * y = 56.0
iv. x / y = 3.50

RELATIONAL OPERATORS

• An operator that compares two values.

For example, the expression:

x < 5 means x is less than 5

• This expression will have a value of TRUE if the variable x is less than 5; otherwise the
value of the expression will be FALSE.

• Relational operators are sometimes called comparison operators.

• Expressions that contain relational operators are called relational expressions.

• A simple relational expression contains only one relational operator and takes the
following form:

Where exp1 and exp2 are expressions, which may be simple constants, variables or
combination of them.

• The following are relational operators:

Operator Name Description

< Less than Indicates whether the value of the left


operand
is less than the value of the right
operand.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

<= Less than or equal to Indicates whether the value of the


left operand
is less than or equal to the value of the
right
operand.

> Greater than Indicates whether the value of the left


operand
is greater than the value of the right
operand.

>= Greater than or equal to Indicates whether the value of the


left
operand is greater than or equal to
the value
of the right operand.

• The following are relational operators:

Operator Name Description

== Equal to Indicates whether the value of the left


operand is equal to the value of the right
operand.

!= Not equal to Indicates whether the value of the left


operand is not equal to the value of the
right operand.

Example:

Let x = 2 and y = 5 then

i. x<y = True
ii. (x + 2) > (y * 2) = False
iii. (x + 3) <= y = True
iv. x != y = True
v. y > (3 + x) = False

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

LOGICAL OPERATORS

• An operator that compare or evaluate logical and relational expressions.

• The following are logical operators:

Operator Name

&& Logical AND

|| Logical OR

! Logical NOT

Logical AND

• This operator is used to evaluate two conditions or expressions with relational operators
simultaneously.

• If both the expressions to the left and to the right of the logical operator is true then the
whole compound expression is true.

Exp1 Exp2 Exp1 && Exp2

False False False

True False False

False True False

True True True

Example:

(a > b) && (x == 10)


S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College

The expression to the left is a > b and that on the right is x == 10, the whole expression is
true only if both expressions are true i.e., if a is greater than b and x is equal to 10.

Example:
Given a = 2, b = 3 and c = 5, evaluate the following logical expressions:

i. (a > b) && (c != 5) = False


ii. (a < b) && (c < b) = False
iii. (a > b) && (c == 5) = False
iv. (a < b) && (b < c) = True

Logical OR

• The logical OR is used to combine two expressions or the condition evaluates to true if
any one of the 2 expressions is true.

• The expression evaluates to true if any one of them is true or if both of them are true.

Exp1 Exp2 Exp1 || Exp2

False False False

True False True

False True True

True True True

Example:

(a < m) || (a < n)

The expression evaluates to true if any one of them is true or if both of them are true.

Example:

Given a = 2, b = 3 and c = 5, evaluate the following logical expressions:

i. (a > b) || (c != 5) = False
ii. (a < b) || (c < b) = True

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

iii. (a > b) || (c == 5) = True


iv. (a < b) || (b < c) = True

Logical NOT

• The logical NOT operator takes single expression and evaluates to true if the expression is
false and evaluates to false if the expression is true.

• In other words it just reverses the value of the expression.

Exp1 !Exp1

True False

False True

Example:

! (x >= y)

The NOT expression evaluates to true only if the value of x is neither greater than or equal
to y

Example:

Given a = 2, b = 3 and c = 5, evaluate the following logical expressions:


a) !(a > b) = True
b) !(a < b) = False
c) !(a > b || c == 5) = False

INCREMENT AND DECREMENT OPERATORS


• The increment and decrement operators are one of the unary operators which are very
useful in programming language.
• They are extensively used in loops.
• The syntax of the operators is given below:
++ variable name
variable name++
– –variable name
variable name– –

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

• The increment operator ++ adds the value 1 to the current value of operand.
• The decrement operator – – subtracts the value 1 from the current value of operand.
Example:

Suppose if we rewrite the above statement


as

Consider the following: m = 5;


y = m++; (postfix)
Then the value of y will be 5 and that of m
m = 5; y = ++m; (prefix) will be 6.

In this case the value of y and m


would be 6.

• A prefix operator first adds 1 to the operand and then the result is assigned to the
variable on the left.

• On the other hand, a postfix operator first assigns the value to the variable on the left and
then increments the operand.

Example 1:

x=4

y = ++x

PRINT x

PRINT y

What is the output? 5 5

Example 2:

x=3

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

y = x++

PRINT x

PRINT y

What is the output?

ASSIGNMENT OPERATORS

There are different kinds of the operators, such as arithmetic, relational, bitwise,
assignment, etc., in the C programming language. The assignment operator is used to assign
the value, variable and function to another variable. Let's discuss the various types of the
assignment operators such as =, +=, -=, /=, *= and %=.

Example of the Assignment Operators:

A = 5; // use Assignment symbol to assign 5 to the operand A


B = A; // Assign operand A to the B
B = &A; // Assign the address of operand A to the variable B
A = 20 \ 10 * 2 + 5; // assign equation to the variable A

Simple Assignment Operator (=):

It is the operator used to assign the right side operand or variable to the left side variable.

Syntax

int a = 5;
or int b = a;
ch = 'a';

Let's create a program to use the simple assignment operator in C.

Program1.c

#include <stdio.h>

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

#include <conio.h>
int main ()
{
// initialize variables
int n1, n2, c, x, y;
n1 = 5;
n2 = n1;
c = n1 + n2;
x = 20 / 4 * 2 + 5;
printf (" \n The value of n1: %d", n1);
printf (" \n The value of n2: %d", n2);
printf (" \n The value of c: %d", c);
printf (" \n The value of x: %d", x);
return 0;
}

Output

The value of n1: 5


The value of n2: 5
The value of c: 10
The value of x: 15

Plus and Assign Operator (+=):

The operator is used to add the left side operand to the left operand and then assign results
to the left operand.

Syntax

A += B;
Or
A = A + B;

Let's create a program to use the Plus and assign operator in C.

Program2.c

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

#include <stdio.h>
#include <conio.h>
int main ()
{
// initialize variables
int n1, n2, c;
n1 = 5;
n2 = 10;
n2 += n1;
printf (" \n The value of n1: %d", n1);
printf (" \n The value of n2: %d", n2);

return 0;
}

Output
of 5 b: 15
The value of a: 5
The value of b: 15

Subtract and Assign Operator (-=):

The operator is used to subtract the left operand with the right operand and then assigns
the result to the left operand.

Syntax

A -= B;
Or
A = A - B;

Let's create a program to use the Subtract and Assign (-=) operator in C.

Program3.c

#include <stdio.h>
#include <conio.h>
int main ()
{
// initialize variables

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

int n1, n2, c;


n1 = 5;
n2 = 10;
n2 -= n1; // Use Subtract and Equal operator (b = b - a)
printf (" \n The value of n1: %d", n1);
printf (" \n The value of n2: %d", n2);

return 0;
}

Output

The value of n1: 5


The value of n2: 5

Multiply and Assign Operator (*=)

The operator is used to multiply the left operand with the right operand and then assign
result to the left operand.

Syntax

A *= B;
Or
A = A * B;

Let's create a program to use the multiply and assign operator (*=) in C.

Multiply and Assign Operator (*=)

The operator is used to multiply the left operand with the right operand and then assign
result to the left operand.

Syntax

A *= B;
Or
A = A * B;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Let's create a program to use the multiply and assign operator (*=) in C.

CONDITIONAL OPERATOR

The conditional operator is also known as a ternary operator. The conditional


statements are the decision-making statements which depends upon the output of the
expression. It is represented by two symbols, i.e., '?' and ':'.

As conditional operator works on three operands, so it is also known as the ternary


operator.

The behavior of the conditional operator is similar to the 'if-else

' statement as 'if-else' statement is also a decision-making statement.

Syntax of a conditional operator

Expression1? expression2: expression3;

Meaning of the above syntax.

o In the above syntax, the expression1 is a Boolean condition that can be either true
or false value.
o If the expression1 results into a true value, then the expression2 will execute.
o The expression2 is said to be true only when it returns a non-zero value.
o If the expression1 returns false value then the expression3 will execute.
o The expression3 is said to be false only when it returns zero value.

Let's understand the ternary or conditional operator through an example.

#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // condition
al operator
return 0;
}

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

In the above code, we are taking input as the 'age' of the user. After taking input, we have
applied the condition by using a conditional operator. In this condition, we are checking the
age of the user. If the age of the user is greater than or equal to 18, then the statement1 will
execute, i.e., (printf("eligible for voting")) otherwise, statement2 will execute, i.e.,
(printf("not eligible for voting")).

Let's observe the output of the above program.

If we provide the age of user below 18, then the output would be:

If we provide the age of user above 18, then the output would be:

As we can observe from the above two outputs that if the condition is true, then the
statement1 is executed; otherwise, statement2 will be executed.

Till now, we have observed that how conditional operator checks the condition and based
on condition, it executes the statements. Now, we will see how a conditional operator is
used to assign the value to a variable.

Let's understand this scenario through an example.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

#include <stdio.h>
int main()
{
int a=5,b; // variable declaration
b=((a==5)?(3):(2)); // conditional operator
printf("The value of 'b' variable is : %d",b);
return 0;
}

In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value
to the 'a' variable. After the declaration, we are assigning value to the 'b' variable by using
the conditional operator. If the value of 'a' is equal to 5 then 'b' is assigned with a 3 value
otherwise 2.

Output

The above output shows that the value of 'b' variable is 3 because the value of 'a' variable is
equal to 5.

As we know that the behavior of conditional operator and 'if-else' is similar but they
have some differences. Let's look at their differences.

o A conditional operator is a single programming statement, while the 'if-else'


statement is a programming block in which statements come under the parenthesis.
o A conditional operator can also be used for assigning a value to the variable,
whereas the 'if-else' statement cannot be used for the assignment purpose.
o It is not useful for executing the statements when the statements are multiple,
whereas the 'if-else' statement proves more suitable when executing multiple
statements.
o The nested ternary operator is more complex and cannot be easily debugged, while
the nested 'if-else' statement is easy to read and maintain.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

ARITHMETIC EXPRESSIONS

C has a wide range of operators. An arithmetic expression is composed of operators


and operands. Operators act on operands to yield a result. Commonly used arithmetic
operators are +, -, *, / and %.

The plus sign (+) is used to add two values, the minus sign (-) to subtract one value
from another, the asterisk(*) to multiply two values, the division (/) to divide a value and
the modulus (%) to obtain the reminder of integer division. These are known as binary
operators since they operate on two values or variables.

Following are examples of arithmetic expressions :

result = x - y;

total = principle + interest;

numsquare = x * x;

celcius = (fahrenheit - 32) / 1.8

Notice the equal sign (=) in the above expressions, it is known as the assignment
operator. It assigns the value on the right hand side of the equal sign to the variable on the
left hand side.

In the last expression, parentheses are used to perform a certain operation first.
This is because in C, operators follow a precedence rule. *, / and % have a higher
precedence over + and -. Hence to override the precedence, parentheses should be used.
Expressions having operators of the same precedence are generally evaluated from left to
right. Another point to note is that in an expression which involves division, care should be
taken to avoid a division by zero, since this results in infinity or an abnormal value. In
Chapter 5 on control statements, we will see how a check can be done before a division
occurs and prevent such operations.

Program

#include

main()

{ int var1 = 10;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

int var2 = 2;

int var3 = 35;

int var4 = 8;

int result;

result = var1 + var2;

printf("Sum of var1 and var2 is %d\n", result);

result = var3 * var3;

printf("Square of var3 is %d\n", result);

result = var2 +var3 * var4; /* precedence */

printf("var2 + var3 * var4 =%d\n", result); }

EVALUATION OF EXPRESSION
Evaluate an expression represented by a String. The expression can contain
parentheses, you can assume parentheses are well-matched. For simplicity, you can
assume only binary operations allowed are +, -, *, and /. Arithmetic Expressions can be
written in one of three forms.
Infix Notation: Operators are written between the operands they operate on, e.g. 3 + 4.
Prefix Notation: Operators are written before the operands, e.g + 3 4
Postfix Notation: Operators are written after operands.

Infix Expressions are harder for Computers to evaluate because of the additional
work needed to decide precedence. Infix notation is how expressions are written and
recognized by humans and, generally, input to programs. Given that they are harder to
evaluate, they are generally converted to one of the two remaining forms. A very well
known algorithm for converting an infix notation to a postfix notation is Shunting Yard
Algorithm by Edgar Dijkstra. This algorithm takes as input an Infix Expression and
produces a queue that has this expression converted to postfix notation. The same
algorithm can be modified so that it outputs the result of the evaluation of expression
instead of a queue. The trick is using two stacks instead of one, one for operands, and one
for operators. The algorithm was described succinctly on http://www.cis.upenn.edu/

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

matuszek/cit594-2002/Assignments/5-expressions.htm, and is reproduced here. (Note


that credit for succinctness goes to the author of said page)

PRECEDENCE OF ARITHMETIC OPERATORS


Operator precedence determines the grouping of terms in an expression and
decides how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has a higher precedence than the addition
operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Example

Try the following example to understand operator precedence in C −


#include <stdio.h>

main() {

int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;

e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );

e = (a + b) * (c / d); // (30) * (15/5)


printf("Value of (a + b) * (c / d) is : %d\n", e );

e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );

return 0;
}
When you compile and execute the above program, it produces the following result

Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

TYPE CONVERSION IN EXPRESSION

A type cast is basically a conversion from one type to another. There are two types of type
conversion:
1. Implicit Type Conversion

Also known as ‘automatic type conversion’.


 Done by the compiler on its own, without any external trigger from the user.
 Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid loss of data.
 All the data types of the variables are upgraded to the data type of the variable
with largest data type.

bool -> char -> short int -> int ->


unsigned int -> long -> unsigned ->
long long -> float -> double -> long double

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long
long is implicitly converted to float).

Example of Type Implicit Conversion:

// An example of implicit conversion

#include<stdio.h>

int main()

int x = 10; // integer x

char y = 'a'; // character c

// y implicitly converted to int. ASCII

// value of 'a' is 97

x = x + y;

// x is implicitly converted to float

float z = x + 1.0;

printf("x = %d, z = %f", x, z);

return 0;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Output:
x = 107, z = 108.000000

2. Explicit Type Conversion

This process is also called type casting and it is user defined. Here the user can type cast
the result to make it of a particular data type.
The syntax in C:
(type) expression
Type indicated the data type to which the final result is converted.

// C program to demonstrate explicit type casting

#include<stdio.h>

int main()

double x = 1.2;

// Explicit conversion from double to int

int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Output:
sum = 2
Advantages of Type Conversion
 This is done to take advantage of certain features of type hierarchies or type
representations.
 It helps us to compute expressions containing variables of different data types.

OPERATOR PRECEDENCE AND ASSOCIATIVITY


Operator precedence determines the grouping of terms in an expression and
decides how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has a higher precedence than the addition
operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Category Operator Associativity

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Example Code

#include <stdio.h>
main() {
int a = 20;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}

Output

Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

MATHEMATICAL FUNCTIONS
C Math

C Programming allows us to perform mathematical operations through the functions


defined in <math.h> header file. The <math.h> header file contains various methods for
performing mathematical operations such as sqrt(), pow(), ceil(), floor() etc.

C Math Functions

There are various methods in math.h header file. The commonly used functions of math.h
header file are given below.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

No. Function Description

1) ceil(number) rounds up the given number. It returns the integer value which is
greater than or equal to given number.

2) floor(number) rounds down the given number. It returns the integer value which is
less than or equal to given number.

3) sqrt(number) returns the square root of given number.

4) pow(base, returns the power of given number.


exponent)

5) abs(number) returns the absolute value of given number.

C Math Example

Let's see a simple example of math functions found in math.h header file.

#include<stdio.h>
#include <math.h>
int main(){ printf("\n
%f",ceil(3.6));
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
printf("\n%f",pow(2,4));
printf("\n%f",pow(3,3));
printf("\n%d",abs(-12));
return 0;
}
400

4 Output:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

93.7K
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
12
.000000
3.000000

ARRAYS

INTRODUCTION
An array is a collection of items stored at contiguous memory locations. The idea is
to store multiple items of the same type together. This makes it easier to calculate the
position of each element by simply adding an offset to a base value, i.e., the memory
location of the first element of the array (generally denoted by the name of the array).
The base value is index 0 and the difference between the two indexes is the offset.
For simplicity, we can think of an array as a fleet of stairs where on each step is placed a
value (let’s say one of your friends). Here, you can identify the location of any of your
friends by simply knowing the count of the step they are on.
Remember: “Location of next index depends on the data type we use”.

Array’s size
In C language, array has a fixed size meaning once the size is given to it, it cannot be
changed i.e. you can’t shrink it neither can you expand it. The reason was that for
expanding, if we change the size we can’t be sure ( it’s not possible every time) that we
get the next memory location to us as free. The shrinking will not work because the
array, when declared, gets memory statically allocated, and thus compiler is the only
one can destroy it.
Types of indexing in an array:
 0 (zero-based indexing): The first element of the array is indexed by a subscript of 0.
 1 (one-based indexing): The first element of the array is indexed by the subscript of 1.
 n (n-based indexing): The base index of an array can be freely chosen. Usually,
programming languages allowing n-based indexing also allow negative index values,

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

and other scalar data types like enumerations, or characters may be used as an array
index.

#include <iostream>
using namespace std;

int main()
{
// Creating an integer array named arr of size 10.
int arr[10];
// accessing element at 0 index and setting its value
// to 5.
arr[0] = 5;
// access and print value at 0 index we get the output
// as 5.
cout << arr[0];
return 0;
}

Advantages of using arrays:


 Arrays allow random access to elements. This makes accessing elements by position
faster.
 Arrays have better cache locality that makes a pretty big difference in performance.
 Arrays represent multiple data items of the same type using a single name.

Disadvantages of using arrays:

You can’t change the size i.e. once you have declared the array you can’t change its
size because of static memory allocation. Here Insertion(s) and deletion(s) are difficult as
the elements are stored in consecutive memory locations and the shifting operation is
costly too.

Now if take an example of implementation of data structure Stack using array there
are some obvious flaw.
Let’s take the POP operation of the stack. The algorithm would go something like this.
1. Check for the stack underflow
2. Decrement the top by 1

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

So there what we are doing is that, the pointer to the topmost element is
decremented means we are just bounding our view actually that element stays there
taking up of the memory space. If you have any primitive datatype then it might be ok but
the object of an array would take a lot of memory.
Examples –
// A character array in C/C++/Java
char arr1[] = {'g', 'e', 'e', 'k', 's'};

// An Integer array in C/C++/Java


int arr2[] = {10, 20, 30, 40, 50};

// Item at i'th index in array is typically accessed


// as "arr[i]". For example arr1[0] gives us 'g'
// and arr2[3] gives us 40.
Usually, an array of characters is called a ‘string’, whereas an array of ints or floats is
simply called an array.
Applications on Array
1. Array stores data elements of the same data type.
2. Arrays can be used for CPU scheduling.
3. Used to Implement other data structures like Stacks, Queues, Heaps, Hash tables, etc.
If you like GeeksforGeeks and would like to contribute, you can also write an article using
write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your
article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

000
4.000000
One
di45751
16.0000
00dfd
27.000000
12
S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College

ONE DIMENSIONAL ARRAY

The variable allows us to store a single value at a time, what if we want to store roll
no. of 100 students? For this task, we have to declare 100 variables, then assign values to
each of them. What if there are 10000 students or more? As you can see declaring that
many variables for a single entity (i.e student) is not a good idea. In a situation like these
arrays provide a better way to store data.

What is an Array?

An array is a collection of one or more values of the same type. Each value is called
an element of the array. The elements of the array share the same variable name but each
element has its own unique index number (also known as a subscript). An array can be of
any type, For example: int, float, char etc. If an array is of type int then it's elements must be
of type int only.

To store roll no. of 100 students, we have to declare an array of


size 100 i.e roll_no[100]. Here size of the array is 100 , so it is capable of storing 100 values.
In C, index or subscript starts from 0, so roll_no[0] is the first element, roll_no[1] is the
second element and so on. Note that the last element of the array will be at roll_no[99] not
at roll_no[100] because the index starts at 0.

Arrays can be single or multidimensional. The number of subscript or index


determines the dimensions of the array. An array of one dimension is known as a one-
dimensional array or 1-D array, while an array of two dimensions is known as a two-
dimensional array or 2-D array.

Let's start with a one-dimensional array.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Conceptually you can think of a one-dimensional array as a row, where elements are stored
one after another.

Syntax: datatype array_name[size];

datatype: It denotes the type of the elements in the array.

array_name: Name of the array. It must be a valid identifier.

size: Number of elements an array can hold. here are some example of array declarations:

1int num[100];
2float temp[20];
3char ch[50];
num is an array of type int, which can only store 100 elements of type int.
temp is an array of type float, which can only store 20 elements of type float.
ch is an array of type char, which can only store 50 elements of type char.

Note: When an array is declared it contains garbage values.

The individual elements in the array:

1num[0], num[1], num[2],......, num[99]


2temp[0], temp[1], temp[2],....., temp[19]
3ch[0], ch[1], ch[2],....., ch[49]
We can also use variables and symbolic constants to specify the size of the array.

1 #define SIZE 10

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

2
3 int main()
4{
5 int size = 10;
6
7 int my_arr1[SIZE]; // ok
8 int my_arr2[size]; // not allowed until C99
9 // ...
10}
Note: Until C99 standard, we were not allowed to use variables to specify the size of the
array. If you are using a compiler which supports C99 standard, the above code would
compile successfully. However, If you're using an older version of C compiler like Turbo C+
+, then you will get an error.

The use of symbolic constants makes the program maintainable, because later if you want
to change the size of the array you need to modify it at once place only i.e in
the #define directive.

DECLARATION OF ARRAY

An "array declaration" names the array and specifies the type of its elements. It can
also define the number of elements in the array. A variable with array type is considered a
pointer to the type of the array elements.

Syntax

declaration:
declaration-specifiers init-declarator-listopt ;

init-declarator-list:
init-declarator
init-declarator-list , init-declarator

init-declarator:
declarator
declarator = initializer

declarator:
pointeropt direct-declarator

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

direct-declarator: /* A function declarator */


direct-declarator [ constant-expressionopt ]

Because constant-expression is optional, the syntax has two forms:

 The first form defines an array variable. The constant-expression argument within
the brackets specifies the number of elements in the array. The constant-expression,
if present, must have integral type, and a value larger than zero. Each element has the
type given by type-specifier, which can be any type except void. An array element
cannot be a function type.
 The second form declares a variable that has been defined elsewhere. It omits
the constant-expression argument in brackets, but not the brackets. You can use this
form only if you previously have initialized the array, declared it as a parameter, or
declared it as a reference to an array explicitly defined elsewhere in the program.

In both forms, direct-declarator names the variable and can modify the variable's type. The
brackets ([ ]) following direct-declarator modify the declarator to an array type.

Type qualifiers can appear in the declaration of an object of array type, but the qualifiers
apply to the elements rather than the array itself.

You can declare an array of arrays (a "multidimensional" array) by following the array
declarator with a list of bracketed constant expressions in this form:

type-specifier declarator [ constant-expression ] [ constant-expression ] ...

Each constant-expression in brackets defines the number of elements in a given dimension:


two-dimensional arrays have two bracketed expressions, three-dimensional arrays have
three, and so on. You can omit the first constant expression if you have initialized the array,
declared it as a parameter, or declared it as a reference to an array explicitly defined
elsewhere in the program.

You can define arrays of pointers to various types of objects by using complex declarators,
as described in Interpreting More Complex Declarators.

Arrays are stored by row. For example, the following array consists of two rows with three
columns each:

CCopy

char A[2][3];

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

The three columns of the first row are stored first, followed by the three columns of the
second row. This means that the last subscript varies most quickly.

To refer to an individual element of an array, use a subscript expression, as described


in Postfix Operators.

Examples

These examples illustrate array declarations:

float matrix[10][15];

The two-dimensional array named matrix has 150 elements, each having float type.

struct {
float x, y;
} complex[100];

This is a declaration of an array of structures. This array has 100 elements; each element is
a structure containing two members.

extern char *name[];

This statement declares the type and name of an array of pointers to char. The actual
definition of name occurs elsewhere.

Microsoft Specific

The type of integer required to hold the maximum size of an array is the size of size_t.
Defined in the header file STDDEF.H, size_t is an unsigned int with the range 0x00000000
to 0x7CFFFFFF.

INITIATING ON TWO AND MULTIDIMENSIONAL ARRAYS


Array-Basics

In C/C++, we can define multidimensional arrays in simple words as an array of


arrays. Data in multidimensional arrays are stored in tabular form (in row-major order).

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

The general form of declaring N-dimensional arrays:

data_type array_name[size1][size2]....[sizeN];

data_type: Type of data to be stored in the array.


Here data_type is valid C/C++ data type
array_name: Name of the array
size1, size2,....,sizeN: Sizes of the dimensions
Examples:

Two dimensional array:


int two_d[10][20];

Three dimensional array:


int three_d[10][20][30];

Size of multidimensional arrays


The total number of elements that can be stored in a multidimensional array can be
calculated by multiplying the size of all the dimensions.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

Multi dimensional arrays

Multi dimensional arrays are the arrays with a single variable name and more than
one subscript. Declaration is as like one dimensional but only change is there in the
subscript. It need data type array name and the subscript (indices).

The general syntax of multidimensional arrays :

Data-type array-name[index1][index2][index3]… [indexn];

Example of 4 dimensional array :

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

int multi[10][10][10];

here the multidimensional array ‘multi’ is an integer array the sizes are given as the
subscript.

Matrix

A two dimensional array is called a matrix. Thus it is two dimensional it has two
subscripts. A matrix is used to store a table of values. As it is similar to a table a matrix has
rows and columns. Thus the first subscript refers as the rows and second index as the
columns.

Syntax :

Data-type matrix-name[rows][columns];

Example :

int a[2][2];

here a is a matrix with 2 rows and 2 columns. We can say ‘a’ is a 2 x 2 (read 2 by two)
matrix.

Column 0 Column 1

Row 0 a[0][0] a[0][1]

Row 1 a[1][0] a[1][1]

Assigning values to the matrix

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

A matrix can be assigned values by specifying bracketed values for each row as Follows.

int a[2][2] = {0,1,2,3};

The other method which is more readable is like


Int a[2][2] = {
{0, 1} , //first row
{2,3} //second row
};

Here the values enclosed in brackets denotes the rows of the matrix.

This two initializations results as a matrix like

0 1

2 3

For accessing matrix variables we use the subscripts along with the name of the
matrix. But make sure that we number the values of rows and columns from 0. In the
above example to access the value 1 we use a[0][1] that is the position of 1 is in the 0 th row
and the 1st column.

The dynamic initialization of matrix, need two loops one for row values and another
for column values.

Program to assign the values to the matrix and print that matrix

#include <stdio.h>
void main()
{
int i, j, m, n, a[10][10];

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

printf("Enter the number of rows and columns of matrix ");


scanf("%d%d", &m, &n);
printf("Enter the elements of matrix ");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
scanf("%d", &a[i][j]);
}
}
printf("The elements of matrix a is");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
printf("%d", a[i][j] “ “);
}
printf(“\n”) // for new line( for rows)
}
}
When execute this program it reads the size and then assign the values to the matrix as , if
m=2,n=3 then the values assigned is like
a[0][0] = 0;
a[0][1] = 10;
a[0][2] = 8;
a[1][0] = 4;
a[1][1] = 9;
a[1][2] = 12;

0 10 8

4 9 12

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

The values are assigned like this and it displays the matrix as

0 10 8
4 9 12

Operations on matrices

As on arrays a set of operations are performed using matrices, they may be

 Addition
 Subtraction
 Multiplication
 Transpose etc.

For the first three we need two or more arrays , transpose is done on that same matrix, it is
changing the values on rows to columns and columns as rows.

Program to add two matrices.

#include <stdio.h>
int main()
{
int m, n, i, j, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix");
for (i = 0 ; i < m ; i++ )
{
for ( j= 0 ; j < n ; j++)
{
scanf("%d", &first[i][j]);
}
}
printf("Enter the elements of second matrix ");
for ( i = 0 ; i< m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

scanf("%d", &second[c][d]);
}
}
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
sum[i][j] = first[i][j] + second[i][j];
}
printf("Sum is") ;
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
printf("%d\t", sum[i][j]);
}
printf("\n");
}
}

first

10 5

20 10

second

9 10

3 25

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

sum

19 15

23 35

Two – dimensional array is the simplest form of a multidimensional array. We can see a
two – dimensional array as an array of one – dimensional array for easier understanding.

 The basic form of declaring a two-dimensional array of size x, y:


Syntax:

data_type array_name[x][y];
data_type: Type of data to be stored. Valid C/C++ data type.
 We can declare a two-dimensional integer array say ‘x’ of size 10,20 as:

int x[10][20];
 Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the
row number and ‘j’ is the column number.
 A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where
the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1).
A two – dimensional array ‘x’ with 3 rows and 3 columns is shown below:

Initializing Two – Dimensional Arrays: There are two ways in which a Two-Dimensional
array can be initialized.
First Method:

int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}


The above array has 3 rows and 4 columns. The elements in the braces from left to right
are stored in the table also from left to right. The elements will be filled in the array in
order, the first 4 elements from the left in the first row, the next 4 elements in the second
row, and so on.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Better Method:

int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};


This type of initialization makes use of nested braces. Each set of inner braces represents
one row. In the above example, there is a total of three rows so there are three sets of inner
braces.
Accessing Elements of Two-Dimensional Arrays: Elements in Two-Dimensional arrays are
accessed using the row indexes and column indexes.
Example:

int x[2][1];
The above example represents the element present in the third row and second column.
Note: In arrays, if the size of an array is N. Its index will be from 0 to N-1. Therefore, for row
index 2 row number is 2+1 = 3.
To output all the elements of a Two-Dimensional array we can use nested for loops. We will
require two for loops. One to traverse the rows and another to traverse columns.

// C++ Program to print the elements of a

// Two-Dimensional array

#include<iostream>

using namespace std;

int main()

// an array with 3 rows and 2 columns.

int x[3][2] = {{0,1}, {2,3}, {4,5}};

// output each array element's value

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

for (int i = 0; i < 3; i++)

for (int j = 0; j < 2; j++)

cout << "Element at x[" << i

<< "][" << j << "]: ";

cout << x[i][j]<<endl;

return 0;

Output:

Element at x[0][0]: 0
Element at x[0][1]: 1
Element at x[1][0]: 2
Element at x[1][1]: 3
Element at x[2][0]: 4
Element at x[2][1]: 5

Three-Dimensional Array

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Initializing Three-Dimensional Array: Initialization in a Three-Dimensional array is


the same as that of Two-dimensional arrays. The difference is as the number of dimensions
increases so the number of nested braces will also increase.
Method 1:

int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,


11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23};
Better Method:

int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};

Accessing elements in Three-Dimensional Arrays: Accessing elements in Three-Dimensional


Arrays is also similar to that of Two-Dimensional Arrays. The difference is we have to use
three loops instead of two loops for one additional dimension in Three-dimensional Arrays.

// C++ program to print elements of Three-Dimensional


// Array
#include<iostream>
using namespace std;
int main()
{
// initializing the 3-dimensional array
int x[2][3][2] =
{
{ {0,1}, {2,3}, {4,5} },
{ {6,7}, {8,9}, {10,11} }
};

// output each element's value


for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

{
cout << "Element at x[" << i << "][" << j
<< "][" << k << "] = " << x[i][j][k]
<< endl;
}
}
}
return 0;
}

Output:

Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11

In similar ways, we can create arrays with any number of dimensions. However,
the complexity also increases as the number of dimensions increases.
The most used multidimensional array is the Two-Dimensional Array.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

UNIT III
DECISION MAKING, BRANCHING, LOOPING
Decision Making and Branching:
Introduction to if, if...else, nesting of if ...else statements- else if ladder – The switch
statement, The ?: Operator – The goto Statement.
Decision Making and Looping:
Introduction - while loop –do loop –do while lopp –for loop –Nested Loops–break– continue–goto–
exit–return.

DECISION MAKING AND BRANCHING


INTRODUCTION

In C programming it support sequential program statements which execute one


statement immediately after another. Here the flow is sequential it never change the flow
of control from the next line. The compiler executes the program sequentially in the order
which they appear. This happens when there are no options and if the repeated steps are
not needed. But there are another option when we need the options and when we want to
use the selective steps repeatedly. In many situations we may have to change the order of
execution and want to repeat certain steps based on any condition or until the condition
meets, which means decision making. C supports much decision making or control
statements.

The main important decision making statements in c are as follows.

 If statement
 Switch statement

IF STATEMENT

‘If’ is the most powerful decision making statement in C language. Thus it is used to control
the execution of statements. ‘If’ is used along with an expression. It is a two way
branching or decision making statement.

Syntax :

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

if(test expression)
{
Body of if;
}

Using an ‘if’ a computer first evaluate the expression and if it is true the body of if is
executed which means the flow of control passes to the if’s body, or if the test condition
is false then the flow of control passes to the immediate step next to if’s body. If there are
more than one step in the body of ‘if’ they are normally written with in brackets ‘{ }’ to
denote it is the body of ‘if’.

The test expression will return a Boolean value which is a’0’ or ‘1’. Here 1 is ‘true’ and 0
denotes it is ‘false’.

Two way branching

Example:

if(age>55){
printf(“ Retired”);
}

Depending upon the complexity and conditions to be tested if can be further subdivided.

 Simple if
 if…..else
 nested if…else
 if…else…if

ladder simple if

statement

The general syntax of a simple if statement is

if(test expression)
{
Body of if;
}

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Statement X;

The body of ‘if’ may be a single statement or group of statements. When the test expression
returns a true value these body of if is executed. If the condition is false the flow of control
passes to the statement X. The statement X will be executed in both cases.

IF ELSE

Syntax of if else statement:


If condition returns true then the statements inside the body of “if” are executed and the
statements inside body of “else” are skipped.
If condition returns false then the statements inside the body of “if” are skipped and the
statements in “else” are executed.

if(condition) {
// Statements inside body of if
}
else {
//Statements inside body of else
}

Flow diagram of if else statement

Example of if else statement

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

In this program user is asked to enter the age and based on the input, the if..else
statement checks whether the entered age is greater than or equal to 18. If this condition
meet then display message “You are eligible for voting”, however if the condition doesn’t
meet then display a different message “You are not eligible for voting”.

#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
/* This statement will only execute if the
* above condition (age>=18) returns true
*/
printf("You are eligible for voting");
}
else
{
/* This statement will only execute if the
* condition specified in the "if" returns false.
*/
printf("You are not eligible for voting");
}
return 0;
}
Output:

Enter your age:14


You are not eligible for voting
Note: If there is only one statement is present in the “if” or “else” body then you do not need
to use the braces (parenthesis). For example the above program can be rewritten like this:

#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

scanf("%d",&age);
if(age >=18)
printf("You are eligible for voting");
else
printf("You are not eligible for voting");
return 0;
}

NESTING OF IF ELSE STATEMENTS

When an if else statement is present inside the body of another “if” or “else” then
this is called nested if else.
Syntax of Nested if else statement:

if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}

Example of nested if..else

#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 != var2)

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

{
printf("var1 is not equal to var2\n");
//Nested if else
if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
printf("var2 is greater than var1\n");
}
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
Output:

Input the value of var1:12


Input the value of var2:21
var1 is not equal to var2
var2 is greater than var1

NESTED IF STATEMENT

It is used when a series of decisions are involved and have to use more than one
if…else statement.

Syntax :

if(condition 1)
{
if(condition 2)
{
body of if;
}
else
{
Body of else;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

}
}
else
{
Body of else;
}

Statement x;

Example :

if( a>b)
{
if(a>c)
printf(“ a is greater”);
else
printf(“ c is greater”);
}
else
{
if(b>c)
{
Printf(“b is greater”);
}
else
{
Printf(“c is greater”);
}
}

Here it explains the greatest among three numbers.

ELSE IF LADDER
This is the most general way of writing a multi-way decision.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Syntax
Refer the syntax given below −

if (condition1)
stmt1;
else if (condition2)
stmt2;
-----
-----
else if (condition n)
stmtn;
else
stmt x;

Algorithm
Refer the algorithm given below −

START

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Step 1: Declare int variables.


Step 2: Read a,b,c,d values at runtime
Step 3: i. if(a>b && a>c && a>d)
Print a is largest
ii. else if(b>c && b>a && b>d)

Print b is largest
iii. else if(c>d && c>a && c>b)

Print c is largest
iv. else

print d is largest
STOP
Example
Following is the C program to execute Else If Ladder conditional operators −

#include<stdio.h
> void main (){
int a,b,c,d;
printf("Enter the values of a,b,c,d:
"); scanf("%d%d%d
%d",&a,&b,&c,&d); if(a>b && a>c
&& a>d){
printf("%d is the largest",a);
}else if(b>c && b>a && b>d)
{ printf("%d is the
largest",b);
}else if(c>d && c>a && c>b)
{ printf("%d is the
largest",c);
}else{

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Output
You will see the following output −

Run 1:Enter the values of a,b,c,d: 2 4 6 8


8 is the largest
Run 2: Enter the values of a,b,c,d: 23 12 56 23
56 is the largest

THE SWITCH STATEMENT

If is a conditional statement where ‘switch’ is a selection statement which means if


we want to select one from many alternatives we use ‘switch’. The selective statement
‘switch’ is a multi way decision statement, that is using a single expression we can direct
the flow of control to multiple paths. ‘Switch ‘ statement tests the value of given expression
or variable against a list of case values and when a match is found that block of
statements associated with that case is executed.

Syntax :

switch(expression)
{
case constant1 :
block1;
break;
case constant2 :
block2;
break;
case constant n:
block n;
break;
.
.
.
default:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

default block;
break;
}

statement x;

When the ‘switch’ is executed the value of the expression is successfully compared
against the case’s constants. When a case constant is found the block of codes associated
with it is executed, and if till the last case constant no match is found the block
associated with the default case is executed. The default is an optional case . If it is not
present and no matches are found then control passes to the statement x.

Example :

int num;
printf(“enter a number”);
scanf(‘%d”,&num);
switch(num)
{
case 1:
printf(“Sunday”);
break;
case 2:
printf(“Monday”);
break;
case 3:
printf(“Tuesday”);
break;
case 4:
printf(“Wednesday”);
break;
case 5:
printf(“Thursday”);
break;
case 6:
printf(“Friday”);
break;
case 7:
printf(“Saturday”);

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

break;
default:
printf(“wrong choice”);
break;
}

Here according to numbers from 1 to 7 the corresponding day is displayed. If we input any
number other than 1 to 7 then the default case is executed.

THE ?: OPERATOR

?: is a ternary operator that is part of the syntax for basic conditional expressions in
several programming languages. It is commonly referred to as the conditional
operator, inline if (iif), or ternary if. An expression a ? b : c evaluates to b if the value
of
a is true, and otherwise to c . One can read it aloud as "if a then b otherwise c".

It originally comes from CPL, in which equivalent syntax


fo
e1 ? e2 : e3 was e1 → e2, e3 .[1][2]
r
Although many ternary operators are possible, the conditional operator is so
common, and other ternary operators so rare, that the conditional operator is commonly
referred to as the ternary operator.
The ternary operator take three arguments:

1. The first is a comparison argument


2. The second is the result upon a true comparison
3. The third is the result upon a false comparison
It helps to think of the ternary operator as a shorthand way or writing an if-else
statement. Here’s a simple decision-making example using if and else:
int a = 10, b = 20, c;

if (a < b) {
c = a;
}
else {
c = b;
}

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

printf("%d", c);
This example takes more than 10 lines, but that isn’t necessary. You can write the above
program in just 3 lines of code using a ternary operator.

Syntax

condition ? value_if_true : value_if_false


The statement evaluates to value_if_true if condition is met, and value_if_false otherwise.
Here’s the above example rewritten to use the ternary operator:

int a = 10, b = 20, c;

c = (a < b) ? a : b;

printf("%d", c);

Output of the example above should be:

10

c is set equal to a, because the condition a < b was true.


Remember that the arguments value_if_true and value_if_false must be of the same type,
and they must be simple expressions rather than full statements.
Ternary operators can be nested just like if-else statements. Consider the following code:

int a = 1, b = 2, ans;
if (a == 1) {
if (b == 2) {
ans = 3;
} else {
ans = 5;
}
} else {
ans = 0;
}
printf ("%d\n", ans);
Here's the code above rewritten using a nested ternary operator:

int a = 1, b = 2, ans;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

ans = (a == 1 ? (b == 2 ? 3 : 5) : 0);
printf ("%d\n", ans);

The output of both sets of code above should be:

GOTO STATEMENT

The goto statement is known as jump statement in C. As the name suggests, goto is
used to transfer the program control to a predefined label. The goto statment can be used
to repeat some part of the code for a particular condition. It can also be used to break the
multiple loops which can't be done by using a single break statement. However, using goto
is avoided these days since it makes the program less readable and complecated.

Syntax:

1. label:
2. //some part of the code;
3. goto label;

Let's see a simple example to use goto statement in C language.

#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}

Output:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Enter the number whose table you want to print?10


10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

DECISION MAKING AND LOOPING


INTRODUCTION
Execution of a statement or set of statement repeatedly is called as looping.
The loop may be executed a specified number of times and this depends on the
satisfaction of a test condition.
A program loop is made up of two parts one part is known as body of the loop and
the other is known as control condition.
Depending on the control condition statement the statements within the loop may
be executed repeatedly.
Depending on the position of the control statement in the loop, a control structure
may be classified either as an entry controlled loop or as an exit controlled loop.

Entry Controlled Loop:


When the control statement is placed before the body of the loop then such loops
are called as entry controlled loops.
If the test condition in the control statement is true then only the body of the loop is
executed.
If the test condition in the control statement is not true then the body of the loop
will not be executed. If the test condition fails in the first checking itself the body of the
loop will never be executed.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Exit Controlled Loop:

When the control statement is placed after the body of the loop then such loops are
called as exit controlled loop.

In this the body of the loop is executed first then the test condition in the control statement
is checked.

If it is true then the body of the loop is executed again.


If the test condition is false, the body of the loop will not be executed again. In exit
controlled loops even if the test condition fails in the first attempt itself the body of the loop
is executed at least once.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Following are the steps in a looping process:

1. Initialization of loop control variable


2. Test of a specific condition for the execution of the loop
3. Execution of the statements in the body of the loop
4. Altering the value of the loop control variable

In the beginning the loop control variable is initialized after that step2, step3 and
step4 are carried out till specified test condition becomes false.
The test may be either to determine whether the loop has been repeated the specified
number of times or to determine whether a particular condition has been met. The C
language provides 3 loop structures.

1. while loop.
2. do loop.
3. for loop.

WHILE LOOP

While loop is also known as a pre-tested loop. In general, a while loop allows a part
of the code to be executed multiple times depending upon a given boolean condition. It can
be viewed as a repeating if statement. The while loop is mostly used in the case where the
number of iterations is not known in advance.

Syntax of while loop in C language

The syntax of while loop in c language is given below:

1. while(condition){
2. //code to be executed
3. }

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Flowchart of while loop in C

Example of the while loop in C language

Let's see the simple program of while loop that prints table of 1.

1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }

Output
1
2
3
4
5
6
7
8
9
10

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

WHILE AND DO/WHILE LOOPS

This is similar to for loops, but much simpler than it. While and do/while loops have
similar functionality with small difference. The while loop checks for the condition/s and
executes the set of statements within it until the condition is false. It does not require any
initial values or increment factor. It always gets executed until the condition is false.
In while loop, condition is checked at the beginning of the loop whereas in do/while
loop condition is checked at the end of the loop. Hence in while loop, if the condition is false
at the beginning itself, then it will not execute its body and comes out of the loop. But in
do/while loop as the condition is checked at the end, it will execute body of it at least once.

The general syntax for while and do/while loops are given below :
while (condition/s)

{ Expression /

statements;

do{

Expression / statements;

} while (condition/s);

Like in for loops, these conditions can be anything. It can be a single condition with any
operator or multiple conditions joined using logical operator.

Let us consider the same example of displaying first 15 natural numbers using both while
and do while loops.

#include

void main() {

int intNum = 0;

printf("\n Example of WHILE Loop\n");

printf("First 15 natural numbers are: \n");

while (intNum < 15){

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

printf("%d ", intNum);

intNum++;

printf("\n Example of DO/WHILE Loop\n");

printf("First 15 natural numbers in descending order is: \n");

while (intNum >=0){

printf("%d ", intNum--);

In the example above, intNum is used to check for the condition and display the
numbers. Initially it is declared and initialized. In while and do/while loops we cannot
declare and initialize it like we did in for loops. This is because, these loops checks for the
conditions and does not have any execution for the initial value. Hence if we declare or
initialize the variable in while loop, it will check for the same condition repeatedly and the
loop will never terminate

When the while loop starts, it checks for the value in intNum with the condition, i.e.;
0. In the next lines it finds do/while loop. Here we have not initialized intNum and it has
value 15. Since it is a do while loop, it does not checks for the condition first. Hence it enters
the loop without any condition check. It prints the value of intNum which is 15. You will
find the printf statement has postfix decrement operator on intNum – intNum –. Though we
have decrement operator, printf statement prints 15 instead of 14. This is because of the
priority of operator.
Since it is a postfix operator, it first prints the value of intNum and then decrements
the value of intNum. Hence intNum gets value 14 after printing it. Thus 15 is displayed at
the first. Then comes the while condition. It checks if intNum >=0 → 14 >=0 → TRUE. Hence
it repeats the loop and prints 14 and decrements the number. Again checks for condition
and repeats the loop until it is false. i.e.; when intNum = -1, it checks -1 >=0 → FALSE.
Hence comes out of the loop. Now intNum will have value -1. This is how both while and
do/while loop works.
Here we have given the example of displaying the numbers with increment and
decrement operators. It need not be increment / decrement by one. We can have any factor

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

to increment or decrement. Even we can have multiplication or division or any


other arithmetic expression, like in for loop.

Let us consider another example without any increment/decrement operator.


Consider the program to enter the marks of the student from the keyboard till the user
wants to enter the names.

#include

void main() {

int intOption=1;

int intMark;

while (intOption ==1){

printf("\n Please enter the marks of a student:");

scanf("%d", &intMark);

printf("\n Do you want to continue(Yes - 1/ No - 0)?: \n");

scanf("%d", &intOption);

Here the program checks for the user input value and the loop continues until they
enter any other number other than 1, though it says 0 for No. this is because the condition
in while loop is intOption == 1. This means when any other number is entered the
condition returns FALSE and loop terminates.

Same can be re-written using do/while loop. Here initialization of intOption is not
required as the condition is checked at the end. Hence it executes the loop at least once
irrespective of the option being entered or whether it is initialized or not. Here you can
note that we have entered option as 5 to terminate the loop even though it says 0 for No.
#include

void main() {

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

int intOption;

int intMark;

do{

printf("\n Please enter the marks of a student:");

scanf("%d", &intMark);

printf("\n Do you want to continue(Yes - 1/ No - 0)?: \n");

scanf("%d", &intOption);

} while (intOption == 1);

FOR LOOP

The for loop in C language is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like the array and linked
list.

Syntax of for loop in C

The syntax of for loop in c language is given below:

1. for(Expression 1; Expression 2; Expression 3){


2. //code to be executed
3. }

Flowchart of for loop in C

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Let's see the simple program of for loop that prints table of 1.

1. #include<stdio.h>
2. int main(){
3. int i=0;
4. for(i=1;i<=10;i++){
5. printf("%d \n",i);
6. }
7. return 0;
8. }

Output

1
2
3
4
5
6

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

7
8
9
10

NESTED LOOPS

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping
of statements inside another loop. Let's observe an example of nesting loops in C.

Any number of loops can be defined inside another loop, i.e., there is no restriction for
defining any number of loops. The nesting level can be defined at n times. You can define
any type of loop inside another loop; for example, you can define 'while' loop inside a 'for'
loop.

Syntax of Nested loop

Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}

Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-
while' loop.

Nested for loop

The nested for loop means any type of loop which is defined inside the 'for' loop.

for (initialization; condition; update)


{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Example of nested for loop

#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}

Explanation of the above code

o First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
o The program control checks whether the condition 'i<=n' is true or not.
o If the condition is true, then the program control passes to the inner loop.
o The inner loop will get executed until the condition is true.
o After the execution of the inner loop, the control moves back to the update of the
outer loop, i.e., i++.
o After incrementing the value of the loop counter, the condition is checked again, i.e.,
i<=n.
o If the condition is true, then the inner loop will be executed again.
o This process will continue until the condition of the outer loop is true.

Output:

Nested while loop

The nested while loop means any type of loop which is defined inside the 'while' loop.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

while(condition)
{
while(condition)
{
// inner loop statements.
}
// outer loop statements.
}

Example of nested while loop

#include <stdio.h>
int main()
{
int rows; // variable declaration
int columns; // variable declaration
int k=1; // variable initialization
printf("Enter the number of rows :"); // input the number of rows.
scanf("%d",&rows);
printf("\nEnter the number of columns :"); // input the number of columns.
scanf("%d",&columns);
int a[rows][columns]; //2d array declaration
int i=1;
while(i<=rows) // outer loop
{
int j=1;
while(j<=columns) // inner loop
{
printf("%d\t",k); // printing the value of k.
k++; // increment counter
j++;
}
i++;
printf("\n");
}
}

Explanation of the above code.

o We have created the 2d array, i.e., int a[rows][columns].

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

o The program initializes the 'i' variable by 1.


o Now, control moves to the while loop, and this loop checks whether the condition is
true, then the program control moves to the inner loop.
o After the execution of the inner loop, the control moves to the update of the outer
loop, i.e., i++.
o After incrementing the value of 'i', the condition (i<=rows) is checked.
o If the condition is true, the control then again moves to the inner loop.
o This process continues until the condition of the outer loop is true.

Output:

Nested do..while loop

The nested do..while loop means any type of loop which is defined inside the 'do..while'
loop.

1. do
2. {
3. do
4. {
5. // inner loop statements.
6. }while(condition);
7. // outer loop statements.
8. }while(condition);

Example of nested do..while loop.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

#include <stdio.h>
int main()
{
/*printing the pattern
********
********
********
******** */
int i=1;
do // outer loop
{
int j=1;
do // inner loop
{
printf("*");
j++;
}while(j<=8);
printf("\n");
i++;
}while(i<=4);
}

Output:

BREAK STATEMENT

The break is a keyword in C which is used to bring the program control out of the loop. The
break statement is used inside loops or switch statement. The break statement breaks the
loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

proceeds to outer loops. The break statement in C can be used in the following two
scenarios:

1. With switch case


2. With loop

Syntax:

1. //loop or switch case


2. break;

Example

#include<stdio.h>
#include<stdlib.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);

Output

0 1 2 3 4 5 came outside of loop i = 5

Example of C break statement with switch case

Click here to see the example of C break with the switch statement

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

C break statement with the nested loop

In such case, it breaks only the inner loop, but not outer loop.

1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. printf("%d &d\n",i,j);
7. if(i==2 && j==2){
8. break;//will break loop of j only
9. }
10. }//end of for loop
11. return 0;
12. }

Output

11
12
13
21
22
31
32
33

As you can see the output on the console, 2 3 is not printed because there is a break
statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 are printed because the break
statement is used to break the inner loop only.

break statement with while loop

Consider the following example to use break statement inside while loop.

#include<stdio.h>

void main ()
{
int i = 0;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

while(1)
{
printf("%d ",i);
i++;
if(i == 10)
break;
}
printf("came out of while loop");
}

Output

0 1 2 3 4 5 6 7 8 9 came out of while loop

BREAK STATEMENT

Consider the following example to use the break statement with a do-while loop.

#include<stdio.h>
void main ()
{
int n=2,i,choice;
do
{
i=1;
while(i<=10)
{
printf("%d X %d = %d\n",n,i,n*i);
i++;
}
printf("do you want to continue with the table of %d , enter any non-
zero value to continue.",n+1);
scanf("%d",&choice);
if(choice == 0)
{
break;
}
n++;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

}while(1);
}

Output

2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
do you want to continue with the table of 3 , enter any non-zero value to continue.1
3X1=3
3X2=6
3X3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
do you want to continue with the table of 4 , enter any non-zero value to continue.0

CONTINUE STATEMENT

The continue statement in C language is used to bring the program control to the beginning
of the loop. The continue statement skips some lines of code inside the loop and continues
with the next iteration. It is mainly used for a condition so that we can skip some code for a
particular condition.

Syntax:

//loop statements
continue;
//some lines of the code which is to be skipped

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Continue statement example 1

#include<stdio.h>
void main ()
{
int i = 0;
while(i!=10)
{
printf("%d", i);
continue;
i++;
}
}

Output

infinite loop

Continue statement example 2

#include<stdio.h>
int main(){
int i=1;//initializing a local variable
//starting a loop from 1 to 10
for(i=1;i<=10;i++){
if(i==5){//if value of i is equal to 5, it will continue the loop
continue;
}
printf("%d \n",i);
}//end of for loop
return 0;
}

Output

1
2
3
4
6
7

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

8
9
10

As you can see, 5 is not printed on the console because loop is continued at i==5.

C continue statement with inner loop

In such case, C continue statement continues only inner loop, but not outer loop.

#include<stdio.h>
int main(){
int i=1,j=1;//initializing a local variable
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
if(i==2 && j==2){
continue;//will continue loop of j only
}
printf("%d %d\n",i,j);
}
}//end of for loop
return 0;
}

Output

11
12
13
21
23
31
32
33

As you can see, 2 2 is not printed on the console because inner loop is continued at i==2
and j==2.

GOTO STATEMENT

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

The goto statement is known as jump statement in C. As the name suggests, goto is
used to transfer the program control to a predefined label. The goto statment can be used
to repeat some part of the code for a particular condition. It can also be used to break the
multiple loops which can't be done by using a single break statement. However, using goto
is avoided these days since it makes the program less readable and complecated.

Syntax:

label:
//some part of the code;
goto label;

goto example

Let's see a simple example to use goto statement in C language.

#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}

Output:

Enter the number whose table you want to print?10


10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

10 x 10 = 100

EXIT

The exit() function is used to terminate a process or function calling immediately in


the program. It means any open file or function belonging to the process is closed
immediately as the exit() function occurred in the program. The exit() function is the
standard library function of the C, which is defined in the stdlib.h header file. So, we can say
it is the function that forcefully terminates the current program and transfers the control to
the operating system to exit the program. The exit(0) function determines the program
terminates without any error message, and then the exit(1) function determines the
program forcefully terminates the execution process.

Important points of the exit() function

Following are the main points of the exit function in C programming as follows:

1. We must include the stdlib.h header file while using the exit () function.
2. It is used to terminate the normal execution of the program while encountered the
exit () function.
3. The exit () function calls the registered atexit() function in the reverse order of their
registration.
4. We can use the exit() function to flush or clean all open stream data like read or
write with unwritten buffered data.
5. It closed all opened files linked with a parent or another function or file and can
remove all files created by the tmpfile function.
6. The program's behaviour is undefined if the user calls the exit function more than
one time or calls the exit and quick_exit function.
7. The exit function is categorized into two parts: exit(0) and exit(1).

Syntax of the exit() function

1. void exit ( int status);

The exit() function has no return type.

Important points of the exit() function

Following are the main points of the exit function in C programming as follows:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

1. We must include the stdlib.h header file while using the exit () function.
2. It is used to terminate the normal execution of the program while encountered the
exit () function.
3. The exit () function calls the registered atexit() function in the reverse order of their
registration.
4. We can use the exit() function to flush or clean all open stream data like read or
write with unwritten buffered data.
5. It closed all opened files linked with a parent or another function or file and can
remove all files created by the tmpfile function.
6. The program's behaviour is undefined if the user calls the exit function more than
one time or calls the exit and quick_exit function.
7. The exit function is categorized into two parts: exit(0) and exit(1).

Syntax of the exit() function

1. void exit ( int status);

The exit() function has no return type.

7M

203

Major Internet Services Hit By Brief But Widespread Outage

int status: It represents the status value of the exit function returned to the parent process.

Example 1: Program to use the exit() function in the for loop

Let's create a program to demonstrate the exit (0) function for normal terminating the
process in the C programming language.

1. #include <stdio.h>
2. #include <stdlib.h>
3. int main ()
4. {
5. // declaration of the variables
6. int i, num;
7. printf ( " Enter the last number: ");
8. scanf ( " %d", &num);

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

9. for ( i = 1; i<num; i++)


10. {
11. // use if statement to check the condition
12. if ( i == 6 )
13.
14. /* use exit () statement with passing 0 argument to show termination of the program witho
ut any error message. */
15. exit(0);
16.
17. else
18.
19. printf (" \n Number is %d", i);
20. }
21. return 0;
22. }

Output

Enter the last number: 10

Number is 1
Number is 2
Number is 3
Number is 4
Number is 5

RETURN

A return statement ends the execution of a function, and returns control to the
calling function. Execution resumes in the calling function at the point immediately
following the call. A return statement can return a value to the calling function. For more
information, see Return type.

Syntax

jump-statement:
return expressionopt ;

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

The value of expression, if present, is returned to the calling function. If expression is


omitted, the return value of the function is undefined. The expression, if present, is
evaluated and then converted to the type returned by the function. When
a return statement contains an expression in functions that have a void return type, the
compiler generates a warning, and the expression isn't evaluated.

If no return statement appears in a function definition, control automatically returns


to the calling function after the last statement of the called function is executed. In this case,
the return value of the called function is undefined. If the function has a return type other
than void, it's a serious bug, and the compiler prints a warning diagnostic message. If the
function has a void return type, this behavior is okay, but may be considered poor style. Use
a plain return statement to make your intent clear.

As a good engineering practice, always specify a return type for your functions. If a
return value isn't required, declare the function to have void return type. If a return type
isn't specified, the C compiler assumes a default return type of int.

Many programmers use parentheses to enclose the expression argument of


the return statement. However, C doesn't require the parentheses.

The compiler may issue a warning diagnostic message about unreachable code if it finds
any statements placed after the return statement.

In a main function, the return statement and expression are optional. What happens
to the returned value, if one is specified, depends on the implementation. Microsoft-
specific: The Microsoft C implementation returns the expression value to the process that
invoked the program, such as cmd.exe. If no return expression is supplied, the Microsoft C
runtime returns a value that indicates success (0) or failure (a non-zero value).

Example

This example is one program in several parts. It demonstrates the return statement,
and how it's used both to end function execution, and optionally, to return a value.

CCopy

// C_return_statement.c
// Compile using: cl /W4 C_return_statement.c
#include <limits.h> // for INT_MAX
#include <stdio.h> // for printf

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

long long square( int value )


{
// Cast one operand to long long to force the
// expression to be evaluated as type long long.
// Note that parentheses around the return expression
// are allowed, but not required here.
return ( value * (long long) value );
}

The square function returns the square of its argument, in a wider type to prevent an
arithmetic error. Microsoft-specific: In the Microsoft C implementation, the long long type
is large enough to hold the product of two int values without overflow.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

UNIT IV

PYTHON
Python:

About python, features of python, python set up, fundamentals of python, values and data
types, variables, key word, identifier of python, quotations, indentation, multi line
statement, input-output and import function in python, advantages and disadvantages of
python.

ABOUT PYTHON
What is Python?

Python is a widely-used, interpreted, object-oriented, and high-level programming


language with dynamic semantics, used for general-purpose programming. It was created
by Guido van Rossum, and first released on February 20, 1991.

While you may know the python as a large snake, the name of the Python
programming language comes from an old BBC television comedy sketch series
called Monty Python’s Flying Circus.

One of the amazing features of Python is the fact that it is actually one person’s
work. Usually, new programming languages are developed and published by large
companies employing lots of professionals, and due to copyright rules, it is very hard to
name any of the people involved in the project. Python is an exception.

Of course, van Rossum did not develop and evolve all the Python components
himself. The speed with which Python has spread around the world is a result of the
continuous work of thousands (very often anonymous) programmers, testers, users (many
of them aren’t IT specialists) and enthusiasts, but it must be said that the very first idea
(the seed from which Python sprouted) came to one head – Guido’s.

Python isn’t a young language. It is mature and trustworthy. It’s not a one-hit
wonder. It’s a bright star in the programming firmament, and time spent learning Python is
a very good investment.

Python goals

In 1999, Guido van Rossum defined his goals for Python:


S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College

 an easy and intuitive language just as powerful as those of the major


competitors;
 open source, so anyone can contribute to its development;
 code that is as understandable as plain English;
 suitable for everyday tasks, allowing for short development times.

About 20 years later, it is clear that all these intentions have been fulfilled. Some sources
say that Python is the third-most popular programming language in the world, while others
claim it’s the fifth.

Why Python?

What makes Python so special? How does it happen that programmers, young and
old, experienced and novice, want to use it? How did it happen that large companies
adopted Python and implemented their flagship products using it?

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

There are many reasons – we’ve listed some of them already, but let’s enumerate them
again in a more practical manner:

 it’s easy to learn – the time needed to learn Python is shorter than for many
other languages; this means that it’s possible to start the actual programming faster;
 it’s easy to teach – the teaching workload is smaller than that needed by other
languages; this means that the teacher can put more emphasis on general (language-
independent) programming techniques, not wasting energy on exotic tricks, strange
exceptions and incomprehensible rules;

 it’s easy to use for writing new software – it’s often possible to write code faster
when using Python;

 it’s easy to understand – it’s also often easier to understand someone else’s code
faster if it is written in Python;

 it’s easy to obtain, install and deploy – Python is free, open and multiplatform; not all
languages can boast that.

Python in Action

Where can we see Python in action? We see it every day and almost everywhere.

It’s used extensively to implement complex Internet services like search engines,
cloud storage and tools, social media and so on. Whenever you use any of these
services, you are actually very close to Python, although you wouldn’t know it.

Many developing tools are implemented in Python.

More and more everyday use applications are being written in Python. Lots of
scientists have abandoned expensive proprietary tools and switched to Python.

Lots of IT project testers have started using Python to carry out repeatable test
procedures. The list is long.

Python Examples

Python is a great choice for:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

 Web and Internet development (e.g., Django and Pyramid frameworks, Flask and
Bottle micro-frameworks)
 Scientific and numeric computing (e.g., SciPy – a collection of packages for the
purposes of mathematics, science, and engineering; Ipython – an interactive shell
that features editing and recording of work sessions)
 Education (it’s a brilliant language for teaching programming!)
 Desktop GUIs (e.g., wxWidgets, Kivy, Qt)
 Software Development (build control, management, and testing – Scons, Buildbot,
Apache Gump, Roundup, Trac)
 Business applications (ERP and e-commerce systems – Odoo, Tryton)
 Games (e.g., Battlefield series, Sid Meier\’s Civilization IV…), websites and
services (e.g., Dropbox, UBER, Pinterest, BuzzFeed…)
 And that’s just the beginning…

FEATURES OF PYTHON
Python is a dynamic, high level, free open source and interpreted programming
language. It supports object-oriented programming as well as procedural oriented
programming.

In Python, we don’t need to declare the type of variable because it is a dynamically


typed language.
For example, x = 10
Here, x can be anything such as String, int, etc.

Features in Python

There are many features in Python, some of which are discussed below –

1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc. It is very easy to code in
python language and anybody can learn python basics in a few hours or days. It is also a
developer-friendly language.
2. Free and Open Source:
Python language is freely available at the official website and you can download it from the
given download link below click on the Download Python keyword.
Since it is open-source, this means that source code is also available to the public. So you
can download it as, use it as well as share it.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object-
oriented language and concepts of classes, objects encapsulation, etc.
4. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or
Tk in python.
PyQt5 is the most popular option for creating graphical apps with Python.
5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to
remember the system architecture, nor do we need to manage the memory.
6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++
language and also we can compile that code in C/C++ language.
7. Python is Portable language:
Python language is also a portable language. For example, if we have python code for
windows and if we want to run this code on other platforms such as Linux, Unix, and Mac
then we do not need to change it, we can run this code on any platform.
8. Python is Integrated language:
Python is also an Integrated language because we can easily integrated python with other
languages like c, c++, etc.
9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time.
like other languages C, C++, Java, etc. there is no need to compile python code this makes
it easier to debug our code. The source code of python is converted into an immediate
form called bytecode.
10. Large Standard Library
Python has a large standard library which provides a rich set of module and functions so
you do not have to write your own code for every single thing. There are many libraries
present in python for such as regular expressions, unit-testing, web browsers, etc.
11. Dynamically Typed Language:
Python is a dynamically-typed language. That means the type (for example- int, double,
long, etc.) for a variable is decided at run time not in advance because of this feature we
don’t need to specify the type of variable.

PYTHON SET UP

This page explains how to set up Python on a machine so you can run and edit
Python programs, and links to the exercise code to download. You can do this before
starting the class, or you can leave it until you've gotten far enough in the class that you
S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College

want to write some code. The Google Python Class uses a simple, standard Python
installation, although more complex strategies are possible. Python is free and open source,
available for all operating systems from python.org. In particular we want a Python install
where you can do two things:

 Run an existing python program, such as hello.py

 Run the Python interpreter interactively, so you can type code right at it

Both of the above are done quite a lot in the lecture videos, and it's definitely something
you need to be able to do to solve the exercises.

As a first step, download the google-python-exercises.zip file and unzip it someplace


where you can work on it. The resulting google-python-exercises directory contains many
different python code exercises you can work on. In particular, google-python-exercises
contains a simple hello.py file you can use in the next step to check that Python is working
on your machine. Below are instructions for Windows and other operating systems.

Python on Linux, Mac OS X, and other OS

Most operating systems other than Windows already have Python installed by
default. To check that Python is installed, open a command line (typically by running the
"Terminal" program), and cd to the google-python-exercises directory. Try the following to
run the hello.py program (what you type is shown in bold):

~/google-python-exercises$ python hello.py


Hello World
~/google-python-exercises$ python hello.py Alice
Hello Alice

If python is not installed, see the Python.org download page. To run the Python interpreter
interactively, just type python in the terminal:

~/google-python-exercises$ python
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 + 1
2
>>> you can type expressions here .. use ctrl-d to exit

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

For Google's Python Class, it's best to use Python 2.7. Although Python 3.x is becoming
more popular, this course is designed for Python 2.6 or later.

Execute Bit (optional)

The commands above are the simplest way to run python programs. If the "execute bit" is
set on a .py file, it can be run by name without having to type python first. Set the execute
bit with the chmod command like this:

~/google-python-exercises$ chmod +x hello.py


~/google-python-exercises$ ./hello.py ## now can run it as ./hello.py
Hello World

Python on Windows

To install Python on Windows, go to the python.org download page and download


Python 2.7.x. Run the Python installer and accept all the defaults. This will install Python in
the root directory and set up some file associations.
With Python installed, open a command prompt (Accessories > Command Prompt,
or type cmd into the run dialog). Cd to the google-python-exercises directory (from
unzipping google-python-exercises.zip). You should be able to run the hello.py python
program by typing python hello.py (what you type is shown in bold):
C:\google-python-exercises> python hello.py
Hello World
C:\google-python-exercises> python hello.py Alice
Hello Alice
To run the Python interpreter interactively, select the Run... command from the
Start menu, and type Python -- this will launch Python interactively in its own window. On
Windows, use Ctrl-Z to exit (on all other operating systems it's Ctrl-D to exit).
In the lecture videos, we generally run the Python programs with commands like ./hello.py.
On Windows, it's simplest to use the python hello.py form.

Editing Python (all operating systems)


A Python program is just a text file that you edit directly. As above, you should have
a command line open, where you can type python hello.py Alice to run whatever exercise
you are working on. At the command line prompt, just hit the up-arrow key to recall
previously typed commands, so it's easy to run previous commands without retyping them.
You want a text editor with a little understanding of code and indentation. There are many
good free ones:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Windows -- do not use Notepad or Wordpad. Try the free and open source Notepad++ or
the free and open source JEdit
Mac -- The built in TextEdit works, but not very well. Try the free BBEdit or the free and
open source JEdit
Linux -- any unix text editor is fine, or try the above JEdit.

Editor Settings
Following are some recommended settings for your text editor:
When you press Tab, it's best if your editor inserts spaces instead of a real tab
character. All of the tutorial files use 2-spaces as the indent, and 4-spaces is another
popular choice.
It's helpful if the editor will "auto indent" so when you press Enter, the new line
starts with the same indentation as the previous line.
When you save your files, use the unix line-ending convention, since that's how the
various starter files are set up. If running hello.py gives the error "Unknown option: -", the
file may have the wrong line-ending.
Here are the preferences to set for common editors to treat tabs and line-endings
correctly for Python:
Windows Notepad++ -- Tabs: Settings > Preferences > Edit Components > Tab
settings, and Settings > Preferences > MISC for auto-indent. Line endings: Format >
Convert, set to Unix.
JEdit (any OS) -- Line endings: Little 'U' 'W' 'M' on status bar, set it to 'U' (for Unix line-
endings).
Windows Notepad or Wordpad -- do not use.
Mac BBEdit -- Tabs: At the top, BBEdit > Preferences (or Cmd + , shortcut). Go to Editor
Defaults section and make sure Auto-indent and Auto-expand tabs are checked. Line
endings: In Preferences go to Text Files section and make sure Unix (LF) is selected under
Line breaks.
Mac TextEdit -- do not use.
Unix pico -- Tabs: Esc-q toggles tab mode, Esc-i to turns on auto-indent mode.
Unix emacs -- Tabs: manually set tabs-inserts-spaces mode: M-x set-variable(return)
indent-tabs-mode(return) nil.
Editing Check
To try out your editor, edit the hello.py program. Change the word "Hello" in the
code to the word "Howdy" (you don't need to understand all the other Python code in there
- we'll explain it all in class). Save your edits and run the program to see its new output. Try
adding a print 'yay!' just below the existing print and with the same indentation. Try
running the program, to see that your edits work correctly. For class we want an edit/run
workflow that allows you to switch between editing and running easily.
Quick Python Style

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

One of the advantages of Python is that it makes it easy to type a little code and
quickly see what it does. In class, we want a work setup that matches that: a text editor
working on the current file.py, and a separate command line window where you can just
press the up-arrow key to run file.py and see what it does.
Teaching philosophy aside: the interpreter is great for little experiments, as shown
throughout the lectures. However, the exercises are structured as Python files that students
edit. Since being able to write Python programs is the ultimate goal, it's best to be in that
mode the whole time and use the interpreter just for little experiments.

FUNDAMENTALS OF PYTHON
Fundamentals of Python consists of a discussion of basic building blocks of the
Python programming language. Here, “Fundamentals of Python” is divided into the
following categories. And we will be discussing each topic separately.
Watch this Video on Python Course

 Statements
o Expressions
o Assignment Statements
 Indentations
 Comments
o Single-line comments
o Multi-line comment
o doc-staring comments
 Variables
 Constants
 Tokens
o Identifiers
o Keywords
o Literals
o Operators

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

First and foremost, we will be discussing statements in Python.


Statements
Python statements are nothing but logical instructions that interpreters can read and
execute. It can be both single and multiline.
There are two categories of statements in Python:

 Expression Statements
 Assignment Statements

Expression Statement:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

With the help of expressions, we perform operations like addition, subtraction,


concentration etc.
In other words, it is a statement that returns a value.
it is an expression if it appears-

 On the right side of an assignment,


 As a parameter to a method call.

Note: An expression must have a return.


Example:

 Using simple arithmetic expression:

(1+5) * 3
18

 Using a function in an expression:

pow (3,2)
9

Assignment Statements

With the help of assignment statements, we create new variables, assign values and also
change values.
Structure of an assignment statement syntax:

#LHS <=> RHS


variable = expression

We can categorize Assignment statements into three primary categories based on what’s
on the Right-Hand Side of the statement.

 Value-Based Expression on RHS


 Current Variable on RHS
 Operation on RHS

Value-Based Expression on the RHS:


In this case, Python allocates a new memory location to the newly assigned variable.
Let us take an example of this category.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

 First, let’s create a string and assign it to a variable “test”,


 Then, we will check the memory location id python has assigned for the variable

test= "Hello World"


id(test)

Note:
Look at the example shown below:
test1="Hello" id(test1) output:
2524751071304
test2="Hello" id(test2) output:
2524751071304

As you might have noticed that we have assigned the same string to two different variables.
But python allocated the same memory location for both the variables. That is because:
Python allocates the same memory location for the two cases mentioned below:

 If the strings with less than 20 characters that don’t have white spaces and
 Integers ranging between (-5 to +255).

This concept used by Python to save memory is also called Interning.


Current Python variable on RHS:

In this case, Python doesn’t allocate a new memory location.


Let’s understand that with the help of an example:
current_var= "It's HumbleGumble" print(id(current_var))
new_var= current_var print(id(new_var)) 24751106240
2524751106240

As you can see we have the same location id allotted for the two variables.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Operation on RHS:

In this category, we have an operation on the right side of the statement, which is the
defining factor of the type of our statement.
Let’s understand that with the help of an example:
test= 7 * 2 type(test) int
test1= 7 * 2 / 10 type(test1) output:
float

Multiline statements
There are two ways to define multiline statements.

 Implicit Method
 Explicit Method

The end of a statement in python is considered as a newline character, to extend the


statements over multiple lines we can use two methods.

 Implicit: By using parenthesis like (), {} or [].

e.g.
a = (0 + 1 + 2 +
3 + 4 + 5)

 Explicit: By using continuation character “\”.

a=0+1+2+\
3+4+5

Indentation
Unlike most programming languages python uses indentation to mark a block of code.
According to python style guidelines or PEP8, you should keep an indent size of four.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Most of the programming languages provide indentation for better code formatting and
don’t enforce to have it. But in Python it is mandatory. This is why indentation is so crucial
in Python.
Comments
Comments are nothing but tagged lines of in codes which increases the readability of the
code and make the code self-explanatory. Comments can be of two categories:
Single-line comments:

With the help of one ‘#’, we begin a single-line comment


Example:
test= 7 * 2 type(test)
#Single-line comment

Multi-line comments:

With the help of ‘‘‘… ’’,’ we write multiline comments in python.


Example:
test1= 7 * 2 / 10 type(test1)
'''
line one line two line three '''

Docstring comments:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Python has the documentation strings (or docstrings) feature. It gives programmers an
easy way of adding quick notes with every Python module, function, class, and method.
The strings defined using the triple-quotation mark are multiline comments. However, if
such a string is placed immediately after a function or class definition or on top of a
module, then they turn into docstrings.
Example:
def SayFunction(): '''
Strings written using '''_''' after a function represents docstring of func Python docstrings are not comments
'''
print("just a docstring")
print("Let us see how to print the docstring value") print(theFunction. doc )

Variables:
A variable is a memory address that can change and when a memory address cannot
change then it is known as constant. Variable is the name of the memory location where
data is stored. Once a variable is stored then space is allocated in memory. It defines a
variable using a combination of numbers, letters, and the underscore character.
Assigning Values to Variables

There is no need for an explicit declaration to reserve memory. The assignment is done
using the equal (=) operator. Some examples of legal python variables are –
i=1
j=2

Multiple Variable Assignment:

You can assign a single value to the multiple variables as follows –


a=2
Also, we can assign multiple values to the multiple variables as follows –
a, b, c = 2, 25, ‘abc’

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Note: Python is a type inferred language i.e. it automatically detects the type of assigned
variable.
For instance,
test=1 type(test) output:
int test1="String" type(test1) output:
str

Constants:
Constant is a type of variable that holds values, whose value cannot be changed. In reality,
we rarely use constants in python.
Assigning a value to a constant in Python

 Constants are usually declared and assigned on a different module/file.

#Declare constants in a separate file called constant.py PI = 3.14


GRAVITY = 9.8

 Then import it to the main file.

#inside main.py we import the constants import constant


print(constant.PI)
print(constant.GRAVITY)

Token
Tokens are the smallest unit of the program. There are the following tokens in Python:

 Reserved words or Keywords


 Identifiers
 Literals
 Operators

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Keywords:

Keywords are nothing but a set of special words, which are reserved by python and have
specific meanings. Remember that we are not allowed to use keywords as variables in
python.
Keywords in python are case sensitive.
We’ve just captured here a snapshot of the possible Python keywords.
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or continue global pass
Identifiers

Identifiers in python are nothing but user-defined names to represent programmable


entities like variables, functions, classes, modules or any other objects.
But there are a few rules that we need to follow while defining an identifier. They are:

 You can use a sequence of letters (lowercase (a to z) or uppercase (A to Z)). You can
also mix up digits (0 to 9) or an underscore (_) while defining an identifier.
 You can’t use digits to begin an identifier name.
 You should not use Reserved Keywords to define an identifier.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

 Other than underscore (_) you are not allowed to use any other special characters.
 Even though python doc says that you can name an identifier with unlimited length.
But it is not entirely true.

Using a large name (more than 79 chars) would lead to the violation of a rule set by the
PEP-8 standard. It says.
Literals:

The other built-in objects in python are Literals. Literals can be defined as data that is given
in a variable or constant. Python has the following literals:

String Literals:
A string literal is a sequence of characters surrounded by quotes. We can use both single,
double or triple quotes for a string. And, a character literal is a single character surrounded
by single or double-quotes.

Numeric Literals:
Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different
numerical types Integer, Float, and Complex.

Boolean Literals:
A Boolean literal can have any of the two values: True or False.

Collection literals:
There are four different literal collections List literals, Tuple literals, Dict literals, and Set
literals.

Special literals:
Python contains one special literal i.e. None. We use it to specify that field that is not
created.
Operators:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Operators are the symbols that perform the operation on some values. These values are
known as operands.
In Python, operators are categorized into the following categories:

 Arithmetic Operators
 Relational Operators
 Assignment Operators
 Logical Operators
 Membership Operators
 Identity Operators
 Bitwise Operators

Arithmetic Operators
Arithmetic Operator Description Example
Operators Name

+ Addition Perform Addition I=40,


J=20
>>>I+ J
>>>60

– Subtraction Perform Subtraction I=40,


J=20
>>>I – J
>>>20

* Multiplication Perform Multiplication I=40,


J=20
>>>I * J
>>> 800

/ Division Perform Division I=30,


J=20
>>>I /J
>>> 2.5

% Modulus Return the remainder I=40,


after Division J=20
>>>I /J
>>> 0

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

** Exponent Performs exponential I=4, J=20


(power) calculation >>>I /J
>>> 204

// Floor Division Perform division I=30,


remove the decimal J=20
value and return >>>I//J
Quotient value >>> 1

Relational Operators
It is also known as the comparison operator because it compares the values. After
comparison, it returns the Boolean value i.e. either true or false.
Operator Operator Name Description Example

== Equal to If the values of two operands are equal, then I = 20, J = 20


then it returns true. (I == J)
is True

!= Not Equal to If the values of two operands are not equal, I = 20, J = 20
then it returns true. (I == J)
is False

< Less than If the value of the left operand is less than the I = 40, J = 20
value of the right operand, then it returns true (I < J)
is False

> Greater than If the value of the left operand is greater than I= 40, J = 20
the value of the right operand, then it returns (I > J)
true is True

<= Less than or equal If the value of the left operand is less than or I = 40, J = 20
to equal to the value of the right operand, then it (I <= J)
returns true is False

>= Greater than or If the value of the left operand is greater than I = 40, J = 20
equal to or equal to the value of the right operand, (I >= J)
then it returns true. is True

<> Not equal to If the values of two operands are not equal, I=40, J = 20
(similar to !=) then the condition becomes true (I <> J)

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

is True.

Assignment Operators
Operator Operator Name Description Example

= Assignment It assigns a value from right side I = 40


operand to left side operand It assigns 40 to I

+= Add then assign It performs addition and then I+=J


results is assigned to the left-hand that means I = I
operand +J

-= Subtract then assign It performs subtraction and then I-=J


results is assigned to the left-hand that means I = I –
operand J

*= Multiply the assign It performs multiplication and then I*=J


the results are assigned to the left- that means I = I *
hand operand. J

/= Divide then assign It performs division and then results I/=J


is assigned to the left-hand operand that means I = I /
J

%= Modulus then assign It performs modulus and then I%=J


results is assigned to the left-hand that means I = I
operand %J

**= Exponent then assign It performs exponent and then I**=J


results is assigned to the left-hand that means I = I
operand ** J

//= The floor division then It performs floor division and then I//=J
assign results is assigned to the left-hand that means I = I
operand // J

Logical Operators
Operator Operator Name Description Example

and Logical AND When Both side condition is true the result is 2<1 and 2<3

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

true otherwise false False

or Logical OR When at least one condition is true then the 2<1 or 2<3
result is true otherwise false True

not Logical NOT Reverse the condition Not (5>4)


False

Membership Operators
Operator Description Example

in It returns true if it finds a variable in the sequence List = [1,2,3,4,5,6,7,8]


otherwise returns false i=1
if i in List:
print(‘i is available in list’)
else:
print(‘i is not available in list’)
Output – i is available in list
not in It returns true if it does not find a variable in the List = [1,2,3,4,5,6,7,8]
sequence otherwise returns false j=10
if j not in List:
print (‘j is not available in list’)
else:
print (‘j is available in list’)
Output – j is not available in list
Bitwise Operators
It performs bit by bit operation.
Suppose there are two variables,
I = 10 and
J = 20
and their binary values are:
I = 10 = 0000 1010
J = 20 = 0001 0100
now let us see how bitwise operators perform.
Operator Operator Name Description Example

& Binary AND If both bits are 1 then 1 otherwise I & J


0 0000 0000

| Binary OR If one of the bits is 1 then 1 I | J

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

otherwise 0 0001 1110

^ Binary XOR If both bits are same, then 0 I ^ J


otherwise 1 0001 1110

~ Binary If bit is 1 the make it 0 and if bit is ~I


Complement 0 the make it 1 1111 0101

<< Binary Left Shift The left operand is moved left by I << 2
the number of bits specified by 240 i.e. 1111
the right operand. 0000

>> Binary Right Shift The left operand is moved right I >> 2
by the number of bits specified by 15 i.e. 1111
the right operand.

Identity Operators
These operators are used to compare the memory address of two objects.
Operator Description Example

is It returns true if both I = 20


operand‘s identity is same J = 20
otherwise false if(I is J):
print (‘I and J have the same
identity)
else:
print (‘I and J have not same
identity’)
Output – I and J have same
identity
is not It returns true if both I = 20
operand‘s identity is not the J = 230
same otherwise false if(I is not J):
print (‘I and J have not same
identity’)
else:
print (‘I and J have the same
identity)
Output – I and J have not same
identity

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

VALUES AND DATA TYPES


Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data. Since
everything is an object in Python programming, data types are actually classes and
variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value
can be integer, floating number or even complex numbers. These values are defined
as int, float and complex class in Python.
Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer
value can be.
Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed
by a positive or negative integer may be appended to specify scientific notation.
Complex Numbers – Complex number is represented by complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.

# Python program to
# demonstrate numeric value

a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Output:
Type of a: <class 'int'>

Type of b: <class 'float'>

Type of c: <class 'complex'>


Sequence Type
In Python, sequence is the ordered collection of similar or different data types. Sequences
allows to store multiple values in an organized and efficient fashion. There are several
sequence types in Python –
String
List
Tuple
1) String
In Python, Strings are arrays of bytes representing Unicode characters. A string is a
collection of one or more characters put in a single quote, double-quote or triple quote. In
python there is no character data type, a character is a string of length one. It is
represented by str class.

Creating String
Strings in Python can be created using single quotes or double quotes or even triple
quotes.

# Python Program for


# Creation of String

# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

print(type(String1))

# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))

# Creating String with triple


# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

Output:
String with the use of Single Quotes:
Welcome to the Geeks World

String with the use of Double Quotes:


I'm a Geek
<class 'str'>

String with the use of Triple Quotes:


I'm a Geek and I live in a world of "Geeks"
<class 'str'>

Creating a multiline String:


Geeks
For
Life

Accessing elements of String


In Python, individual characters of a String can be accessed by using the method of
Indexing. Indexing allows negative address references to access characters from the back
of the String, e.g. -1 refers to the last character, -2 refers to the second last character and
so on.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

# Python Program to Access


# characters of String

String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing First character print("\


nFirst character of String is: ")
print(String1[0])

# Printing Last character print("\


nLast character of String is: ")
print(String1[-1])

Output:
Initial String:
GeeksForGeeks

First character of String is:


G

Last character of String is:


s

Note – To know more about strings, refer Python String.


2) List
Lists are just like the arrays, declared in other languages which is a ordered collection of
data. It is very flexible as the items in a list do not need to be of the same type.

Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].
Python3

# Python program to demonstrate


# Creation of List

# Creating a List

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

List = []
print("Initial blank List: ")
print(List)

# Creating a List with


# the use of a String
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List


# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)

Output:
Initial blank List:
[]

List with the use of String:


['GeeksForGeeks']

List containing multiple values:


Geeks
Geeks

Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]

Accessing elements of List

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

In order to access the list items refer to the index number. Use the index operator [ ] to
access an item in a list. In Python, negative sequence indexes represent positions from the
end of the array. Instead of having to compute the offset as in List[len(List)-3], it is
enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers
to the last item, -2 refers to the second-last item, etc.

# Python program to demonstrate


# accessing of element from list

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]

# accessing a element from the


# list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])

# accessing a element using


# negative indexing
print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of


list print(List[-3])

Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Note – To know more about Lists, refer Python List.

3) Tuple

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Just like list, tuple is also an ordered collection of Python objects. The only difference
between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it
is created. It is represented by tuple class.

Creating Tuple
In Python, tuples are created by placing a sequence of values separated by ‘comma’
with or without the use of parentheses for grouping of the data sequence. Tuples can
contain any number of elements and of any datatype (like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one
element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a
tuple.

# Python program to demonstrate


# creation of Set

# Creating an empty tuple


Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)

# Creating a Tuple with


# the use of Strings
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple with the


# use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

# Creating a Tuple

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

# with nested tuples


Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

Output:
Initial empty Tuple:
()

Tuple with the use of String:


('Geeks', 'For')

Tuple using List:


(1, 2, 4, 5, 6)

Tuple with the use of function:


('G', 'e', 'e', 'k', 's')

Tuple with nested tuples:


((0, 1, 2, 3), ('python', 'geek'))

Note – Creation of Python tuple without the use of parentheses is known as Tuple
Packing.
Accessing elements of Tuple
In order to access the tuple items refer to the index number. Use the index
operator [ ] to access an item in a tuple. The index must be an integer. Nested tuples are
accessed using nested indexing.

# Python program to
# demonstrate accessing tuple

tuple1 = tuple([1, 2, 3, 4, 5])

# Accessing element using indexing


print("First element of tuple")
print(tuple1[0])

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

# Accessing element from last


# negative indexing
print("\nLast element of
tuple") print(tuple1[-1])

print("\nThird last element of


tuple") print(tuple1[-3])

Output:
First element of tuple
1

Last element of tuple


5

Third last element of tuple


3
Note – To know more about tuples, refer Python Tuples.
Boolean
Data type with one of the two built-in values, True or False. Boolean objects that
are equal to True are truthy (true), and those equal to False are falsy (false). But non-
Boolean objects can be evaluated in Boolean context as well and determined to be true or
false. It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will
throw an error.

# Python program to
# demonstrate boolean type

print(type(True))
print(type(False))

print(type(true))

Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

NameError: name 'true' is not defined

Set
In Python, Set is an unordered collection of data type that is iterable, mutable and
has no duplicate elements. The order of elements in a set is undefined though it may
consist of various elements.
Creating Sets
Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by ‘comma’. Type of
elements in a set need not be the same, various mixed-up data type values can also be
passed to the set.

# Python program to demonstrate


# Creation of Set in Python

# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)

# Creating a Set with


# the use of a String
set1 = set("GeeksForGeeks") print("\
nSet with the use of String: ")
print(set1)

# Creating a Set with


# the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with


# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed
Values") print(set1)

Output:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Initial blank Set:


set()

Set with the use of String:


{'F', 'o', 'G', 's', 'r', 'k', 'e'}

Set with the use of List:


{'Geeks', 'For'}

Set with the use of Mixed Values


{1, 2, 4, 6, 'Geeks', 'For'}

Accessing elements of Sets


Set items cannot be accessed by referring to an index, since sets are unordered the
items has no index. But you can loop through the set items using a for loop, or ask if a
specified value is present in a set, by using the in keyword.

# Python program to demonstrate


# Accessing of elements in a set

# Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)

# Accessing element using


# for loop print("\
nElements of set: ") for i in
set1:
print(i, end =" ")

# Checking the element


# using in keyword
print("Geeks" in set1)

Output:
Initial set:
{'Geeks', 'For'}

Elements of set:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Geeks For

True

Note – To know more about sets, refer Python Sets.


Dictionary
Dictionary in Python is an unordered collection of data values, used to store data
values like a map, which unlike other Data Types that hold only single value as an
element, Dictionary holds key:value pair. Key-value is provided in 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’.
Creating Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Values in a dictionary can be of any datatype and
can be duplicated, whereas keys can’t be repeated and must be immutable. Dictionary can
also be created by the built-in function dict(). An empty dictionary can be created by
just placing it to curly braces{}.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be
treated distinctly.

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\
nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("\
nDictionary with the use of Mixed Keys: ")
print(Dict)

# Creating a Dictionary
# with dict() method

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})


print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')]) print("\
nDictionary with each item as a pair: ")
print(Dict)

Output:
Empty Dictionary:
{}

Dictionary with the use of Integer Keys:


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:


{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Dictionary with the use of dict():


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair:


{1: 'Geeks', 2: 'For'}

Accessing elements of Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used
inside square brackets. There is also a method called get() that will also help in accessing
the element from a dictionary.

# Python program to demonstrate


# accessing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print("Accessing a element using key:")

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

print(Dict['name'])

# accessing a element using get()


# method
print("Accessing a element using get:")
print(Dict.get(3))

Output:
Accessing a element using key:
For
Accessing a element using get:

VARIABLES

Python is not “statically typed”. We do not need to declare variables before using
them or declare their type. A variable is created the moment we first assign a value to it. A
variable is a name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
Rules for creating variables in Python:
A variable name must start with a letter or the underscore character.
A variable name cannot start with a number.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ ).
Variable names are case-sensitive (name, Name and NAME are three different variables).
The reserved words(keywords) cannot be used naming the variable.
Let’s see the simple variable creation:

#!/usr / bin / python

# An integer assignment
age = 45

# A floating point
salary = 1456.8

# A string

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

name = "John"

print(age)
print(salary)
print(name)

Output:
45
1456.8
John
Declare the Variable:
Let’s see how to declare the variable and print the variable.

# declaring the var


Number = 100

# display
print( Number)

Output:
100
Re-declare the Variable:
We can re-declare the python variable once we have declared the variable already.

# declaring the var


Number = 100

# display
print("Before declare: ", Number)

# re-declare the var


Number = 120.3

print("After re-declare:", Number)

Output:
Before declare: 100
After re-declare: 120.3
Assigning a single value to multiple variables:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Also, Python allows assigning a single value to several variables simultaneously with “=”
operators.
For example:

#!/usr / bin / python

a = b = c = 10

print(a)
print(b)
print(c)

Output:
10
10
10
Assigning different values to multiple variables:
Python allows adding different values in a single line with “,”operators.

#!/usr / bin / python

a, b, c = 1, 20.2, "GeeksforGeeks"

print(a)
print(b)
print(c)

Output:
1
20.2
GeeksforGeeks
Can we use the same name for different types?
If we use the same name, the variable starts referring to a new value and type.

#!/usr / bin / python

a = 10
a = "GeeksforGeeks"

print(a)

Output:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

GeeksforGeeks
How does + operator work with variables?

#!/usr / bin / python

a = 10
b = 20
print(a+b)

a = "Geeksfor"
b = "Geeks"
print(a+b)

Output
30
GeeksforGeeks
Can we use + for different types also?
No using for different types would produce error.

#!/usr / bin / python

a = 10
b = "Geeks"
print(a+b)

Output :
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Global and Local Variables in Python:
Local variables are the ones that are defined and declared inside a function. We can not
call this variable outside the function.

# This function uses global variable s


def f():
s = "Welcome geeks"
print(s)

f()

Output:
Welcome geeks

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Global variables are the ones that are defined and declared outside a function, and we
need to use them inside a function.

# This function has a variable with


# name same as s.
def f():
print(s)

# Global scope
s = "I love Geeksforgeeks"
f()

Output:
I love Geeksforgeeks
Global keyword in Python:
Global keyword is a keyword that allows a user to modify a variable outside of the
current scope. It is used to create global variables from a non-global scope i.e inside a
function. Global keyword is used inside a function only when we want to do assignments
or when we want to change a variable. Global is not needed for printing and accessing.
Rules of global keyword:
If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a
local unless explicitly declared as global.
Variables that are only referenced inside a function are implicitly global.
We Use global keyword to use a global variable inside a function.
There is no need to use global keyword outside a function.
Example:

# Python program to modify a global


# value inside a function

x = 15

def change():

# using a global keyword


global x

# increment value of a by 5

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

x=x+5
print("Value of x inside a function :", x)

change()
print("Value of x outside a function :", x)

Output:
Value of x inside a function : 20
Value of x outside a function : 20

Variable type in Python:


Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data. Since
everything is an object in Python programming, data types are actually classes and
variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary
Example:

# numberic
var = 123
print("Numbric data : ", var)

# Sequence Type
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Boolean
print(type(True))
print(type(False))

# Creating a Set with


# the use of a String

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

set1 = set("GeeksForGeeks") print("\


nSet with the use of String: ")
print(set1)

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\
nDictionary with the use of Integer Keys: ")
print(Dict)

Output:
Numbric data : 123
String with the use of Single Quotes:
Welcome to the Geeks World
<class 'bool'>
<class 'bool'>

Set with the use of String:


{'r', 'G', 'e', 'k', 'o', 's', 'F'}

Dictionary with the use of Integer Keys:


{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Object References:
Let, we assign a variable x to value 5, and another variable y to the variable x.

x=5
y=x

When Python looks at the first statement, what it does is that, first, it creates an
object to represent the value 5. Then, it creates the variable x if it doesn’t exist and made
it a reference to this new object 5. The second line causes Python to create the variable y,
and it is not assigned with x, rather it is made to reference that object that x does. The net
effect is that the variables x and y wind up referencing the same object. This situation,
with multiple names referencing the same object, is called a Shared Reference in Python.
Now, if we write:

x = 'Geeks'

This statement makes a new object to represent ‘Geeks’ and makes x to reference this
new object.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Creating objects (or variables of a class type):


Please refer Class, Object and Members for more details.

# Python program to show that the variables with a value


# assigned in class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.

# Class for Computer Science Student


class CSStudent:

# Class Variable
stream = 'cse'

# The init method or constructor


def init (self, roll):

# Instance Variable
self.roll = roll

# Objects of CSStudent class


a = CSStudent(101)
b = CSStudent(102)

print(a.stream) # prints "cse"


print(b.stream) # prints "cse"
print(a.roll) # prints 101

# Class variables can be accessed using class


# name also
print(CSStudent.stream) # prints "cse"

Output
cse
cse
101
cse

KEY WORD

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Python Keywords are special reserved words that convey a special meaning to the
compiler/interpreter. Each keyword has a special meaning and a specific operation. These
keywords can't be used as a variable. Following is the List of Python Keywords.
True False None and as

asset def class continue break

else finally elif del except

global for if from import

raise try or return pass

nonlocal in not is lambda


Consider the following explanation of keywords.
True - It represents the Boolean true, if the given condition is true, then it returns "True".
Non-zero values are treated as true.
False - It represents the Boolean false; if the given condition is false, then it returns "False".
Zero value is treated as false
None - It denotes the null value or void. An empty list or Zero can't be treated as None.
and - It is a logical operator. It is used to check the multiple conditions. It returns true if
both conditions are true. Consider the following truth table.

A B A and B

True True True

True False False

False True False

False False False


5. or - It is a logical operator in Python. It returns true if one of the conditions is true.
Consider the following truth table.

A B A and B

True True True

True False True

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

False True True

False False False


6. not - It is a logical operator and inverts the truth value. Consider the following truth
table.

A Not A

True False

False True
7. assert - This keyword is used as the debugging tool in Python. It checks the correctness
of the code. It raises an AssertionError if found any error in the code and also prints the
message with an error.
Example:
a = 10
b=0
print('a is dividing by Zero')
assert b != 0
print(a / b)
Output:
a is dividing by Zero
Runtime Exception:
Traceback (most recent call last):
File "/home/40545678b342ce3b70beb1224bed345f.py", line 4, in
assert b != 0, "Divide by 0 error"
AssertionError: Divide by 0 error
8. def - This keyword is used to declare the function in Python. If followed by the function
name.
def my_func(a,b):
c = a+b
print(c)
my_func(10,20)
Output:
30
9. class - It is used to represents the class in Python. The class is the blueprint of the objects.
It is the collection of the variable and methods. Consider the following class.
class Myclass:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

#Variables……..
def function_name(self):
#statements………
10. continue - It is used to stop the execution of the current iteration. Consider the
following example.
a=0
while a < 4:
a += 1
if a == 2:
continue
print(a)
Output:
1
3
4
11. break - It is used to terminate the loop execution and control transfer to the end of the
loop. Consider the following example.
Example
for i in range(5):
if(i==3):
break
print(i)
print("End of execution")
Output:
0
1
2
End of execution
12. If - It is used to represent the conditional statement. The execution of a particular block
is decided by if statement. Consider the following example.
Example
i = 18
if (1 < 12):
print("I am less than 18")
Output:
I am less than 18
13. else - The else statement is used with the if statement. When if statement returns false,
then else block is executed. Consider the following example.
Example:
n = 11

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

if(n%2 == 0):
print("Even")
else:
print("odd")
Output:
Odd
14. elif - This Keyword is used to check the multiple conditions. It is short for else-if. If the
previous condition is false, then check until the true condition is found. Condition the
following example.
Example:
marks = int(input("Enter the marks:"))
if(marks>=90):
print("Excellent")
elif(marks<90 and marks>=75):
print("Very Good")
elif(marks<75 and marks>=60):
print("Good")
else:
print("Average")
Output:
Enter the marks:85
Very Good
15. del - It is used to delete the reference of the object. Consider the following
example. Example:
a=10
b=12
del a
print(b)
# a is no longer exist
print(a)
Output:
12
NameError: name 'a' is not defined
16. try, except - The try-except is used to handle the exceptions. The exceptions are run-
time errors. Consider the following example.
Example:
a=0
try:
b = 1/a
except Exception as e:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

print(e)
Output:
division by zero
17. raise - The raise keyword is used to through the exception forcefully. Consider the
following example.
Example
a=5
if (a>2):
raise Exception('a should not exceed 2 ')
Output:
Exception: a should not exceed 2
18. finally - The finally keyword is used to create a block of code that will always be
executed no matter the else block raises an error or not. Consider the following example.
Example:
a=0
b=5
try:
c = b/a
print(c)
except Exception as e:
print(e)
finally:
print('Finally always executed')
Output:
division by zero
Finally always executed
19. for, while - Both keywords are used for iteration. The for keyword is used to iterate
over the sequences (list, tuple, dictionary, string). A while loop is executed until the
condition returns false. Consider the following example.
Example: For loop
list = [1,2,3,4,5]
for i in list:
print(i)
Output:
1
2
3
4
5
Example: While loop

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

a=0
while(a<5):
print(a)
a = a+1
Output:
0
1
2
3
4
20. import - The import keyword is used to import modules in the current Python script.
The module contains a runnable Python code.
Example:
import math
print(math.sqrt(25))
Output:
5
21. from - This keyword is used to import the specific function or attributes in the current
Python script.
Example:
from math import sqrt
print(sqrt(25))
Output:
5
22. as - It is used to create a name alias. It provides the user-define name while importing a
module.
Example:
import calendar as cal
print(cal.month_name[5])
Output:
May
23. pass - The pass keyword is used to execute nothing or create a placeholder for future
code. If we declare an empty class or function, it will through an error, so we use the pass
keyword to declare an empty class or function.
Example:
class my_class:
pass

def my_func():
pass

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

24. return - The return keyword is used to return the result value or none to called
function.
Example:
def sum(a,b):
c = a+b
return c

print("The sum is:",sum(25,15))


Output:
The sum is: 40
25. is - This keyword is used to check if the two-variable refers to the same object. It
returns the true if they refer to the same object otherwise false. Consider the following
example.
Example
x=5
y=5

a = []
b = []
print(x is y)
print(a is b)
Output:
True
False
26. global - The global keyword is used to create a global variable inside the function. Any
function can access the global. Consider the following example.
Example
def my_func():
global a
a = 10
b = 20
c = a+b
print(c)

my_func()

def func():
print(a)

func()

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Output:
30
10
27. nonlocal - The nonlocal is similar to the global and used to work with a variable inside
the nested function(function inside a function). Consider the following example.
Example
def outside_function():
a = 20
def inside_function():
nonlocal a
a = 30
print("Inner function: ",a)
inside_function()
print("Outer function: ",a)
outside_function()
Output:
Inner function: 30
Outer function: 30
28. lambda - The lambda keyword is used to create the anonymous function in Python. It is
an inline function without a name. Consider the following example.
Example
a = lambda x: x**2
for i in range(1,6):
print(a(i))
Output:
1
4
9
16
25
29. yield - The yield keyword is used with the Python generator. It stops the function's
execution and returns value to the caller. Consider the following example.
Example
def fun_Generator():
yield 1
yield 2
yield 3

# Driver code to check above generator function


for value in fun_Generator():

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

print(value)
Output:
1
2
3
30. with - The with keyword is used in the exception handling. It makes code cleaner and
more readable. The advantage of using with, we don't need to call close(). Consider the
following example.
Example
with open('file_path', 'w') as file:
file.write('hello world !')
31. None - The None keyword is used to define the null value. It is remembered
that None does not indicate 0, false, or any empty data-types. It is an object of its data type,
which is Consider the following example.
Example:
def return_none():
a = 10
b = 20
c=a+b

x = return_none()
print(x)
Output:
None
We have covered all Python keywords. This is the brief introduction of Python Keywords.
Keyword Description

and A logical operator

as To create an alias

assert For debugging

break To break out of a loop

class To define a class

continue To continue to the next iteration of a loop

def To define a function

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

del To delete an object

elif Used in conditional statements, same as else if

else Used in conditional statements

except Used with exceptions, what to do when an exception occurs

False Boolean value, result of comparison operations

finally Used with exceptions, a block of code that will be executed no


matter if there is an exception or not

for To create a for loop

from To import specific parts of a module

global To declare a global variable

if To make a conditional statement

import To import a module

in To check if a value is present in a list, tuple, etc.

is To test if two variables are equal

lambda To create an anonymous function

None Represents a null value

nonlocal To declare a non-local variable

not A logical operator

or A logical operator

pass A null statement, a statement that will do nothing

raise To raise an exception

return To exit a function and return a value

True Boolean value, result of comparison operations

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

try To make a try...except statement

while To create a while loop

with Used to simplify exception handling

yield To end a function, returns a generator

IDENTIFIER OF PYTHON

In this TechVidvan’s Python article, we are going to learn about identifiers in


Python. They are the basic building blocks of Python and we use them everywhere
while writing programs. So, it’s important to understand everything about them.
We will see the rules to define identifiers, and all the best practices to follow while defining
Python identifiers. Let’s start with the definition of identifiers.
What is Python Identifier?
“An identifier is a name given to an entity”.
In very simple words, an identifier is a user-defined name to represent the basic building
blocks of Python. It can be a variable, a function, a class, a module, or any other object.
Naming Rules for Identifiers
Now you know what exactly identifiers are. So, how do we use them? We can’t use
anything, there are some certain rules to keep in mind that we must follow while naming
identifiers.

1. The Python identifier is made with a combination of lowercase or uppercase letters, digit
s or an underscore.

These are the valid characters.


Lowercase letters (a to z)
Uppercase letters (A to Z)
Digits (0 to 9)
Underscore (_)
Examples of a valid identifier:
num1
FLAG
get_user_name
userDetails
_1234

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

2. An identifier cannot start with a digit. If we create an identifier that starts with a digit
then we will get a syntax error.

We also cannot use special symbols in the identifiers name


Symbols like ( !, @, #, $, %, . ) are invalid.

A keyword cannot be used as an identifier. In Python, keywords are the reserved


names that are built-in in Python. They have a special meaning and we cannot use them as
identifier names.

If you want to see the list of all the keywords, then in your Python shell, type “help()” and
then type “keywords” to get the list of all Python keywords.

5. The length of the identifiers can be as long as you want. Of course, it can not be greater
than the available memory, however, the PEP-8 standards rule suggests not to
exceed 79 characters in a line.
Testing the Validity of Python Identifiers
Python has some helper functions that are useful when you are not sure whether a string is
a keyword or a valid identifier.

1.) To check whether a string is a keyword or not, we have a keyword module.

import keyword
print( keyword.iskeyword(“var”) )
print( keyword.iskeyword(“False”) )
print( keyword.iskeyword(“continue”) )
print( keyword.iskeyword(“count”) )
Output:
False
True
True
False
2. The str.isidentifier() function is used to check the validity of an
identifier. print( “name”.isidentifier() )
print( “#today”.isidentifier() )
print( “_12hello”.isidentifier() )
print( “8cellos”.isidentifier() )
Output:
True
False

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

True
False
Best Practices for Python Identifiers
Following the naming conventions are mandatory for everyone. But that’s not it!
The Python community has made a few more guidelines that are not compulsory but it
is advised to follow some practices that are better for everyone in understanding things.
Let’s see what these guidelines are.
1. Class names should start with a capital letter and all the other identifiers should start
with a lowercase letter.
2. Begin private identifiers with an underscore (_). Note, this is not needed to make
the variable private. It is only for the ease of the programmer to easily distinguish
between private variables and public variables.
3. Use double underscores ( ) around the names of magic methods and don’t use them
anywhere else. Python built-in magic methods already use this notation. For
example: init , len .
4. Double underscores are used only when you are dealing with mangling in Python.
5. Always prefer using names longer than one character. index=1 is better than i=1
6. To combine words in an identifier, you should use underscore(_). For
example: get_user_details.
7. Use camel case for naming the variables. For example: fullName, getAddress,
testModeOn, etc.

Reserved Classes of Python Identifiers


Some classes in Python have special meanings and to identify them, we use patterns of
leading and trailing underscores.
1. Single leading underscore (_*)
This identifier is used to store the result of the last evaluation in the interactive interpreter.
These results are stored in the builtin module. These are private variables and they
are not imported by “from module import *”
2. Double leading and trailing underscores (__*__)
Only the system-defined names use this notation. They are defined by the interpreter and
its implementations. It is not recommended to define additional names using this
convention.
3. Leading double underscores (__*)
Class-private name mangling: These category names are used within the context of a class
definition. They are re-written to use a mangled form and avoid name clashes between
private variables of base and derived classes.

QUOTATIONS

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

What are different types of quotes in Python?


Quotation symbols are used to create string object in Python. Python recognizes single,
double and triple quoted strings. String literals are written by enclosing a sequence of
characters in single quotes ('hello'), double quotes ("hello") or triple quotes ('''hello''' or
"""hello""").
>>> var1='hello'
>>> var1
'hello'
>>> var2="hello"
>>> var2
'hello'
>>> var3='''hello'''
>>> var3
'hello'
>>> var4="""hello"""
>>> var4
'hello'
If it is required to embed double quotes as a part of string, the string itself should be put in
single quotes. On the other hand, if single quoted text is to be embedded, string should be
written in double quotes.
>>> var1='Welcome to "Python training" from Tutorialspoint'
>>> var1
'Welcome to "Python training" from Tutorialspoint'
>>> var2="Welcome to 'Python training' from Tutorialspoint"
>>> var2
"Welcome to 'Python training' from Tutorialspoint"

Difference Between Single and Double Quotes in Python


A String is a sequence of characters. You are allowed to start and end a string literal with
single and double quotes in Python. There are two ways to represent a string in python
programming.
In this article, you will see the difference between both the quotation marks with the help
of an example i.e. code with its output.
What are single quotes used for in Python?
Single quotes are used to mark a quote within a quote or a direct quote in a news story
headline.
When programming with Python, we generally use single quotes for string literals. For
example – ‘my-identifier’. Let us understand with an example through code in Python.
NOTE: Always make use of single quotes when you know your string may contain double
quotes within.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Example usage of single quotes in Python


Below is the code where you can see the implementation of single quote.
1 word = 'Ask?'
2 print(word)
3 sentence = 'Python Programming'
4 print(sentence)
5 name = '"Hi" ABC'
6 print(name)
7 congrat = 'We congrat's you.'
8 print(congrat)

Output
Ask?
Python Programming
Hi ABC
Invalid Syntax
What are double quotes in Python used for?
A double quotation mark is to set off a direct (word-for-word) quotation. For example – “I
hope you will be here,” he said. In Python Programming, we use Double Quotes for string
representation. Let us understand with an example through code in python.
NOTE: Use double quotes to enclose your strings when you know there are going to be
single quotes within your string

Code
1 wish = "Hello World!"
2 print(wish)
3 hey = "AskPython says "Hi""
4 print(hey)
5 famous ="'Taj Mahal' is in Agra."
6 print(famous)
Output
Hello World!
Invalid Syntax
'Taj Mahal' is in Agra.
Key Differences Between Single and Double Quotes in Python
Single Quotation Mark Double Quotation Mark

Represented as ‘ ‘ Represented as ” “

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Single quotes for anything that behaves like an


Identifier. Double quotes generally we used for text.

Single quotes are used for regular expressions, dict Double quotes are used for string
keys or SQL. representation.

Eg. ‘We “welcome” you.’ Eg. “Hello it’s me.”

Bonus – Triple Quotes in Python


What if you have to use strings that may include both single and double quotes? For this,
Python allows you to use triple quotes. A simple example for the same is shown below.
Triple quotes also allow you to add multi-line strings to Python variables instead of being
limited to single lines.
Example of triple quotes
sentence1 = '''He asked, "did you speak with him?"'''
print(sentence1)
sentence2 = '''"That's great", she said.'''
print(sentence2)
Output:
He asked, "did you speak with him?"
"That's great", she said.
As you can see, Python now understands that the double and single quotes are part of the
string and do not need to be escaped.
Conclusion
To conclude this simple topic, I’d like to say this – the difference between single and double
quotes in Python is not huge. It absolutely depends on the circumstances that we use single
and double quotes in.

INDENTATION IN PYTHON

Indentation is a very important concept of Python because without proper


indenting the Python code, you will end up seeing IndentationError and the code will not
get compiled.
Indentation
In simple terms indentation refers to adding white space before a statement. But the
question arises is it even necessary?

To understand this consider a situation where you are reading a book and all of a
sudden all the page numbers from the book went missing. So you don’t know, where to

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

continue reading and you will get confused. This situation is similar with Python. Without
indentation, Python does not know which statement to execute next or which statement
belongs to which block. This will lead to IndentationError.
Python indentation is a way of telling a Python interpreter that the group of
statements belongs to a particular block of code. A block is a combination of all these
statements. Block can be regarded as the grouping of statements for a specific purpose.
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation to highlight the blocks of code. Whitespace is used for
indentation in Python. All statements with the same distance to the right belong to the
same block of code. If a block has to be more deeply nested, it is simply indented further
to the right. You can understand it better by looking at the following lines of code.
Example #1:

# Python program showing


# indentation

site = 'gfg'

if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
print('retype the URL.')
print('All set !')

Output:
Logging on to geeksforgeeks...
All set !
The lines print(‘Logging on to geeksforgeeks…’) and print(‘retype the URL.’) are two
separate code blocks. The two blocks of code in our example if-statement are both
indented four spaces. The final print(‘All set!’) is not indented, and so it does not belong
to the else-block.
Example #2:

j=1

while(j<= 5):
print(j)
j=j+1

Output:
1

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

2
3
4
5
To indicate a block of code in Python, you must indent each line of the block by the same
whitespace. The two lines of code in the while loop are both indented four spaces. It is
required for indicating what block of code a statement belongs to. For
example, j=1 and while(j<=5): is not indented, and so it is not within while block. So,
Python code structures by indentation.

Note: Python uses 4 spaces as indentation by default. However, the number of spaces is
up to you, but a minimum of 1 space has to be used.

MULTI LINE STATEMENT

Python statements are the code instructions that are executed by the Python
interpreter.
Python Statements Examples
Let’s look at some simple statement examples.
count = 10 # statement 1

class Foo: # statement 2


pass # statement 3
Python Multi-line Statements
Python statements are usually written in a single line. The newline character marks the end
of the statement. If the statement is very long, we can explicitly divide into multiple lines
with the line continuation character (\).
Let’s look at some examples of multi-line statements.
message = "Hello There.\nYou have come to the right place to learn Python Programming.\n" \
"Follow the tutorials to become expert in Python. " \
"Don't forget to share it with your friends too."

math_result = 1 + 2 + 3 + 4 + \
5+6+7+8+\
9 + 10

print(message)
print(math_result)
Python Statements

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Python supports multi-line continuation inside parentheses ( ), brackets [ ], and braces { }.


The brackets are used by List and the braces are used by dictionary objects. We can use
parentheses for expressions, tuples, and strings.
message = ("Hello\n"
"Hi\n"
"Namaste")

math_result = (1 + 2 + 3 + 4 +
5+6+7+8+
9 + 10)

prime_numbers_tuple = (2, 3, 5, 7,
11, 13, 17)

list_fruits = ["Apple", "Banana",


"Orange", "Mango"]

dict_countries = {"USA": "United States of America", "IN": "India",


"UK": "United Kingdom", "FR": "France"}
Can we have multiple statements in a single line?
We can use semicolon (;) to have multiple statements in a single line.
x = 1; y = 2; z = 3
Python Simple Statements
Python simple statement is comprised in a single line. The multiline statements
created above are also simple statements because they can be written in a single line. Let’s
look at some important types of simple statements in Python.
1. Expression Statement
i = int("10") # expression is evaluated and the result is assigned to the variable.

sum = 1 + 2 + 3 # statement contains an expression to be evaluated first.

2. Assignment Statement
count = 10 # value is assigned to the variable, no expression is evaluated

message = "Hi"

3. Assert Statement
assert 5 < 10
assert (True or False)

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

4. pass Statement
def foo():
pass # pass statement

5. del Statement
name = "Python"
del name # del statement

return Statement
def foo():
return 10 # return statement

7. yield Statement
def yield_statement():
yield 'Statement 1' # yield statement

8. raise Statement
def raise_example():
raise TypeError('Exception Example') # raise statement

9. break Statement
numbers = [1, 2, 3]

for num in numbers:


if num > 2:
break # break statement

10. continue Statement


numbers = [1, 2, 3]

for num in numbers:


if num > 2:
continue # continue statement
print(num)

11. import Statement

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

import collections
import calendar as cal
from csv import DictReader

12. global Statement


name = "Python"

def global_example():
global name # global statement
name = "Flask"

print(name) # prints Python


global_example()
print(name) # prints Flask

13. nonlocal Statement

def outer_function():
scope = "local"

def inner_function():
nonlocal scope # nonlocal statement
scope = "nonlocal"
print(scope)

inner_function()
print(scope)

outer_function()

Python Compound Statements


Python compound statements contains group of other statements and affect their
execution. The compound statement generally span across multiple lines. Let’s briefly look
into a few compound statements.
1. if Statement
if 5 < 10:
print("This will always print")
else:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

print("Unreachable Code")

2. for Statement
for n in (1, 2, 3):
print(n)

3. while Statement
count = 5
while count > 0:
print(count)
count -= 1

4. try Statement
try:
print("try")
except ValueError as ve:
print(ve)

5. with Statement
with open('data.csv') as file:
file.read()

6. Function Definition Statement


A python function definition is an executable statement. Its execution binds the function
name in the current local namespace to a function object. The function is executed only
when it’s called.
def useless():
pass
7. Class Definition Statement
It’s an executable statement. The class definition defines the class object.
class Data:
id = 0
8. Coroutines Function Definition Statement
import asyncio

async def ping(url):


print(f'Ping Started for
{url}') await asyncio.sleep(1)
print(f'Ping Finished for {url}')
Conclusion

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Python statements are used by the Python interpreter to run the code. It’s good to know
about the different types of statements in Python.

INPUT AND OUTPUT IN PYTHON

How to Take Input from User in Python


Sometimes a developer might want to take user input at some point in the program. To do
this Python provides an input() function.
Syntax:
input('prompt')
where prompt is an optional string that is displayed on the string at the time of taking
input.
Example 1: Python get user input with a message

# Taking input from the user


name = input("Enter your name: ")

# Output
print("Hello, " + name)
print(type(name))

Output:
Enter your name: GFG
Hello, GFG
<class 'str'>
Note: Python takes all the input as a string input by default. To convert it to any other
data type we have to convert the input explicitly. For example, to convert the input to int
or float we have to use the int() and float() method respectively.
Example 2: Integer input in Python

# Taking input from the user as integer


num = int(input("Enter a number: "))

add = num + 1

# Output
print(add)

Output:
Enter a number: 25
26

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

How to Display Output in Python


Python provides the print() function to display output to the standard output
devices.
Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one.
Default :
end=’end’: (Optional) Specify what to print at the end.Default : ‘ \n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Returns: It returns output to the screen.
Example: Python Print Output

# Python program to demonstrate


# print() method
print("GFG")
# code for disabling the softspace feature
print('G', 'F', 'G')

Output
GFG
GFG
In the above example, we can see that in the case of the 2nd print statement there is a
space between every letter and the print statement always add a new line character at
the end of the string. This is because after every character the sep parameter is printed
and at the end of the string the end parameter is printed. Let’s try to change this sep and
end parameter.
Example: Python Print output with custom sep and end parameter

# Python program to demonstrate


# print() method
print("GFG", end = "@")

# code for disabling the softspace feature


print('G', 'F', 'G', sep="#")

Output
GFG@G#F#G
Formatting Output

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Formatting output in Python can be done in many ways. Let’s discuss them below
Using formatted string literals
We can use formatted string literals, by starting a string with f or F before opening
quotation marks or triple quotation marks. In this string, we can write Python
expressions between { and } that can refer to a variable or any literal value.
Example: Python String formatting using F string

# Declaring a variable
name = "Gfg"

# Output
print(f'Hello {name}! How are you?')

Output:
Hello Gfg! How are you?
Using format()
We can also use format() function to format our output to make it look presentable. The
curly braces { } work as placeholders. We can specify the order in which variables occur
in the output.
Example: Python string formatting using format() function

# Initializing variables
a = 20
b = 10

# addition
sum = a + b

# subtraction
sub = a- b

# Output
print('The value of a is {} and b is {}'.format(a,b))

print('{2} is the sum of {0} and {1}'.format(a,b,sum))

print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a = a ,


value_b = b,
sub_value = sub))

Output:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

The value of a is 20 and b is 10


30 is the sum of 20 and 10
10 is the subtraction of 20 and 10

Using % Operator
We can use ‘%’ operator. % values are replaced with zero or more value of elements.
The formatting using % is similar to that of ‘printf’ in the C programming language.
%d – integer
%f – float
%s – string
%x – hexadecimal
%o – octal
Example:

# Taking input from the user


num = int(input("Enter a value: "))

add = num + 5

# Output
print("The sum is %d" %add)

Output:
Enter a value: 50
The sum is 55

IMPORT IN PYTHON
Import is a keyword that is used to import the definitions or functions from a
module. Also, a module is a Python file that contains prewritten code or functions. The
import keyword is used along with another keyword from which is used to import the
module.
Suppose you want a program that accepts an integer and give the square root of the
integer. For this, you can make a program or you can use a predefined function sqrt(),
which is a part of module math. So, to use the sqrt() function, you need to import it on your
current file by using the import keyword.
Let’s understand it with the following example:
from math import sqrt
var = int(input("Enter a Number: "))
sqt = sqrt(var)
print(sqt)

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Output
Enter a Number: 10
3.1622776601683795
Important Points to Remember
To print two different data types using the print() function, use a comma to separate
them.
Use Type conversion to convert the data type of the value which you get from
the input() function.
The from keyword is used to import a module.
The import keyword imports the definitions or functions from a module.
There are many modules in Python.
You can also install the third-party modules or libraries using the pip install command.

ADVANTAGES OF PYTHON
Easy to use and learn: For beginners, Python is straightforward to use. It is a high-level
programming language, and its syntax is like the English language. These reasons make the
language easy to learn and adapt to. Compared to Java and C, in Python, the same task can
be performed using fewer lines of code. As a result of its easy learning, the principles in
Python can be executed faster compared to other languages.
Increased productivity: Python is a very productive language. The simple nature of
Python helps the developers to concentrate on solving the issues in it. To understand the
syntax and behavior of the programming language, the users do not have to spend hours, so
more work is done.

Flexibility: This language is very flexible, and hence it allows the user to try new things.
The users can develop new sorts of the application using Python programming language.
The language does not restrict the user from trying something different. Other
programming languages do not provide this type of flexibility and freedom, and hence
Python is more preferred in these matters.

Extensive library: Python provides the user with a vast library. Python’s standard library
is massive, and just about every function one needs to perform is available in its library.
This is because it has a hugely supportive community and corporate sponsorship. External
libraries are not used by users while working with Python.

Supportive community: The Python language was created years ago, and hence it has a
mature community that can support every type of developer, starting from beginners’ level
to expert level. There are enough guides, tutorials, and documentation available on the
Python programming language, which helps the developers to understand the language

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

faster and better. Because of its supportive community, Python has rapid growth compared
to other languages.

DISADVANTAGES OF PYTHON

Speed: Compared to Java or C, the rate of Python is slower. Python is an interpreted


language that is dynamically typed. For the execution of a code, each line of the code needs
to be explicitly ordered since the language gets interpreted. This is time-consuming, and
hence it slows down the process of execution. The dynamic structure of Python also slows
its speed because while executing the code, the excess work also needs to be completed.
Therefore, in cases where fast acceleration is required, Python is not used there very
commonly.

Memory consumption: Python has a very high memory consumption. This is because it is
flexible to the data types. It uses large amounts of memory. Python is not a good choice for
tasks where the user wants to optimize memory, i.e., a memory-intensive language.
Mobile development: Python is strong in server platforms and desktops, and hence it is a
fantastic server-side programming language. But it is not appropriate for mobile
development. For mobile development, Python is a fragile language. Since it is not memory
efficient and has a prolonged power for processing, due to these reasons, Python does not
have many built-in mobile applications. Carbonnelle is a built-in application present in
Python.

Database access: Python provides easy programming. However, when it interacts with the
database, some issues arise. Compared to technologies like JDBC and ODBC, which are
pretty famous, the database access layer of the Python programming language is primitive
and underdeveloped. Large enterprises that usually need smooth interaction with complex
legacy data do not prefer the usage of Python.

Runtime errors: The users of Python mentioned various issues they faced with the
language design. Since the language of Python is dynamically typed, there can be changes in
the data type of a variable at any time. Therefore, it needs to be tested more often, and also,
there are errors in the language displayed during runtime.
Simplicity: Python is a straightforward and easy-to-use programming language which is
also a disadvantage of the language. The users of Python get so accustomed to its easy
syntax and extensive library feature that they face issues while learning other
programming languages. Some users also feel that the Java codes are unnecessary due to
their complexity. Therefore, Python has a very vulnerable nature, and the users start taking
everything lightly.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Comparison Table for Advantages and Disadvantages of Python


Advantages Disadvantages
Because of its elementary programming, users face
It is easy to learn and use, and it has
difficulty while working with other programming
an extensive library.
languages.
Python is a time-consuming language. It has a low
Python increases productivity.
execution speed.
There are many issues with the design of the
It is very flexible. language, which only gets displayed during
runtime.
It is not suited for memory-intensive programs and
It has a very supportive community.
mobile applications.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

UNIT V
FRUITFUL FUNCTIONS IN PYTHON

Fruitful functions in python:


Defining a function, function call, types of function, python function arguments,
composition, python recursion and python lambda function.

DEFINING A FUNCTION

Python Functions is a block of related statements designed to perform a


computational, logical, or evaluative task. The idea is to put some commonly or
repeatedly done tasks together and make a function so that instead of writing the same
code again and again for different inputs, we can do the function calls to reuse code
contained in it over and over again.
Functions can be both built-in or user-defined. It helps the program to be concise, non-
repetitive, and organized.
Syntax:
def function_name(parameters):
"""docstring"""
statement(s)
return expression
Creating a Function
We can create a Python function using the def keyword.
Example: Python Creating Function

# A simple Python function

def fun():
print("Welcome to GFG")
Rules for defining a function
 The def keyword is used in the Python function to declare and define a function.
 The function name must begin with the following identifiers such as: A-Z, a- z, and
underscore (_).
 Every function must follow colon (:) and then indention to write the program.
 In a Python function, the reserved word cannot be used as a function name or
identifier.
 In Python, the function parameter can be empty or multiples.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

FUNCTION CALLING IN PYTHON

Once a function is created in Python, we can call it by writing function_name() itself


or another function/ nested function. Following is the syntax for calling a function.
Syntax:
def function_name():
Statement1
function_name() # directly call the function

# calling function using built-in function


def function_name():
str = function_name('john') # assign the function to call the function
print(str) # print the statement
Consider the following example to print the Welcome Message using a function in
Python.
CallFun.py
def MyFun():
print("Hello World")
print(" Welcome to the JavaTpoint")

MyFun() # Call Function to print the message.


Output:
Hello World
Welcome to the JavaTpoint
In the above example, we call the MyFun() function that prints the statements.

Calling Nested Function in Python

When we construct one function inside another, it is called a nested function. We


can create nested functions using the def keyword. After creating the function, we have
to call the outer and the inner function to execute the statement. Lets' create a program
to understand the concept of nested functions and how we can call these functions.
Nest.py
def OutFun(): # outer function
print("Hello, it is the outer function")

def InFun(): # inner function

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

print("Hello, It is the inner function")


InFun() # call inner

OutFun() # call outer function


Output:
Hello, it is the outer function
Hello, it is the inner function
As we can see in the above example, the InFun() function is defined inside the
OutFun() function. To call the InFun() function, we first call the OutFun() function in the
program. After that, the OutFun() function will start executing and then call InFun() as
the above output.

Functions as First-Class Objects


In Python, the functions as First-Class Objects. Because it treats the same as the
object, and it has the same properties and method as an object. A function can be
assigned to a variable, pass them as an argument, store them in data structures and
return a value from other functions. It can be manipulated, such as other objects in
Python. Furthermore, all the data in the Python program is represented in the objects or
relations. Hence it is also called first-class citizens of Python function.
Properties of First-Class functions
 Functions can be assigned to a variable
 A function is an example of an object type.
 We also return the function from a function.
 Functions have the same properties and methods as objects
 The function is treated as an object to pass as an argument to another function.
 Create a program to understand Python functions as an object.
Obj.py

def MyObject(text): # Pass an argument.


return text.upper()

# Call the function inside the print() function.


print (MyObject("Welcome to JavaTpoint"))

str = MyObject # assign the function to a variable

# call the function using the str variable.


print (str("Hello, Welcome to JavaTpoint"))

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Output:
WELCOME TO JAVATPOINT
HELLO, WELCOME TO JAVATPOINT
Write a program to call a function inside the class.
Student.py
class Student:
Roll_no = 101
name = "Johnson"
def show(self):
print(" Roll no. is %d\nName of student is %s" % (self.Roll_no, self.name))

stud = Student() # Create the stud object of Student class


stud.show() # call the function using stud object.
Output:
Roll no. is 101
Name of student is Johnson

Calling a Function
After creating a function we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.
Example: Python Calling Function

# A simple Python function

def fun():
print("Welcome to GFG")

# Driver code to call a function


fun()

Output
Welcome to GFG
Arguments of a Function
Arguments are the values passed inside the parenthesis of the function. A function can
have any number of arguments separated by a comma.
Example: Python Function with arguments
In this example, we will create a simple function to check whether the number passed as
an argument to the function is even or odd.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

# A simple Python function to check


# whether x is even or odd

def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2)
evenOdd(3)

Output
even
odd
Types of Arguments
Python supports various types of arguments that can be passed at the time of the function
call. Let’s discuss each type in detail.
Default arguments
A default argument is a parameter that assumes a default value if a value is not provided
in the function call for that argument. The following example illustrates Default
arguments.

# Python program to demonstrate


# default arguments

def myFun(x, y=50):


print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only


# argument)
myFun(10)

Output

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

('x: ', 10)


('y: ', 50)
Like C++ default arguments, any number of arguments in a function can have a default
value. But once we have a default argument, all the arguments to its right must also have
default values.

Keyword arguments
The idea is to allow the caller to specify the argument name with values so that caller
does not need to remember the order of parameters.

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')

Output
('Geeks', 'Practice')
('Geeks', 'Practice')
Variable-length arguments
In Python, we can pass a variable number of arguments to a function using special
symbols. There are two special symbols:
*args (Non-Keyword Arguments)
**kwargs (Keyword Arguments)
Example 1: Variable length non-keywords argument

# Python program to illustrate


# *args for variable number of arguments

def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Output
Hello
Welcome
to
GeeksforGeeks
Example 2: Variable length keyword arguments

# Python program to illustrate


# *kwargs for variable number of keyword arguments

def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))

# Driver code
myFun(first='Geeks', mid='for', last='Geeks')

Output
first == Geeks
mid == for
last == Geeks
Docstring
The first string after the function is called the Document string or Docstring in short. This
is used to describe the functionality of the function. The use of docstring in functions is
optional but it is considered a good practice.
The below syntax can be used to print out the docstring of a function:
Syntax: print(function_name.__doc__)
Example: Adding Docstring to the function

# A simple Python function to check


# whether x is even or odd

def evenOdd(x):
"""Function to check if the number is even or odd"""

if (x % 2 == 0):
print("even")

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

else:
print("odd")

# Driver code to call the function


print(evenOdd. doc )

Output
Function to check if the number is even or odd
The return statement
The function return statement is used to exit from a function and go back to the function
caller and return the specified value or data item to the caller.
Syntax: return [expression_list]
The return statement can consist of a variable, an expression, or a constant which is
returned to the end of the function execution. If none of the above is present with the
return statement a None object is returned.
Example: Python Function Return Statement

def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))

Output:
4
16
Is Python Function Pass by Reference or pass by value?
One important thing to note is, in Python every variable name is a reference. When we
pass a variable to a function, a new reference to the object is created. Parameter passing
in Python is the same as reference passing in Java.
Example:

# Here x is a new reference to same list lst


def myFun(x):
x[0] = 20

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

Output
[20, 11, 12, 13, 14, 15]
When we pass a reference and change the received reference to something else, the
connection between the passed and received parameter is broken. For example, consider
the below program.

def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = [20, 30, 40]

# Driver Code (Note that lst is not modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

Output
[10, 11, 12, 13, 14, 15]
Another example to demonstrate that the reference link is broken if we assign a new
value (inside the function).

def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = 20

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

# Driver Code (Note that lst is not modified


# after function call.
x = 10
myFun(x)
print(x)

Output
10
Exercise: Try to guess the output of the following code.

def swap(x, y):


temp = x
x=y
y = temp

# Driver code
x=2
y=3
swap(x, y)
print(x)
print(y)

Output
2
3
Anonymous functions:
In Python, an anonymous function means that a function is without a name. As we already
know the def keyword is used to define the normal functions and the lambda keyword is
used to create anonymous functions. Please see this for details.

# Python code to illustrate the cube of a number


# using lambda function

def cube(x): return x*x*x

cube_v2 = lambda x : x*x*x

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

print(cube(7))
print(cube_v2(7))

Output
343
Python Function within Functions
A function that is defined inside another function is known as the inner function or
nested function. Nested functions are able to access variables of the enclosing scope.
Inner functions are used so that they can be protected from everything happening outside
the function.

# Python program to
# demonstrate accessing of
# variables of nested functions

def f1():
s = 'I love GeeksforGeeks'

def f2():
print(s)

f2()

# Driver's code
f1()

Output
I love GeeksforGeeks

TYPES OF FUNCTIONS IN PYTHON

In real-time, a Python function may define with or without parameters, and a


function may or may not return a value. It entirely depends upon the user requirement. In
this article, we explain to you the types of functions in Python Programming language with
examples.
In Python programming, as per our requirement, We can define the User defined
functions in multiple ways. The following are the list of available types of functions in
Python.
Python Function with no argument and no return value.
Function with no argument and with a Return value.

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Python Function with argument and No Return value.


Function with argument and return value.
From the above, 1 and 3 types of functions in Python do not return any value when they
called. So, while defining them, we can avoid the return keyword. When we call the 2 and 4
types of functions in Python, they return some value. So, we have to use the return
keyword.
Types of Functions in Python
The following examples explain the list of available types of functions in Python
programming.
Python Function with No argument and No Return value
In this type of function in Python, While defining, declaring, or calling the
function, We won’t pass any arguments to them. This type of Python function won’t return
any value when we call them.
Whenever we are not expecting any return value, we might need some print
statements as output. In such a scenario, we can use this type of functions in Python.

Python Function with no argument and no return value.


Function with no argument and with a Return value.
Python Function with argument and No Return value.
Function with argument and return value.
From the above, 1 and 3 types of functions in Python do not return any value when they
called. So, while defining them, we can avoid the return keyword. When we call the 2 and 4
types of functions in Python, they return some value. So, we have to use the return
keyword.
Types of Functions in Python
The following examples explain the list of available types of functions in Python
programming.
Python Function with No argument and No Return value Example
In this type of function in the Python program, we are going to calculate the Sum of 2
integer values and print the output from the user defined function itself.
# Python Function with No Arguments, and No Return Value
def Adding():
a = 20
b = 30
Sum = a + b
print("After Calling :", Sum)
Adding()
Python Function with No arguments and no Return value output
After Calling : 50
>>> Adding()

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

After Calling : 50
If you observe the Addition() Function, We haven’t passed any arguments /parameters to
the Addition()
We declared the integer variables a, b, and assigned 20 to a and 30 to b. In the next line, we
calculate the sum using Arithmetic operator ( + )
a = 20
b = 30
Sum = a + b
The below Python print statement is to print the output. Whenever we call the Adding(), it
prints the same output because a and b have fixed values inside the method.
print("After Calling :", Sum)
Python Function with no argument and with a Return value
In this type of function in Python, We won’t pass any arguments to the function while
defining, declaring, or calling it. When we call this type of function in Python, it returns
some value.
Function with No arguments and with a Return value Example
In this type of function in the Python program, we are going to calculate the multiplication
of 2 integer values using the user defined function without arguments and return keyword.
# Python Function with No Arguments, and with Return Value
def Multiplication():
a = 10
b = 25
Multi = a * b
return Multi
print("After Calling the Multiplication : ", Multiplication())
Python Function with No arguments and with a Return value output
After Calling the Multiplication : 250
>>> Multiplication()
250
Within the Multiplication (), We haven’t passed any arguments /parameters. Next, We
declared the integer variables of Multi, a, b, and we assigned 10 to a, and 25 to b. In the
next line, we Multiplied both a and b using an Arithmetic operator ( * ).
a = 10
b = 25
Multi = a * b
Lastly, the print statement is to print the output. Remember, we are using the print
statement outside the defined function, and we are using the name inside the print
statement. (nothing but calling the method)
print("After Calling the Multiplication : ", Multiplication())

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Here also, Whenever we call the Multiplication(), it prints the same output because a and b
have fixed values inside it.
Python Function with argument and No Return value
If you observe the above 2 types of functions, No matter how many times you executive,
Python gives the same output. We don’t have any control over the variable values (a, b)
because they are fixed values. In real-time, we mostly deal with dynamic data means we
have to allow the user to enter his own values rather than fixed ones.
This type of function in Python allows us to pass the arguments while calling it. But, This
type of function in Python won’t return any value when we call it.
Python Function with argument and No Return value Example
This program for the type of function in Python allows the user to enter 2 integer values
and then, We are going to pass those values to the user defined function to Multiply them.
Python Function with Arguments, and NO Return Value
def Multiplications(a, b):
Multi = a * b
print("After Calling the Function:", Multi)

Multiplications(10, 20)
We called the Multiplication function with different values, and it is giving the output as per
the values.
Python Function with argument and Return value
This type of python function allows us to pass the arguments to the function while calling
the function. This type of functions in Python returns some value when we call the function.
This type of user defined function called a fully dynamic function means it provides
maximum control to the end-user.
Python Function with arguments and Return value Example
This type of function in the Python program allows the user to enter 2 integer values. Then,
we pass those values to the user-defined function to add those values and return the value
using the return keyword.
# Python Function with Arguments, and NO Return
Value def Addition(a, b):
Sum = a + b
return Sum
# We are calling the Function Outside the Definition
print("After Calling the Function:", Addition(25,
45))

PYTHON FUNCTION ARGUMENTS

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname+ "Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Arguments are often shortened to args in Python documentations.


Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are
passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that are sent to the function when it is called.

Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2 arguments, not
more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname,lname):
print(fname+ "" +lname)

my_function("Emil", "Refsnes")
Try it Yourself »
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
def my_function(fname,lname):
print(fname+ "" +lname)

my_function("Emil")

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

COMPOSITION IN PYTHON

Composition is one of the important concepts of Object-oriented programming


(OOPs). Composition basically enables us for creating complex types objects by combining
other types of objects in the program. Composition represents ‘has a relationship’ type or
we can call composition as ‘has a relationship’ in the OOPs concept. It means that a
composite class present in the program can contains the objects from the other class
components and this type of relationship model is called as has a relationship.
Note: The classes that contains objects from the other classes in the program are called as
composites whereas the classes which we use to create more complex type of relationship
models is called as components.
Look at the following UML diagram to understand about the composition or has a
relationship model:
Composite

In the above UML diagram, we have represented two different type of classes i.e.,
composites and components. The relationship between the composites and components is
the composition. As we can see that we have represented the composition through a line
where diamond from the composite class is pointing towards the components class
representing the composition relationship.
In the composition relation, the composite class side represents the cardinality.
Basically, the cardinality means the number of valid ranges or objects of the components
class that a composite class is containing in it. As we can see in the above diagram, the 1 in
the composite class represents only object of component class type is present in the
composite class through composition.
We can express the cardinality of the composition through the following ways:
By using a number (1, 2, 3, etc.)
By using the * symbol
By defining a range in composite (1...3, 2...5 etc.)
Composition allows us to reuse our code by adding objects with the other new objects, the
feature which is not present in the inheritance concept.
We know that Python is object-oriented programming language so it also follows
the composition method. In Python, the composition allows us to reuse the implementation
of the component class object in the composite classes. We have to remember that the
composite class is not actually inheriting the component class interface but it is adapting
the interface of instances of component class.
The composition relationship in Python between composite class and component
class is considered as loosely coupled. It means that if we make changes in component
S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College

class, it will rarely affect the composite class and if we make changes in the composite class,
it will never affect the component class. This feature of composition in Python provides us
better adaptability with the changes. It also allows us to introduce new changes in the
application according to the requirements without affecting the existing code.
First, we will understand this through a basic example where we will use the basic
concept of composition in our Python program and then we will move forward with the use
of composition.
Example:
# create a component class in program
class ComponentClass:
# create the composite class constructor in component
def init (self):
print('An object for the Component class is created ...')
# using the composite class instance method
def mk1(self):
print('The Component class method mk1() is executed successfully ...')
# create a composite class in program
class CompositeClass:
# create a class constructor for composite class
def init (self):
# creating an instance for the component class
self.inst1 = ComponentClass()
print('An object for the Composite class is also created ...')
# creating a class instance method for composite class
def mk(self):
print('The Composite class method mk() is also successfully executed ...')
# calling the mk1() method of component class in composite class
self.inst1.mk1()
# creating an instance for the composite class
inst2 = CompositeClass()
# calling out mk() method from the composite class
inst2.mk()
Output:
An object for the Component class is created ...
An object for the Composite class is also created ...
The Composite class method mk() is also successfully executed ...
The Component class method mk1() is executed successfully ...

Explanation: In the above given program, we have created two classes i.e., composite class
and component class and named them specifically. The ComponentClass and

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

CompositeClass shares the ‘has a type’ relation between them i.e., Composition relation. We
have also created one object for both the classes. To use the composition between the
classes, we have created a constructor for the composition class. We can see that we
also have defined two methods into the respective classes i.e., mk() & mk1(). We have
called out mk1() method of component class inside the mk() method of composite
class. So, whenever we will call out the mk1() in the program, the mk() method will
also be called out. We can also see this in the output of the program.
That’s how we use the composition relation between the composite and component class in
our Python program. Now, lets move forward with the uses of composition in Python.
Use of Composition in Python:
As we already discussed that the with the help of composition, we can use the
interface of component class objects in the composite class. We can also reuse the code for
the instance and interfaces of it. By this we can save our lot of time and writing of code for
it. Let's understand how the composition in Python will be really helpful to us in daily life
through the following example program:

First create a Python program file by writing the following program in it:
# create an address class in the program
class AddressClass:
# define the components of the address class with default function
def init (self, Street1, LiveinCity, LiveinState, PostalCode, Country, Street2 = ''): #
defining components of address class as variables
self.Street1 = Street1
self.Street2 = Street2
self.LiveinCity = LiveinCity
self.LiveinState = LiveinState
self.PostalCode = PostalCode
self.Country = Country
# define the properties of the address class with default function
def str (self):
TotalLines = [self.Street1]
# using the if method to append the lines
if self.Street2:
lines.append(self.Street2)
# printing following components in next line
TotalLines.append(f'{self.LiveinCity},{self.LiveinState}{self.PostalCode}
{self.Country}')
return '\n'.join(TotalLines) # appending the lines for output
After writing the above program, save this Python file into the disk (We saved it with
changing.py name in the device).

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

After that, open another Python program file and write the following program in it:
# import the python program script for the address class
from changing import AddressClass
# define the elements for the address class
Address1 = AddressClass('55 Main St.', 'Concord City', 'NH25', '03301', 'Mexico')
Address2 = AddressClass('36 Side St.', 'New Mexico City', 'NH67', '033207', 'Mexico')
# print the address elements in the output
print('The first address element we added is: ')
print(Address1)
print('The second address element we added is: ')
print(Address2)
Output:
The first address element we added is:
55 Main St.
Concord City, NH25 03301 Mexico
The second address element we added is:
36 Side St.
New Mexico City, NH67 033207 Mexico
Explanation:
In the above program, we have used composition relation in the address class that
we defined in the changing.py script file.
In the address class, we have also defined the components of it. After that, we set the
components of address class to variables so that it can store values in it. Then, we have
modified the components and append the lines for the components in the output.
We used if statement for it. Then, we saved the script file in the device. We opened another
Python file after that as we can see above. In the second file, we imported the address class
from the changing.py script file. We used the addressclass() to add the elements of address
in it. After that, the elements we added, we stored them as variable. Then, we printed the
address elements that are stored in variables in the output.
We have implemented the str() function in address class to modify the
components of the address class i.e., how they being displayed and append the line in the
output. While we use the address class components, it will also invoke the str() function
to called out. This is because of the composition relation function we used in the address
class. It will help us to reuse the code we have written and interface of the str()
function.

RECURSION IN PYTHON

The term Recursion can be defined as the process of defining something in terms of
itself. In simple words, it is a process in which a function calls itself directly or indirectly.
S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College

Advantages of using recursion


A complicated function can be split down into smaller sub-problems utilizing
recursion.
Sequence creation is simpler through recursion than utilizing any nested iteration.
Recursive functions render the code look simple and effective.
Disadvantages of using recursion
A lot of memory and time is taken through recursive calls which makes it expensive for
use.
Recursive functions are challenging to debug.
The reasoning behind recursion can sometimes be tough to think through.

Syntax:
def func(): <--
|
| (recursive call)
|
func() ----
Example 1:
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....

# Program to print the fibonacci series upto n_terms

# Recursive function
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))

n_terms = 10

# check if the number of terms is valid


if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Output:
Fibonacci series:
0
1
1
2
3
5
8
13
21
34
Example 2:
The factorial of 6 is denoted as 6! = 1*2*3*4*5*6 = 720.

# Program to print factorial of a number


# recursively.

# Recursive function
def recursive_factorial(n):
if n == 1:
return n
else:
return n * recursive_factorial(n-1)

# user input
num = 6

# check if the input is valid or not


if num < 0:
print("Invalid input ! Please enter a positive number.")
elif num == 0:
print("Factorial of number 0 is 1")
else:
print("Factorial of number", num, "=", recursive_factorial(num))

utput:
Factorial of number 6 = 720

What is Tail-Recursion?

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

A unique type of recursion where the last procedure of a function is a recursive


call. The recursion may be automated away by performing the request in the current
stack frame and returning the output instead of generating a new stack frame. The tail-
recursion may be optimized by the compiler which makes it better than non-tail recursive
functions.
Is it possible to optimize a program by making use of a tail-recursive function instead of
non-tail recursive function?
Considering the function given below in order to calculate the factorial of n, we can
observe that the function looks like a tail-recursive at first but it is a non-tail-recursive
function. If we observe closely, we can see that the value returned by Recur_facto(n-1) is
used in Recur_facto(n), so the call to Recur_facto(n-1) is not the last thing done by
Recur_facto(n).

# Program to calculate factorial of a number


# using a Non-Tail-Recursive function.

# non-tail recursive function


def Recur_facto(n):

if (n == 0):
return 1

return n * Recur_facto(n-1)

# print the result


print(Recur_facto(6))

Output:
720

We can write the given function Recur_facto as a tail-recursive function. The idea is to use
one more argument and in the second argument, we accommodate the value of the
factorial. When n reaches 0, return the final value of the factorial of the desired number.

# Program to calculate factorial of a number


# using a Tail-Recursive function.

# A tail recursive function


def Recur_facto(n, a = 1):

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

if (n == 0):
return a

return Recur_facto(n - 1, n * a)

# print the result


print(Recur_facto(6))

Output:
720

PYTHON LAMBDA FUNCTIONS

Python Lambda Functions are anonymous function means that the function is
without a name. As we already know that the def keyword is used to define a normal
function in Python. Similarly, the lambda keyword is used to define an anonymous
function in Python.
Python Lambda Function Syntax:
lambda arguments: expression
This function can have any number of arguments but only one expression, which is
evaluated and returned.
One is free to use lambda functions wherever function objects are required.
You need to keep in your knowledge that lambda functions are syntactically restricted to
a single expression.
It has various uses in particular fields of programming besides other types of expressions
in functions.
Example: Lambda Function Example

# Python program to demonstrate


# lambda functions

string ='GeeksforGeeks'

# lambda returns a function object


print(lambda string : string)

Output
<function <lambda> at 0x7f65e6bbce18>

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

In this above example, the lambda is not being called by the print function but simply
returning the function object and the memory location where it is stored.
So, to make the print to print the string first we need to call the lambda so that the string
will get pass the print.
Example:

# Python program to demonstrate


# lambda functions

x ="GeeksforGeeks"

# lambda gets pass to print


(lambda x : print(x))(x)

Output
GeeksforGeeks

Difference Between Lambda functions and def defined function


Let’s look at this example and try to understand the difference between a normal
def defined function and lambda function. This is a program that returns the cube of a
given value:

# Python code to illustrate cube of a number


# showing difference between def() and lambda().
def cube(y):
return y*y*y

lambda_cube = lambda y: y*y*y

# using the normally


# defined function
print(cube(5))

# using the lambda function


print(lambda_cube(5))

Output:
125
125

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

As we can see in the above example both the cube() function and lambda_cube()
function behave the same and as intended. Let’s analyze the above example a bit more:
Without using Lambda: Here, both of them return the cube of a given number. But, while
using def, we needed to define a function with a name cube and needed to pass a value to
it. After execution, we also needed to return the result from where the function was called
using the return keyword.
Using Lambda: Lambda definition does not include a “return” statement, it always
contains an expression that is returned. We can also put a lambda definition anywhere
a function is expected, and we don’t have to assign it to a variable at all. This is the
simplicity of lambda functions.
Let’s see some more commonly used examples of lambda functions.

Example 1: Python Lambda Function with List Comprehension


In this example, we will use the lambda function with list comprehension and lambda
with for loop. We will try to print the table of 10.

tables = [lambda x=x: x*10 for x in range(1, 11)]

for table in tables:


print(table())

Output
10
20
30
40
50
60
70
80
90
100
Example 2: Python Lambda Function with if-else

# Example of lambda function using if-else


Max = lambda a, b : a if(a > b) else b

print(Max(1, 2))

Output
2

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Example 3: Python Lambda with Multiple statements


Lambda functions does not allow multiple statements, however, we can create two
lambda functions and then call the other lambda function as a parameter to the first
function. Let’s try to find the second maximum element using lambda.

List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]]

# Sort each sublist


sortList = lambda x: (sorted(i) for i in x)

# Get the second largest element


secondLargest = lambda x, f : [y[len(y)-2] for y in f(x)]
res = secondLargest(List, sortList)

print(res)

Output
[3, 16, 9]
In the above example, we have created a lambda function that sorts each sublist of the
given list. Then this list is passed as the parameter to the second lambda function which
returns the n-2 element from the sorted list where n is the length of the sublist.
Lambda functions can be used along with built-in functions
like filter(), map() and reduce().
Using lambda() Function with filter()
The filter() function in Python takes in a function and a list as arguments. This offers an
elegant way to filter out all the elements of a sequence “sequence”, for which the function
returns True. Here is a small program that returns the odd numbers from an input list:
Example 1:

# Python code to illustrate


# filter() with lambda()
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]

final_list = list(filter(lambda x: (x%2 != 0) , li))


print(final_list)

Output:
[5, 7, 97, 77, 23, 73, 61]
Example 2:

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

# Python 3 code to people above 18 yrs


ages = [13, 90, 17, 59, 21, 60, 5]

adults = list(filter(lambda age: age>18, ages))

print(adults)

Output:
[90, 59, 21, 60]

Using lambda() Function with map()


The map() function in Python takes in a function and a list as an argument. The function
is called with a lambda function and a list and a new list is returned which contains all the
lambda modified items returned by that function for each item. Example:
Example 1:

# Python code to illustrate


# map() with lambda()
# to get double of a list.
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]

final_list = list(map(lambda x: x*2, li))


print(final_list)

Output:
[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
Example 2:

# Python program to demonstrate


# use of lambda() function
# with map() function
animals = ['dog', 'cat', 'parrot', 'rabbit']

# here we intend to change all animal names


# to upper case and return the same
uppered_animals = list(map(lambda animal: str.upper(animal), animals))

print(uppered_animals)

Output:
['DOG', 'CAT', 'PARROT', 'RABBIT']

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]
Sree Narayana Guru College

Using lambda() Function with reduce()


The reduce() function in Python takes in a function and a list as an argument. The
function is called with a lambda function and an iterable and a new reduced result is
returned. This performs a repetitive operation over the pairs of the iterable. The reduce()
function belongs to the functools module.
Example 1:

# Python code to illustrate


# reduce() with lambda()
# to get sum of a list

from functools import reduce


li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print (sum)

Output:
193
Here the results of previous two elements are added to the next element and this goes on
till the end of the list like (((((5+8)+10)+20)+50)+100).

Example 2:

# python code to demonstrate working of reduce()


# with a lambda function

# importing functools for reduce()


import functools

# initializing list
lis = [ 1 , 3, 5, 6, 2, ]

# using reduce to compute maximum element from list


print ("The maximum element of the list is : ",end="")
print (functools.reduce(lambda a,b : a if a > b else b,lis))

Output:
The maximum element of the list is : 6

S Sree Narayana Guru College - Study Material - Even


Semester [2021- 22]

You might also like