0% found this document useful (0 votes)
35 views154 pages

24CSE24 - Data Structures Using C

The document outlines the vision, mission, quality policy, and values of the Department of Computer Science & Engineering at New Horizon College of Engineering, focusing on data science education. It details the program outcomes and specific outcomes for the Data Structures using C course, including course content and learning objectives. Additionally, it provides a comprehensive overview of the programming essentials in C, including its history, features, structure, and key concepts such as tokens, keywords, identifiers, and constants.

Uploaded by

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

24CSE24 - Data Structures Using C

The document outlines the vision, mission, quality policy, and values of the Department of Computer Science & Engineering at New Horizon College of Engineering, focusing on data science education. It details the program outcomes and specific outcomes for the Data Structures using C course, including course content and learning objectives. Additionally, it provides a comprehensive overview of the programming essentials in C, including its history, features, structure, and key concepts such as tokens, keywords, identifiers, and constants.

Uploaded by

CHAKRI BABLU
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 154

Department of Computer Science & Engineering (Data Science)

24CSE24

DATA STRUCTURES USING C

Semester: II AY: 2024-25


NEW HORIZON COLLEGE OF ENGINEERING

VISION

To emerge as an institute of eminence in the fields of engineering, technology and


management in serving the industry and the nation by empowering students with
a high degree of technical, managerial and practical competence.

MISSION

To strengthen the theoretical, practical and ethical dimensions of the learning


process by fostering a culture of research and innovation among faculty members
and students.

To encourage long-term interaction between the academia and industry through


their involvement in the design of curriculum and its hands-on implementation.

To strengthen and mould students in professional, ethical, social and


environmental dimensions by encouraging participation in co-curricular and
extracurricular activities

QUALITY POLICY
To provide educational services of the highest quality both curricular and co-
curricular to enable students integrate skills and serve the industry and society
equally well at global level.

VALUES
• Academic Freedom
• Integrity Inclusiveness
• Innovation
• Professionalism
• Social Responsibility
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING (DATA SCIENCE)

PROGRAM OUTCOMES (Pos)

PO1 Engineering Knowledge: Apply knowledge of mathematics, science,


engineering fundamentals and an engineering specialization to the solution of
complex Computer Science and Data Science engineering problems.

PO2 Problem Analysis: Identify, formulate, review research literature and


analyze complex Computer Science and Data Science engineering problems
reaching substantiated conclusions using first principles of mathematics, natural
sciences and engineering sciences.

PO3 Design / Development of Solutions: Design solutions for complex


Computer Science and Data Science engineering problems and design system
components or processes that meet specified needs with appropriate consideration
for public health and safety, cultural, societal and environmental considerations.

PO4 Conduct Investigations of Complex Problems:


Use research-based knowledge and research methods including design of
experiments, analysis and interpretation of data and synthesis of the information
to provide valid conclusions.

PO5 Modern tool usage: Create, select and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
modelling to complex Computer Science and Data Science engineering activities
with an understanding of the limitations.

PO6 The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice in
Computer Science and Data Science Engineering.

PO7 Environment and sustainability: Understand the impact of the


professional engineering solutions in Computer Science and Data Science
engineering in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

PO8 Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.

PO9 Individual and Team Work: Function effectively as an individual and as


a member or leader to diverse teams, and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex Computer
Science and Data Science engineering activities with the engineering community
and with society at large, such as, being able to comprehend and write effective
report and design documentation, make effective presentations, and give and
receive clear instructions.

PO11 Project Management and Finance: Demonstrate knowledge and


understanding of the engineering and management principles and apply these to
one’s own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.

PO12 Life-Long Learning: Recognize the need for, and have the preparation
and ability to engage in independent and life-long learning in the broadest context
of technological change.

PROGRAM SPECIFIC OUTCOMES (PSOs)

Apply data analysis techniques, algorithmic expertise, and


advanced modelling to effectively solve complex problems across
PSO1 various domains demonstrating heir capacity to derive insights and
propose innovative solutions in the realm of data-driven
technologies

Collaborate proficiently with experts from diverse fields and


actively engage in continuous professional growth in the domain of
PSO2
Computer Science & Engineering, specializing in the field of data
science.
DATA STRUCTURES USING C
Course Code 24CSE24 CIE Marks 50
L:T:P:S 2:0:0:0 SEE Marks 50
Hrs / Week 3 Total Marks 100
Credits 02 Exam Hours 03
Course outcomes: At the end of the course, the student will be able to:

CO1 Understand the essentials of programming constructs


CO2 Use the concepts of Arrays and Functions to develop programs using C language
CO3 Apply the concepts of Structures, Unions and Pointers to solve the given problem
CO4 Investigate the insertion and deletion operations of Stack data structure
CO5 Analyze the primitive operations of Queue data structure
CO6 Evaluate Sorting and Searching operations for a given set of data elements
Mapping of Course Outcomes to Program Outcomes and Program Specific Outcomes:

PO PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO1 PO1 PO1
1 0 1 2
CO1 3 3 3 - - - - - - - - 3
CO2 3 3 3 - - - - - - - - 3
CO3 3 3 3 - - - - - - - - 3
CO4 3 - 2 2 - - - - - - - -
CO5 3 3 1 2 - - - - - - - -
CO6 3 3 2 2 - - - - - - - 3
MODULE-1 Programming Essentials CO1 6 Hours
Structure of a Program, Data Types, Operators and Expressions, Managing Input and Output operations, Decision
Making, Branching and Looping Statements.

Text Book Text Book 1: Chapter 1 to Chapter 7


MODULE-2 Arrays and Functions CO2 6 Hours
One-Dimensional Arrays, Two-Dimensional Arrays, Declaration, Initialization. Built-in and User-defined
functions, Calling a Function, Category of Functions, Call by value and Call by reference, Recursion.
Text Book Text Book 1: Chapter 8, 13, 14, Text Book 2: Chapter 1
MODULE-3 Structures, Unions and Pointers CO3 6 Hours
Definition, Initialization, Arrays of Structures, Structures within Structures and Unions.
Understanding Pointers, Declaration, Initialization, Pointer Arithmetic. Pointers to Pointers
Text Book Text Book 1: Chapter 9, 17
MODULE-4 Stacks and Queues CO4, CO5 6 Hours
Overview of Data Structures, Representation of a Stack, Primitive Operations on a Stack, Representations of
Arithmetic Expressions, Evaluation of Postfix Expression.Introduction to Queue, Representation of a Queue,
Primitive Operations on a Queue.
Text Book Text Book 2: Chapter 5,6
MODULE-5 Searching and Sorting CO6 6 Hours
Searching, Linear Search, Binary Search, Recursive Binary Search. Sorting, Internal Sorting, External Sorting,
Bubble sort, Insertion Sort, Selection sort.
Text Book Text Book 2: Chapter 9
Text Books:  Let Us C: Authentic guide to C Programming language – 19th Edition Paperback
– Yashavant Kanetkar, 15 December 2022, ISBN: 9789389845693.
 Data Structures Through C – 4th Edition, Yashavant Kanetkar, BPB Publications, March
2022, ISBN 978-93-5551-189-8.
MODULE -1
Programming
Essentials
2.1 : INTRODUCTION TO C.

2.2 : BASIC STRUCTURE OF A ‘C’ PROGRAM

2.3 : C TOKENS.

2.4 : VARIABLES

2.5 : DATA TYPES.

2.5.1 PRIMARY DATA TYPE


2.5.2 USER DEFINED DATA TYPE
2.5.3 TYPE CONVERSION

2.6 : OPERATORS AND EXPRESSIONS.

2.7 : I/O FUNCTIONS

2.8 : CONTROL STATEMENTS


2.9 : DECISION MAKING STATEMENTS
2.9.1 : SIMPLE IF STATEMENT
2.9.2 : IF…ELSE STATEMENT
2.9.3 : NESTED IF…ELSE STATEMENT
2.9.4 : ELSE IF LADDER
2.10 : SELECTION STATEMENT (SWITCH STATEMENT)
2.11 : LOOPING AND BRANCHING
2.11.1 : WHILE LOOP
2.11.2 : DO...WHILE LOOP
2.11.3 : FOR LOOP
2.11.4 : JUMPS IN LOOPS
2.1 INTRODUCTION TO C
HISTORY OF C :
C language is one of the most popular computer languages today because it is a
structured, high level, machine independent language. It allows software developers to develop
software without worrying about the hardware platforms where they will be implemented.
The following flowchart shows the history of ANSI C .

1960 ALGOL International Group


1967 BCPL Martin Richards
1970 B Ken Thompson
1972 Traditional C Dennis Ritchie
1978 K&R C Kernighan & Ritchie
1989 ANSI C ANSI Committee
1990 ANSI/ISO C ISO Committee

Importance of C:
C is a very important language because of its many useful features. The increasing
popularity of C is due to its many desirable qualities. It is a robust language whose rich set of
built in functions and operators can be used to write any complex program. It allows software
developers to develop software without worrying about the hardware platforms where they will
be implemented. The C compiler combines the capabilities of an assembly language with the
features of a higher level language and therefore it is well suited for both system software and
business packages. Else these,
I. C language is efficient and fast.
II. C is highly portable.
III. C language is well suited for structured programming.
IV. C is a machine independent language.
V. C has the ability to extend itself.

Features of “c” language


 C is a Structured Programming Language and powerful language.
 C is a versatile Language (i.e.,) it has features of both Low Level Languages and High
Level Languages.
 It is used in system programming. Compilers, packages, Operating System are written
using C.
 C is a highly portable language. Source Program written in one computer can be
compiled, executed and run on another computer with less modification.
 Users can develop program quickly with few mistakes.
 It increases the readability of Program. Program can be modified without affecting the
other parts of a program.
 C is a Case Sensitive Language. It differentiates both Upper Case and Lower Case
separately.
 Every statement in C ends with semicolon.
 Programmers can write additional functions of their own. C language has a C Compiler.
 C language has the ability to extend itself. C is also a free form language, because each
group of statements can be placed together on one line.

 C language is used for developing software packages, system software, database systems,
graphics packages, spread sheets, CAD/CAM applications, word processors, office
automation, scientific and engineering applications.

2.1 BASIC STRUCTURE OF C PROGRAMMING: 10 marks

To write a C program, we first create functions and then put them together. A C program
may contain one or more sections. They are illustrated below.

Documentation section
Link section
Definition section
Global declaration section
main () Function section
{
Declaration part
Executable part
}
Subprogram section
Function 1
Function 2 (User defined functions)
…………..
…………..
Function n
i) Documentation section :
The documentation section consists of a set of comment lines giving the name of
the program, the author and other details, which the programmer would like to use later.

ii) Link section :


The link section provides instructions to the compiler to link functions from the
system library.

iii) Definition section :


The definition section defines all symbolic constants.

iv) Global declaration section :


There are some variables that are used in more than one function. Such variables are
called global variables and are declared in the global declaration section that is outside of
all the functions. This section also declares all the user-defined functions.

v) main () function section :


Every C program must have one main function section. This section contains two
parts; declaration part and executable part.

(a) Declaration part :


The declaration part declares all the variables used in the executable part.

(b) Executable part :


There is at least one statement in the executable part. These two parts must appear
between the opening and closing braces. The program execution begins at the opening brace
and ends at the closing brace. The closing brace of the main function is the logical end of
the program. All statements in the declaration and executable part end with a semicolon.

vi) Subprogram section :


The subprogram section contains all the user-defined functions that are called in the
main () function. User-defined functions are generally placed immediately after the main
() function, although they may appear in any order.
All section, except the main () function section may be absent when they are not required.
2.5.1 STEPS IN LEARNING C:

2.3 C TOKENS:

 Individual words and punctuation marks in a passage of text are termed as Tokens.
 In a C program, the smallest individual units are termed as C tokens.

2.6.1 C KEYWORDS
 C keywords are reserved words by the compiler.
 All the c keywords have been assigned a fixed meaning.
 Keywords cannot be used as variable names because they have been assigned fixed jobs.
 For utilizing the keywords in a program, no header files are to be included.
2.6.2 IDENTIFIERS
Identifier is a name given to program elements such as variables, functions, procedure,
arrays and soon. First character must be an Alphabet or Underscore. Identifier consists of
sequence of letters, digits or combination of both.

Rules for Identifier


 First character must be an Alphabet or Underscore( _ ).
 Special characters and embedded commas are not allowed.
 First 31 characters are given high priority or preference.

 Keyword cannot be used as Identifier.


 There should not be any white space.
 Both uppercase and lowercase letters are permitted.
The underscore character is also permitted in identifiers.
2.6.3 CONSTANTS
 Constants which do not change during the execution of a program.
 There are several types of constants in C.
 C supports several types of constants.

1. NUMERIC CONSTANTS:

(i) Integer constants:

 It consists of a set of digits 0 to 9 preceded by an optional + or - sign. Spaces, commas and


non digit characters are not permitted between digits.
 Example for valid decimal integer constants is

123, -31, 0, 562321, + 78


 Some examples for invalid integer constants are
15 750
20,000
Rs. 1000
(ii) Real constants:
 Real Constants are also known as Floating point constants.

 It consists of a fractional part in their representation. Integer constants are inadequate to


represent quantities that vary continuously.

 These quantities are represented by numbers containing fractional parts like 26.082. Example
of real constants is

0.0026
-0.97
435.29
+487.0

Real Numbers can also be represented by exponential notation. The general form for
exponential notation is mantissa exponent. The mantissa is either a real number expressed in decimal
notation or an integer. The exponent is an integer number with an optional plus or minus sign.

2. CHARACTER CONSTANTS:
(i) Single Character Constants

A Single Character constant represent a single character which is enclosed in a pair of quotation
symbols. Example for character constants are

'5'
'x'
';'
‘’
All character constants have an equivalent integer value which is called ASCII Values.

Character M Y ” a g e i s
#
ASCII Code 77 121 34 97 103 101 35 105 115

Character % 2 blank ( t w o ) @

ASCII Code 37 50 32 40 116 119 41 41 64


(ii) String Constants

A string constant is a set of characters enclosed in double quotation marks. The characters in a
string constant sequence may be a alphabet, number, special character and blank space. Example of
string constants are
"VISHAL"
"1234"
"God Bless"

Rules for String constant :


 String constant must be a single alphabet, special character or sequence of
alphabets or digits enclosed in double quotes.
 Every string constant ends with NULL character. It is automatically assigned.

E.g:- Valid “Manakula Vinayagar institute of Technology”


Invalid ‘school’

3. SYMBOLIC CONSTANT

It represent numeric/character string constant. It is defined as follows.


#define<scname><sctext>.
Here scname stands for Symbolic Constant name and sctext stands for Symbolic
Constant text. scname is usually written in capital letters.
Example
#define PI 3.14
const int pi=3.14

2.7 VARIABLES

 A variable is a data name that may be used to store a data value. Unlike constants that
remain unchanged during the execution of a program, a variable may take different
values at different times during execution. It is a memory location used to store a data
value.
 Variables can be of different data types. The data types are integers, real or character
constants
 A variable name consists of alphabets, digits and underscores character.
Rules for defining variables:
1. The variable name should not start with a digit
2. White space is not allowed
3. The length of a variable must not be more than 8 characters
4. A variable should not be a Keyword
5. The variable names may be a combination of upper and lower characters.

Example of variable names are

Sun
number
Salary
Emp_name
average1

Examples of Invalid Variable names are

123
(area)
6th
%abc

2.7.1 DECLARATION OF VARIABLES:

 A variable is a named location in memory, used to store a value of any data type, that can
be modified by the program.
 All variables must be declared before they are used in the program.
Basic data type declaration

Syntax: data-type v1, v2, v3… ..... vn;


Example: int n1, n2, n3, sum;
 data-type is one of the data types such as int, char,
float or double.
Description  v1, v2, v3…….vn are variable names which are
separated by commas.
Assigning Values to variables

Values can be assigned to variables using the assignment operator = as follows


Variable name = constant;
Example: initial_value = 0;
final_value = 100;
balance = 75.84;
yes = ‘x’;

2.4 DATA TYPES:


C language is rich in its data types. Storage representations and machine instructions
to handle constants differ from machine to machine. The variety of data types available allows
the programmer to select the appropriate to the needs of the applications as well as the
machine.

Data Type is a term refers to a kind of data used in a program. The data types
supported in a language dictates the type of values.
C consists of three classes of data types
1. Primary data type
2. User defined data type
3. Derived data types
PRIMARY DATA TYPES
All C compilers supports four primary data types namely.
1. Character data type represented as char
2. Integer data type represented as Int
3. Floating point data type reprinted as float
4. Double
5. void

1. CHARACTER DATA TYPE


 A character data type is used to define a single individual character using the
keyword char.
 The char data type generally requires 1 byte (8 bit) of memory of their storage.
 The char data type can modified by using the qualifier Signed & unsigned.

Name C Representation Size Range Format Delimiter


(bytes)
Character char 1 -128 to 127 %c
Signed Character signed char 1 -128 to 127 %c
Unsigned Character unsigned char 1 0 to 255 %c

2. INTEGER DATA TYPE


 Integer data type is used to define a number using the keyword int.
 Memory requirement for storing an integer value is 1 or 2 bytes.
 The integer data can be modified by using qualifier signed, unsigned, short and
long.

Name C Representation Size Range Format


(bytes) Delimiter
Integer int 2 -32768 to 32767 %d
Short Integer short int / short 2 -32768 to 32767 %d
Long Integer long int / long 4 -2147483648 to 2147483647 %ld
Signed Integer signed int 2 -32768 to 32767 %u
Unsigned Integer unsigned int 2 0 to 65535 %d
Signed Short Integer unsigned short int / 2 -32768 to 32767 %d
short
Unsigned Short unsigned short int / 2 0 to 65535 %u
Integer short
Signed Long Integer signed long int / long 4 -2147483648 to 2147483647 %ld
Unsigned Long unsigned long int / long 4 0 to 4294967295 %lu
Integer

3. FLOATING POINT DATA TYPE


 C clears with several kinds of numbers. Real numbers, which are used frequently, are
called as floating-point numbers.
 Floating-point data types store numerical values with a fractional portion.
 Usually occupy 4 bytes(32 bits) for their storage these are known as Single precision
numbers
 When the range provided by a float data type is not sufficient double data type is used
to define a number.
 Double data type represents the same data type that float represents but with a greater
precision (size) hence it requires 8 bytes of their storage in the memory these are known
as double precision numbers.
 To increase the precision (size) further we can use long double which uses 10 bytes for
their storage. These are known as extended precision numbers.


Name C Representation Size Range Format


(bytes) Delimiter
Float float 4 3.4 e-38 to 3.4 e+38 %f
Double double 8 1.7e-308 to 1.7e+308 %f
Long Double long double 10 3.4 e-4932 to 3.4 e+4932 %lf


EMPTY DATA TYPE
VOID is the empty data type. This data type is used before main function in a C
Language. The word void refers no return data type. It is used before the main function to
specify the type of function. If a function is of type void it does not return any value to the
calling function.

USER DEFINED DATA TYPES:


C Supports a feature known as type definition on that allows the user to define new
data types that are equivalent to existing data type.
TYPE DEFINITION:
 The keyword type def is used to define new data type names. Note that you are not
actually creating a new data type, but rather defining a new name for an existing data
type.
 The general form or the syntax of defining a new data type is

Syntax: typedef data-type identifier;

Example: typedef int integer;


 typedef is a keyword for typedefinition.
 data-type refers to an existing data type.
Description  identifier new name given to the existing
data type.

Example:
 typedef int integer;
 typedef float floating-point;
 typedef char character;
Where
 integer symbolizes int.
 character symbolizes char.
 floating-point symbolizes float.
 they can later used to declare variables as
 character c1, c2;
 integer int1, int2, int3, total;
 floating-point r1, r2, rate;
 The main advantage of type definition is that, you can create meaningful data type
names for increasing the readability of the program.

ENUMERATED DATA TYPE:


 The enumerated data type is a user-defined data type.
 An enumeration is a set of named integer constants represented by identifier that
specifies all the legal values a variable of that type may have.
 Enumerated data type is declared using the enum keyword.
Syntax: enum tag{ member1, member2,........ member n };

Example: enum months{ January, February, march……December};


 enum is the key word,
 tag is the name that identifies enumeration having the
Description composition in the format.
 member1, member2, …...member n are the individual
identifiers (known as enumeration constants) that may be
assigned to the variables of this type.

TYPE CONVERSION

 When an operator has operands of different data types, it is in mixed mode.


 C supports the use of mixed mode operations in arithmetic expressions. Normally,
before an operation takes place both the operands must have the same type.
 C converts one or both the operands to the appropriate data types by the type conversion
Type conversion can be achieved by any one of the following methods.

1. Implicit type conversion


2. Explicit type conversion
The classification of type conversion is shown
Type Conversion

Implicit Explicit

Automatic Assignment

1. IMPILICIT TYPE CONVERSION

 In the case of implicit type conversion one data type is automatically converted into
another type as per the rules described in the C language,
 There are two types of implicit type conversion
1. automatic type conversion and
2. assignment type conversion

AUTOMATIC TYPE CONVERSION


 In automatic type conversion, the data type having lower rank is converted
automatically into higher rank data before the operation proceeds. The result is of the
data type having higher rank.

Data Type Rank


long double 1 (Higher rank)
double 2
float 3
int 4
short int 5
char 6 (Lower rank)

ASSIGNMENT TYPE CONVERSION


 If the two operands in an assignment operation are of different data types, the right side
operand is automatically converted to the data type of the left side.
 Whenever the type of the left operand has lower rank than the type of the right operand,
the result of the assignment is less precise than the actual value. This is known as
downward type conversion.
 If the left operand is int type and the right operand is float type, any fractional part of the
right side value is truncated and its integral part only is assigned. But, when a double type
is assigned to a float type, the value may be rounded or truncated based on the
implementation.

Left operand Right operand Conversion rule


type type
float double Truncate/Round and truncate
long float Truncate fraction
int long Truncate higher order bit
int float Truncate fraction
Short int Truncate higher order bit
char short Truncate

2. EXPLICIT TYPE CONVERSION


 Scalar data type can be explicitly converted into desired data type .This a feature is
known as coercion.
 It is accomplished by using the cast operator. The general cast operation is given below

(data type) expression

Where expression is converted to the target data_type enclosed within the parentheses. The
expression may be a constant or a variable. The data type must be any scalar type or void. If
it is void, the operand must be other the void type expression. The name of the data type to
which the conversion is to be made is enclosed in parentheses and placed directly to the left of
the expression

Cast operator Existing Conversion rule


type
int char Converted to int if an int can represent all values of the
given char type; otherwise the type is unsigned int.
short signed int signed int If the range of signed int fits in the range of short signed
int, the value is unchanged; otherwise the result is
implementation-defined

2.5 OPERATORS AND EXPRESSIONS:


An operator is a symbol that tells the computer to perform certain mathematical and logical
manipulations. Operators are used in programs to manipulate data and variables. Such as, ++,
--, <, > etc.
C has a rich set of operators which can be classified as
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operator
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
i. Comma operator
ii. Sizeof operator
ARITHMETIC OPERATORS
There are two types of arithmetic operators,
1. Binary operators
2. Unary operators
1. Binary Operators: These arithmetic operators are used for numerical calculations between
two constant values.
2. Unary Operators: Unary operators are increment operator (++), decrement operator (--) and
minus (-).

Sl.
OPERATOR MEANING
No.
1 + Addition or unary plus A+B
2 - Subtraction or unary minus A-B
3 * Multiplication A*B
4 / Division A/B
5 Modulo division or A%B
%
remainder after division

RELATIONAL OPERATORS
 These operators are used to distinguish between two values depending on their relations.
 These operators provide the relationship between the two expressions. Often it is required to
compare the relationship between operands and bring out a decision and program accordingly.
 This is when the relational operator come into picture. C supports the following relational
operators.
Table given below shows the relational operators,
OPERATOR MEANING
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
 The general format for relational expression is

Syntax: variable1 relational operator Variable2;

variable1 and variable2 may be numeric values or


numeric expressions.
Description:
relational operator refers to any one of the relational
operators.

1. 6.5 <= 25 TRUE


Example: 2. -65 > 0 FALSE
3. 10 < 7 + 5 TRUE

Relational expressions are used in decision making statements of C language such as if,
while and for statements to decide the course of action of a running program.

LOGICAL OPERATORS
C has the following logical operators, they compare or evaluate logical and relational
expressions.

OPERATOR MEANING
&& Logical AND
|| Logical OR
! Logical NOT

Logical AND (&&)


This operator is used to evaluate 2 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.

Example:

a > b && x = = 10
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.

Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if
any one of the 2 expressions is 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. It
evaluates to true if a is less than either m or n and when a is less than both m and n.

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.

Example: (x >= y) the NOT expression evaluates to true only if the value of x is neither greater
than nor equal to y.

ASSIGNMENT OPERATOR
Assignment is the most commonly used operation to assign either a value or result of an
expression to a variable.

OPERATOR MEANING
= Equal to
+= Addition or equal to
-= Subtraction or equal to
*= Multiplication or equal to
/= Division or Equal to
%= Modulo division or equal to

Syntax: Variable_ name = expression;


variable_name is any variable or identifier,
Description: Expression may be any expression, a constant, a
variable or the combination of all the three.
a=a+1
a=a-1
Example: a=a*(n+1)
a=a/(n+1)
a=a%b
INCREMENT AND DECREMENT OPERATORS

Increment Operators
It is used to increase the value of the Operand by 1. There are two types of Increment
Operators in C Language. They are pre Increment operator and post Increment operator.

Pre Increment Operator


It is used to increase the value of the variable by 1. Here the value of 1 is added to the
variable first along with the given variable value.
Eg: ++g -> pre increment

Post Increment Operators


It is used to increase the value of the variable by 1. Here the value of 1 is added to the
variable first along with the given variable value.
Eg: g++ -> post increment

Decrement Operators
It is used to decrease the value of the Operand by 1. There are two types of Decrement
Operators in C Language. They are pre decrement operator and post decrement operator.
Pre decrement Operator
It is used to decrease the value of the variable by 1. Here the value of 1 is subtracted
to the variable first along with the given variable value.
Eg: --g ------> pre decrement
Post Decrement Operator
It is used to decrease the value of the variable by 1. Here the value of 1 is subtracted
to the variable first along with the given variable value.
Eg: g-- ----> post Decrement
S.No Operator type Operator Description
1 Pre increment ++i Value of i is incremented first then incremented is
2 Post-increment i++ Value is assigned to the variable first and then
3 Pre decrement – –i Value of i is decremented first then incremented is
4 Post decrement i– – Value is assigned to the variable first and then
Assigned value get decremented.
CONDITIONAL OPERATORS
 An expression that evaluates conditions are called as conditional expressions.
 The operator used to evaluate conditional expression is called as a conditional operator
Denoted by (? :).

Syntax: Expression 1? Expression 2: expression 3;


If expression 1 is true,
Expression 2 alone evaluated,
Description:
If expression 1 is false;
Expression 3 alone evaluated.
r = (p < q)? p : q
p = 25
q = 40
Example:
(p<q) is evaluated first
if p less than q then p is assigned to r
otherwise q is assigned to r.

Example program for conditional/ternary operators in OUTPUT:


C: x value is 1
#include <stdio.h> y value is 1
int main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}

BIT WISE OPERATORS


Bit wise operator is used to manipulate with bits within a word of memory. Bit wise
operator operates only on integer and character but not on float and double.
OPERATOR MEANING
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement
Bitwise AND (&):

This operator is represented as ‘&’ and operates on two operands of integer type.
Eg:
x = 7 = 0000 0111
y = 8 = 0000 1000
x&y = 0000 0000

Bitwise OR (|)
Similar to AND operator in all aspects, but this operator gives if either of the operand
bit is ‘1’ then result is ‘1’ or both operands are ‘1’ s then also given ‘1’.
Eg:
x = 7 = 0000 0111
y = 8 = 0000 1000
x|y = 0000 1111

One’s Complement Operator ( ~ )


One’s Complement makes the bits of operand inverted. Here one becomes zero and zero
becomes one.
Eg: x = 7 i.e., x = 0000 0111
One’s complement of t is 248 ( i.e., ~x = 1111 1000 = 248 )

Left shift Operator ( << )


Left shift operator ( << ) shifts each bit of the operand to left. The general form is
Variable << number of bit positions
Eg: x =7 ( i.e., 0000 0111 = 7 )
y = x <<1 is 14. ( i.e., 0000 1110 = 14 )

Right shift Operator ( >> )


Right shift operator shifts each bit of the operand to right. The general form is
Variable >> number of bit positions
Eg: x = 7 ( 0000 0111 = 7 )
y = x >> 1 is 3 ( i.e., 0000 011 = 3 )
SPECIAL OPERATORS:
C supports some special operators of interest such as comma operator, sizeof
operator, pointer operators (& and *) and member selection operators (. And ->).

i) COMMA OPERATOR:
The comma operator can be used to link the related expressions together. A comma- linked
list of expressions is evaluated left to right and the value of right-most expression is the value
of the combined expression. For example, the statement
Value = (x = 10, y = 5, x+y)
First assigns value 10 to x, then assigns 5 to y, and finally assigns 15 to value. Since comma
operator has the lowest precedence of all operstors, the parentheses are necessary.

ii) SIZE-OF OPERATOR:


This operator is used to return the size of string or character. It cannot be used in
together with Integers.
The syntax is
sizeof(variable-name);

Example:

The program employs different kinds of operators. The results of their


evaluation are also shown for comparison. (Illustration of Operators)
main()
{
int a, b, c, d;
a = 15;
b = 10;
c = ++a - b;
printf("a = %d b = %d c = %d\n",a, b, c);
d = b++ +a;
printf("a = %d b = %d d = %d\n",a, b, d);
printf("a/b = %d\n", a/b);
printf("a%%b = %d\n", a%b);
printf("a *= b = %d\n", a*=b);
printf("%d\n", (c>d) ? 1 : 0);
printf("%d\n", (c<d) ? 1 : 0);
}
Output:
a = 16 b = 10 c = 6
a = 16 b = 11 d = 26
a/b = 1
a%b = 5
a *= b = 176
0
1

EVALUATION OF EXPRESSIONS

An arithmetic expression is a combination of variables, constants, and operators


arranged as per the syntax of the language.
Expressions are evaluated using an assignment statement of the form
variable = expression;
ALGEBRAIC EXPRESSION EQUIVALENT C EXPRESSION
3.14x r2 3.14 * r * r
a/bc a / (b * c)
5a2 + 3a + 1 5*a*a+3*a+1
s(s-a)(s-b)(s-c) s * (s - a) * (s - b) * (s - c)

The program illustrates the use of variables in expressions and their


evaluation.
main()
{
float a, b, c, x, y, z;
a = 9;
b = 12;
c = 3;
x = a - b / 3 + c * 2 - 1;
y = a - b / (3 + c) * (2 - 1);
z = a -(b / (3 + c) * 2) - 1;
printf("x = %f\n", x);
printf("y = %f\n", y);
printf("z = %f\n", z);
}
Output:
x = 10.000000
y = 7.000000
z = 4.000000

PRECEDENCE OF OPERATORS

Precedence level or priority of operators

Precedence refers to what comes first. Several operators may appear in one
expression. It is important to know the order in which they are executed. Execution tekes
place according to certain predefined rules, known as hierarchy rules. These rules specify
the order of execution, known as precedence level or priority of operators.

OPERATOR DESCRIPTION ASSOCIATIVITY RANK


() Function call
[] Array element reference Left to Right 1
-> and . Structure operators
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical negation Right to left 2
~ One’s complement
* Pointer reference
& (indirection)
sizeof Address
(type) Size of an object
Type cast (conversion)
* Multiplication
/ Division Left to Right 3
% Modulus
+ Addition Left to Right 4
- Subtraction
<< Left shift Left to Right 5
>> Right shift
< Less than Left to Right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equality Left to Right 7
!= Inequality
& Bitwise AND Left to Right 8
^ Bitwise XOR Left to Right 9
| Bitwise OR Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
?: Condition expression Right to left 13
= 14
*=
/=
%=
+=
-= Assignment operators Right to left
&=
^=
|=
<<=
>>=
, Comma operator Left to Right 15

INPUT AND OUTPUT FUNCTIONS

We know that input, process, output are the three essential features of computer
program. The program takes some input data, processes it and gives the output.
We have two methods for providing data to the program
 Assigning the data to the variable in a program
 By using the Input/output statements

In ‘C’ language, two types of Input/output statements are available, and all input and
output operation are carried out through function calls. Several functions are available for
input/output operations in ‘C’. These functions are collectively known as the standard I/O
library.
1. Unformatted Input/output Statements
2. Formatted Input/output Statements
Unformatted Input/output Statements
These statements are used to Input/output a single/group of characters form/ to the
input/output devices. Here the user cannot specify the type of data that is going to be
input/output.
The following are the unformatted Input/Output statements available in ‘C’

Input Output

getchar() putchar()

getch() putch()

gets() puts()

i) Single Character Input-getchar( ) function


A Single character can be given to the computer using ‘C’ input library function getchar()

Syntax char variable=getchar();

Description char : datatype;


variable : Any valid ‘C’ variable

Example char x; x=getchar();

 The getchar() function is written in standard I/O library. It reads a single character
from a standard input device. This function do not require any arguments, through a
pair of empty parentheses, must follow the statements getchar().
 The first statement declares x as a character type variable. The second statement causes
a single character to be entered from the standard input device and then assigned to
variable x.
Example Program:
The program displays a question of YES/NO type to the user and reads the user's
response in a single character (Y or N). If the response is Y, it outputs the message

My name is BUSY BEE

Otherwise, outputs.

You are good for nothing

Note there is one line space between the input text and output message.

ii) Single Character Output-putchar() function


The putchar() function is used to display one character at a time on the standard output
device. This function does the reverse operation of the single character input function as
discussed above.

Syntax putchar(character variable);

Description Character variable is the valid ‘C’ variable of the type of char data
type

Example char x; putchar(x);

iii) The getc() function


This is used to accept a single character from the standard input to a character variable

Syntax character variable=getch();

Description Character variable is the valid ‘C’ variable of the type of char data
type

Example char c; c=getch();

iv) The putc() function


This is used to display a single character in a character variable to standard output
device.
Syntax putch(character variable);
Description Character variable is the valid ‘C’ variable of the type of char data
type

The getc() a nd putc()


Example char c;function are often used in file processing
putch(c);

v) String Input - gets() function


The gets() function is used to read the string (string is a group of characters) from the
standard input device (keyboard)
vi) String Output - puts() function
The puts() fu nction is used to display/write the string to the standard output device.
 The gets() and puts() function are similar to scanf() and printf() function but the
difference is in the case of scanf() input statement, when there is a blank space in input
text, then it takes the space as an ending of the string the remaining string are not been
taken.

Syntax gets(char type of array variable)


Description Valid ‘c’ variable declared as one dimension char type

Example gets(s);

Syntax puts(char type of array variable)


Description Valid ‘c’ variable declared as one diamension char type

Example put(s);

FORMATTED INPUT/OUTPUT STATEMENTS


Formatted Input/output refers to input and output, that has been arranged in a
particular format.This line contains two parts of data that is arranged in a format, such
data can be read to the format of its appearance, as the first data should be read into a
variable char, the second into int. Such operation can be made possible in ‘C’
language by using the formatted Input/output statements. Using these statements, the
user must specify the type of data, that is going to be accessed (Input/output)
The following are the formatted Input/output statements

Input Output
scanf() printf()
i) The scanf() function
Input data can be entered into the computer using the standard input ‘C’ library function
called scanf(). This function is used to enter any combination of input.
The scanf() function is used to read information form the standard input
device(keyboard), scanf() function starts with a string arguments and may contain
additional arguments. Any additional argument must be pointer

Syntax scanf(“control string”,&var1,&var2,……&varn);

The Control String consists of character groups, Each character group


Description must begin with a percentage sing ‘%’. The character group contains
percentage sign, followed by conversion character as specified in
table below.
var1,var2….varn – are the arguments or variables in which the data
is going to be accepted

Example int n;
scanf(“%d”,&n);

Rules for writing scanf() function


1. The control string must be preceded with (%) sign and must be within quotations, i.e.,
the address of variable should be passed.

2. If there is an number of input data items, items must be separated by commas and
must be preceded with (&) sign except for string input
3. The control string and the variables going to input should match with each other
4. It must have termination with semicolon
5. The scanf() reads the data values until the blank space in numeric input or maximum
number of character have been read or an error is detected

ii) The printf() function


Output data or result of an operation can be displayed from the computer to a standard
output device using the library function printf(). This function used to output any
combination of data. It is similar to the input function scanf(), except that it display data
rather than input.
Syntax printf(“control string”,var1,var2,……varn);

Control string is any of the following.


a) Format code character
b) Execution character set or Escape sequences
c) Characters/String that will be displayed
Description var1,var2,varn are the arguments or variables from which the data is
going to output. Here the variables need not to be preceded with ‘&’
sign.

Example printf(“Result is ….%d”,n);


printf(“%f”,f);
printf(“%s”,s);

Rules for writing printf() function


1. Place appropriate heading in the output
2. The variables must be separated by commas, and need not be preceded with ‘&’ sign
3. The control string and the variables must match in their order
4. The control string must be in quotations and there we can also use any other text to
print with data
5. Provide blank space in between the numbers for better readability
6. Print special messages wherever required in output

CONTROL STRING:
 It is the type of data that the user going to accept via the input statements, this can be
formatted and always preceded with a ‘%’ sign. The below table illustrates code formats
(control strings) in Input/output statements.
 Each variable name (argument) must be preceded by an ampersand (&). The (‘&’) symbol
gives the meaning “address of” the variable.
 The scanf control string or placeholder consists of % at the beginning and type indicator at
the end. Apart from that it can have *, a maximum field width indicator and a type indicator
modified.
FORMAT TYPE OF
INPUT
SPECIFIER ARGUMENT
%c Character Reads a single character
%d or %i Integer Reads a decimal integer
%e or %E or Floating point Reads a floating point value
%f or %g or
%G
%hd or %hi Short integer Reads decimal short integer
%hu Short integer Reads decimal unsigned short integer
%ld or %li Long integer Reads decimal long integer
%le or %lf or Double Reads signed double
%lg
%Le or %Lf Long double Reads signed long double
or %Lg
%lo Long integer Reads an octal long integer
%lu Long integer Reads decimal unsigned long integer
%lx Long integer Reads hexadecimal long integer
%o Octal integer Reads an unsigned octal integer
%s Sequence of Reads a string
characters
%u Integer Reads an unsigned decimal integer
%x or %X Hexadecimal Reads a unsigned hexadecimal integer
integer

The character tests functions and their tests.

In the following table the required functions and their tests are given.

Function Test
isalnum(c) Is c an alphanumeric character?
isalpha(c) Is c an alphabetic character?
isdigit(c) Is c a digit?
islower(c) Is c a lower case letter?
isprint(c) Is c a printable character?
ispunct(c) Is c a punctuation mark?
isspace(c) Is c a white space character?
isupper(c) Is c an upper case later?

DIFFERENCE BETWEEN SCANF AND PRINTF FUNCTION.

Sl. no. Scanf printf


1. Used to accept data Used to display data

2. Control string and & operator is Control string only used.


used
3. It end with semicolon It end with semicolon
Number of input specified with Number of input specified with format
4. format String and enclosed string and separated by commas.
within double quotes.
The Input variables are The output variables are specified by
specified using Address their name and separated by commas.
operator (&) is separated by
commas.

DIFFERENCE BETWEEN GETCHAR() AND GETS()


Sl. no. getchar() gets()
Used to receive a single Used to receive a string with white spaces and
1.
character blanks
Does not require any It require a single argument
2.
argument

DIFFERENCE BETWEEN SCANF() AND GETS()


Sl.
scanf() gets()
no.
Strings with white spaces cannot be Strings with any number of spaces
1.
accessed until ENTER key is pressed can be accessed
Spaces and tabs are not acceptable as a part Spaces and tabs are acceptable as a
2.
of the input string part of input string.
Can receive any number of characters and Only one string can be received at a
3.
integers. time.
Format string and input variable name is Format string and address is
4.
specified. specified.
All data types can be accessed Only character data types can be
5.
accessed

DIFFERENCE BETWEEN PUTS() AND PRINTF()

Sl.
puts() printf()
no.
It can display only one It can display any number of characters, integers or
1.
String at a time. Strings at a time.
All data types are Each data type is considered separately, depending upon
2.
Considered as characters. The conversion specifications.

ESCAPE SEQUENCES (BACKSLASH CHARACTER CONSTANTS)

ASCII Escape
Sl. no Meaning
Value Sequences
1. 000 \0 Null
2. 007 \a Audible alter (bell)
3. 008 \b Backspace
4. 009 \t Horizontal tab
5. 010 \n New line
6. 011 \v Vertical tab
7. 012 \f Form feed
8. 013 \r Carriage return
9. 034 \” Double quote
10. 039 \’ Single quote
11. 063 \? Question mark
12. 092 \\ Backslash

CONTROL STATEMENTS

In a program all the instructions are executed sequentially by default, when no


repetitions of some calculations are necessary. In some situation we may have to change the
execution order of statements based on condition or to repeat a set of statements until
certain conditions are met. In such situation Conditional and Control statements are very
useful

‘C’ language provides four general categories of control statements

i) Sequential structure: in which instructions are executed in sequence

Ex: i=i+1;
c=a+b;

ii) Selection structure: here the sequence of the instructions are determined by using
the result of the condition
Ex: if(x>y)
i=i+1;
else
j=j+1;

iii) Iteration Structure: in which statements are repeatedly executed. These forms
program loops.

Ex: for(i=1;i<=5;i++)
{
i=i+1;
}

iv) Encapsulation structure : in which the other compound structures are included
Ex: we can include an if statement in a for loop or a for loop in a if statement.

DECISION MAKING STATEMENTS

In practice, users may have a number of situations where they may have to change the
order of statements based on certain conditions. This is decision making. C language
possesses such decision making capabilities by supporting the following statements :
Decision making with if Statement
 It is used to control the flow of execution of the statements and also used to test
logically whether the condition is true or false.

 It is always used in conjunction with condition. This statement is used when a


question requires answer.
 The different forms are :
1. Simple if statement
2. If …..else statement
3. Nested if …else statement
4. Else if ladder
SIMPLE IF STATEMENT

SYNTAX FLOWCHART

if (test expression)

{
Statement-block;

}
Statement-x;

If statement executes if the given condition is true otherwise it does not produces any
output.

Example: The following program illustrates the use of if statement.


Program to check whether the entered number is less than 10
#include<stdio.h>
main()
{
int i; /* Local definition */
/* Statement */
printf("\nEnter the number < 10.... ");
scanf("%d",&i);
if(i<10)
printf("\nThe entered number %d is < 10", i);
} /* main */

Output:

The entered number 5 is < 10


IF … ELSE STATEMENTS

 This is basically two way decision making statement and always used in Conjunction
with condition.
 It is used to control the flow of execution and also used to carry out the logical test and
then pick up one of the two possible actions depending on the logical test.

SYNTAX FLOWCHART
if (test expression)
{
True-block
statements;
}
else
{
False-block
statements;
}
Statement-x
In these statement both if part and else part will not be executed at the same time.
Either anyone of the both will be executed during run time.

Example: The following program illustrates the use of if-else statement.


Program to check whether the entered number is less than 10
#include<stdio.h>
main ()
{
int i; /* Local definition */
/* Statement */
printf("\nEnter the number < 10. ... ");
scanf("%d",&i);
if(i<10)
printf("\nThe entered number %d is < 10", i);
else
printf("\nThe entered number %d is > 10", i);
} /* main */

Output:

The entered number 5 is < 10


The entered number 15 is > 10
NESTED…IF … ELSE STATEMENTS
 If more than one if else statement is used then it is nested if-else statement.
 The if statement may itself contain another if statement is known as nested if
statement.

SYNTAX FLOWCHART

Example: Program to check whether largest of three number


(The following program illustrates the use of nested if-else statement.)
#include<stdio.h>
main()
{
float A, B, C;
printf("Enter three values\n");
scanf("%f %f %f", &A, &B, &C);
printf("\nLargest value is ");
if (A>B)
{
if (A>C)
printf("%f\n", A);
else
printf("%f\n", C);
}
else
{
if (C>B)
printf("%f\n", C);
else
printf("%f\n", B);
}
}

Output:
Enter three values
23445 67379 88843

Largest value is 88843.000000


THE ELSE IF LADDER :
 When a multipath decision is involved then we use else if ladder. A multipath
decision is a chain of ifs in which the statement associated with each else is an if.
 This construct is known as the else if ladder. The conditions are evaluated from the
top, downwards.

SYNTAX FLOWCHART

Example: USE OF else if LADDER


An electric power distribution company charges its domestic consumers as follows:
Consumption Units Rate of Charge
0 - 200 Rs. 0.50 per unit
201 - 400 Rs. 100 plus Rs.0.65 per unit excess of 200
401 - 600 Rs. 230 plus Rs.0.80 per unit excess of 400
601 and above Rs. 390 plus Rs.1.00 per unit excess of 600
The program reads the customer number and power consumed and prints the amount
to be paid by the customer.
main()
{
int units, custnum;
float charges;
printf("Enter CUSTOMER NO. and UNITS consumed\n");
scanf("%d %d", &custnum, &units);
if (units <= 200)
charges = 0.5 * units;
else if (units <= 400)
charges = 100 + 0.65 * (units - 200);
else if (units <= 600)
charges = 230 + 0.8 * (units - 400);
else
charges = 390 + (units - 600);

printf("\n\nCustomer No: %d: Charges = %.2f\n",


custnum, charges);
}
Output:
Enter CUSTOMER NO. and UNITS consumed 101 150
Customer No:101 Charges = 75.00

Enter CUSTOMER NO. and UNITS consumed 202 225


Customer No:202 Charges = 116.25

Enter CUSTOMER NO. and UNITS consumed 303 375


Customer No:303 Charges = 213.75

Enter CUSTOMER NO. and UNITS consumed 404 520


Customer No:404 Charges = 326.00

Enter CUSTOMER NO. and UNITS consumed 505 625


Customer No:505 Charges = 415.00

SELECTION STATEMENT

SWITCH STATEMENT:

 Selection statement allows user to select a particular group of statements from


several groups.
 ‘switch’ statement is one of the selection statement.
 It uses case, break and default keywords within it.
 Selection statement starts with the keyword ‘switch’.
SYNTAX FLOWCHART

switch(expression)
{
case value-1:
block1;
break;
case value-2:
block-2;
break;

……………………………………

……………………………………
default:
default-block
break;
}
Ststement-x;

 Here switch is the keyword. Expression may be an integer, character or string.


 If the expression is string it is not specified within double quotes. The value type will
be based on the type of expression. Value acts as a label. Here value1, value2,………
are known as label.
 Label ends with colon ‘:’.
 When switch statement is executed value of expression (int, char, string) is compared
with the value. If it matches corresponding case value will be executed. If it does not
match then default-block will be executed.
 Break statement is used to terminate from the switch-case statement. If any of the
given block-1, block-2…. is true then default-block will be executed.
 Expression type and value must match each other.

Example: C program to count the number of vowels and digits in a given string
using switch case statement.
(The following program illustrates the use of switch statement.)
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
char ch;
int digits, vowels=0;
clrscr();
printf("Enter a string with digits\n");
while((ch=getchar())!='\n')
{
switch(ch)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
digits++;
break;
case 'a':case 'A':
case 'e':case 'E':
case 'i':case 'I':
case 'o':case 'O':
case 'u':case 'U':
vowels++;
break;
}
}
printf("\n No. of vowels in the given string %d",vowels);
printf("\n No. of digits in the given string %d",digits);
getch();
}
Output:
Enter a string with digits
engineering 123456
No. of vowels in the given string 5
No. of digits in the given string 6

3. LOOPING AND BRANCHING

What is a loop ?
 In some situations there is a need to repeat a set of instructions in specified number
of times or until a particular condition is being satisfied. These repetitive operations
are done through a loop control structure.
 The loop is defined as the block of statements which are repeatedly executed for
certain number of times.
 The loop in a program consists two parts,
 one is body of the loop and
 another one is control statement.
 The control statement is used to test the condition and then directs the repeated
execution of the statements in the body of the loop.
 Any looping statement would include the following steps:
i) Initialization of a condition variable
ii) Test the control statements
iii) Executing the body of the loop depending on the condition
iv) Updating the condition variable

Entry controlled and exit controlled loops


Depending on the position of the control statement in the loop, a control structure can
be classified into two types; entry controlled and exit controlled. They are described below.
Entry controlled loop :
 The types of loop where the test condition is stated before the body of the loop, are
known as the entry controlled loop.
 If the test condition is true, then the loop gets the execution, otherwise not. For example,
the for loop is an entry controlled loop. In the given figure, the structure of an entry
controlled loop is shown.
Exit controlled loop :
 The types of loop where the test condition is stated at the end of the body of the loop,
are know as the exit controlled loops.
 If test condition is true, then the loop gets repeated till the result of the test condition is
not false. For example, the do statement or the do.... while loop is an exit controlled loop.
The structure of an exit controlled loop is given in the given figure.
The following are the loop structures available in ‘C’

while loop
do-while loop
for loop.

Comparison of for, while and do-while structures.

For loop While loop Do.... while loop


for(n = 1; n <= 10; n++) n = 1; n = 1;
{ while(n <=10) do
======== { {
======== ========== ========
} ========== ========
n=n+1; n = n + 1;
} }
while(n<=10);
While loop:
 In some situation there is a need to repeat a set of instruction in specified number of
times or until a particular condition is being satisfied.
 It is a repetitive control structure, used to execute the statement within the body
until the condition becomes false.

The general form of while statement is


while( test condition)
{
body of the loop;
}

Next statement
 While statement executes only if the given condition is true.
 If it is not true the next statement will be executed.
 If there is only one while statement then there is do need for having curly braces.
 The execution of while statement comes to end when the condition becomes false.
 Therefore while loop must be finite.
 While loop is also called entry-controlled loop. Entry-controlled loop also
known as pre-test

Example: The following program illustrates the while statement.

#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,sum=0 ; /* Local definitions */
/* Statements */

while (i <= 10)


{
sum =sum+i;
i++;
} /* while */
printf ("The sum of number upto 10 is %d",sum);
getch();
} /* main */

Output :
The sum of number upto 10 is 55

do…while Loop
 In do while loop, statement is executed first then the condition is checked. If the
given condition is not true at-least one statement will be definitely executed.
 If the condition is true then the while loop will be executed and corresponding
statements will be displayed as output.
 In do-while loop condition is terminated (or) ends with semicolon. Even if the given
condition is true or false do-while loop executes atleast once in the program.

The syntax of the do while loop is:


do
{
statement;
}
while(expression);

 Here the statement is executed, then expression is evaluated.


 If the condition expression is true then the body is executed again and this process
continues till the conditional expression becomes false.
 When the expression becomes false the loop terminates.
 do-While loop is also called exit-controlled loop. Entry-controlled loop also known
as post-test.

Example: The following program illustrates the do-while statement.


#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,sum=0 ; /* Local definitions */

/* Statements */

do
{
sum =sum+i;
i++;
} while (i<=10);
printf ("The sum of number upto 10 is %d",sum);
getch();
} /* main */
Output :
The sum of number upto 10 is 55

The for Loop

 The for loop is another repetitive control structure, and is used to execute set of
instructions repeatedly until the condition becomes false.
General form: for (initialization; test condition; increment/decrement)
{
program statement;
}
Explanation: 1. Initialization: is used to initialize counter variable

2. Test condition : is used to test the condition

3. Inc/Dec : counter is used to increment or decrement counter


variables

 Here initialization is done in the beginning of the for loop. It is done using the
assignment operator ‘=’.
 Test condition is the place where the given condition is being checked. Condition is
checked every time using the initialization value.
 Based on the condition initialized value will be incremented/decremented.
 If the initialization value and test condition value does not match the loop gets
terminated and statements will not be executed.
 for loop executes until the test condition is true. When it becomes false the loop
terminates. Both increment and decrement is possible in a for loop.

Example: Program to calculate the square of the given numbers


(The following program illustrates the for statement.) LAB PROGRAM
#include<stdio.h>
void main()
{
int i, s;
printf("The squares of 1 to 10 is given below:");
for(i=1;i<=10;i++)
{
s=i*i;
printf("\n\t SQUARE OF %d is %d ", i,s);
}
}
Output :
The squares of 1 to 10 is given below
SQUARE OF 1 is 1
SQUARE OF 2 is 4
SQUARE OF 3 is 9
SQUARE OF 4 is 16
SQUARE OF 5 is 25
SQUARE OF 6 is 36
SQUARE OF 7 is 49
SQUARE OF 8 is 64
SQUARE OF 9 is 81
SQUARE OF 10 is 100

NESTED FOR LOOP

 Loops containing more than one loops within itself is known as nested loop.
 Here outermost loop will start to execute first but the process of outermost loop
ends only when the condition of innermost loop ends. E
 ach loop must have a unique index variable. Each index variable must not coincide
with each other. Loops should not overlap with each other.
 Each loop should be embedded with each other. Loops can have any number of exit
point but should not permit entry into it. Loops should not overlap each other.

Example: The following program illustrates the Nested for statement.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j ; /* Local definitions */
/* Statements */

for(i=1;i<=3;i++)
{
printf(“\n”);
for(j=1;j<=3;j++)
printf(“%d\t”,j);

} /* main */
Output :
123

123

123
Comparison between …

S.NO While Do ..while

1 This is the top tested loop This is the bottom tested loop
2 The condition is first tested if the condition It executes the body once, after it checks
is true then the block is executed until the the condition, if it is true the body is
condition becomes false executed until the condition becomes
false
3 Loop will not be executed if the condition Loop is executed atlases once even
is false through the condition is false

Comparison among the three loop :


The comparison among the three types of loops for loop, while loop and do. ....while loop is
given below.

No. Topics For loop While loop Do...while loop


01 Initialization In the parenthesis of Before the loop. Before the loop or
of condition the loop. in the body of the
variable loop.
02 Test condition Before the body of the Before the body of After the body of
loop. the loop. the loop.
03 Updating the After the first After the first After the first
condition execution. execution. execution.
variable
04 Type Entry controlled loop. Entry controlled Exit controlled
loop. loop.
05 Loop variable Counter. Counter. Sentinel & counter
Distinguish between entry and exit controlled loops with examples.

The differences between the entry and exit controlled loops are as follows.

No. Topics Entry controlled loops Exit controlled loops


01 Test Test condition appears at the Test condition appears at the end.
condition beginning.
02 Control Control variable is counter Control variable is counter &
variable variable. sentinel variable.
03 Execution Each execution occurs by testing Each execution except the first
condition. one occurs by testing condition.
04 Examples ======
======== do
sum = 0; {
n = 1; printf(“Input a number.\n”);
while (n <= 10) scanf("%d", &num);
sum = sum + n*n; }
======== while(num>0);
======
Distinguish between counter and sentinel controlled loops.

The differences between the counter and sentinel controlled loops are as follows.

No. Topics Counter controlled loop Sentinel controlled loop


01 Number of Previously known number of Unknown number of execution
execution execution occurs. occurs.
02 Condition Condition variable is known as Condition variable is known as
variable counter variable. sentinel variable.
03 Value and The value of the variable and the The limitation for the condition
limitation of limitation of the condition for variable is strict but the value of
variable the variable both are strict. the variable varies in this case.
04 Examples ======== ======
sum = 0; do
n = 1; {
while (n <= 10) printf(“Input a number.\n”);
{ scanf("%d", &num);
sum = sum + n*n; }
n = n+ 1; while(num>0);
} ======
========

3.4.2 JUMPS IN LOOPS

The number of times a loop is repeated is decided in advance and the test condition is
written to achieve this. Sometimes, When executing a loop it becomes desirable to skip a part
of the loop or to leave the loop as soon as a certain condition is occurs.

Break STATEMENT

 Break statement is used to terminate the control from one place to another in a
program.
 When a break statement is encountered then the loop gets terminated or come to an
end.
 Break statement exits only single loop. Hence it is used together with the statements
wherever necessary.
 It is also used to exit from a loop.
 A break causes the innermost enclosing loop or switch to be exited immediately. It is
also used together with while, dowhile, for and switch statement.

Syntax:
break;
Example: The following program illustrates the break statement.
#include<stdio.h>
#include<conio.h>
void main ()
{
/* Local definitions */

int i;
/* Statements */
for(i=1;i<=10;i++)
{
if(i==6)
break; /* break statement */
printf("%d", i);
} /* for */
} /* main */

Output :

12345

Continue STATEMENT

 It is used to continue the process.


 Here keyword continue is used together within a statement.
 This statement is specified after the condition.
 The continue statement causes the loop to be continued with the next iteration after
skipping any statement in between.

Syntax:
continue;

Example: The program illustrates the use of continue statement.


Program to calculate the sum of the given positive numbers
#include<stdio.h>
main
{
int i,n,sum=0; /* Local definitions */
/* Statements */
for(i=1;i<=5;i++)
{
printf("Enter any number..... \n");
scanf("%d",&n);
if(n<0)
continue;
else
sum=sum+n;
} /* for */
printf("Sum is ..... %d",sum);
} /* main *

The GOTO Statement


 ‘C’ provides the goto statements to transfer control unconditionally from one place
to another place in the program.
 A goto statement can cause program control almost anywhere in the program
unconditionally.
 The goto statement requires a label to identify the place to move the execution. A
label is a valid variable name and must be ended with colon (:)

Example: Program illustrates the use of the goto statement.


The program evaluates the square root for five numbers. The variable count keeps
the count of numbers read. When count is less than or equal to 5, goto read; directs
the control to the label read; otherwise, the program prints a message and stops.
#include <math.h>
main()
{
double x, y;
int count;
count = 1;
printf("Enter FIVE real values in a LINE \n");
read:
scanf("%lf", &x);
printf("\n");
if (x < 0)
printf("Value - %d is negative\n",count);
else
{
y = sqrt(x);
printf("%lf\t %lf\n", x, y);
}
count = count + 1;
if (count <= 5)
goto read;
printf("\nEnd of computation");
}

Output :

Enter FIVE real values in a LINE


50.70 40 -36 75 11.25
50.750000 7.123903
40.000000 6.324555
Value -3 is negative
75.000000 8.660254
11.250000 3.354102
End of computation

Difference between 'break' and 'continue' statements

S.NO. Break Continue


1 Break statement takes the control to Continue statement takes the control to
the outside of the loop the beginning of the loop
2 It is also used in switch statement This can be used only in loop statements
3 Always associated with if condition This is also associated with if condition
in loops
4 Syntax: Syntax:
{ {
Statement 1; Statement 1;
Statement 2; continue;
Statement n; Statement 2;
break; }
}
MODULE -2
Arrays and Functions
Data Structures using C: Module-2

2.1: ARRAYS
1. SINGLE DIMENSIONAL ARRAY
2. TWO DIMENSIONAL ARRAY
3. MULTI DIMENSIONAL ARRAY
2.2: FUNCTION
1. TYPES OF FUNCTIONS (PROTOTYPES)
2. PARAMETER PASSING METHODS
3. PASSING ARRAYS TO FUNCTIONS
2.3: RECURSION
: STORAGE CLASSES
Data Structures using C: Module-2

2.1 ARRAYS

DEFINING AND PROCESSING ARRAYS

Array is a derived data type. When it is necessary to store more than one value under a
variable, user can make use of array. An array is a fixed-size sequence collection of elements
of the same data type. It is simply a grouping of like-data type.
 Many applications require the processing of multiple data items that have common
characteristics. In such a situation it is convenient to place such data item in an
Array
 A value in an array is identified by index or subscript enclosed in square brackets
with array name.
 The individual data items can be integers, floating point numbers, and characters and
so on, but they must be the same type and same storage class.
 Each array element is referred by specifying the array name with subscripts each
subscripts enclosed in square brackets and each subscript must be a non-negative
integer.
 Thus ‘n’ elements array ‘A’ and the elements are
A[0],A[1],A[2]…..A[N-1]
 The value of each subscript can be expressed as an integer constant or an integer
variable or an integer expression. The arrays can be used to represent not only simple
list of value but also task of data items in two and three or more dimensions.

1. ONE DIMENSIONAL ARRAY

Arrays can be classified into


One-Dimensional arrays
Two-Dimensional arrays
Multi-Dimensional arrays

Declaration one dimensional array


Arrays are declared in the same manner as an ordinary variables except that each
array name must have the size of the array i.e., number of elements accommodate in that
array. Like variables, the array must be declared before they are used.
Data Structures using C: Module-2

Syntax: data_type array_variable [Size or Subscript of the array];


 data type – Specifies the type of the data that will be
contained in the array
Description  array_variable- Specifies the name of the array
 Size or Subscript – Specifies the maximum number of
elements that the array can hold new name given to the
existing data type.
Example int number[5];
for integer: Where, ‘a’ is the name of the array with 5 subscripts of
integer data types and the computer reserves five storage location as
shown below.

Example Char greet[5];


for character: Where, ‘greet’ is the name of the array with 5 subscripts of
character data types and the computer reserves five storage location
as shown below. Character storage always ends with a null ‘\0’
which is a terminator of the compiler.

INITIALISATION ONE DIMENSIONAL ARRAY:

The values can be initialized to an array, when they are declared like ordinary variable,
otherwise they hold garbage values.

The array can be initialized in the following two ways:

i) At compile time
ii) At run time

Static arrays:
The process of allocating memory at compile time is known as static memory
allocation and the arrays that receives static memory allocation are called static arrays. This
approach works fine as long as user know that what the data requirements are.
Data Structures using C: Module-2

Dynamic arrays:
The process of allocating memory at run time is known as dynamic memory
allocation and the arrays that receive such kind of memory allocation are known as dynamic
arrays. Dynamic arrays are created using what are known as pointer variables and memory
management functions malloc, calloc and realloc.
At Compile Time
User can initialize the elements of an array in the same way as the ordinary variables
when they are declared. This is compile time initialization.

Syntax: data_type array name [size]={List of values};

Example: int marks[3]={70,50,86};

Example Program #include<stdio.h>


void main()
{
int studmark[5]={99,97,87,89,92};
int i;
printf(“mark of the student is:\n”);
for(i=0;i<=4;++i)
{
printf(“%d\t”,studmark[i]);
}
getch();
}

At Run time
An array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays.

Syntax: data_type array name [size];

Example: int n[2];


scanf("%d%d",&n[0],&n[1]);

Example Program for(i=0;i<100;i=i+1)


{
if (i<50)

sum[i]=0.0;
else

sum[i]=1.0;
Data Structures using C: Module-2

2. TWO-DIMENSIONAL ARRAY
 Two dimensional arrays are used in situation where a table of values need to be stored
in an array These can be defined in the same fashion as in one dimensional arrays,
except a separate pair of square brackets are required for each subscript
 Two pairs of square brackets required for to dimensional array and three pairs
required for three dimensional arrays and so on.

Syntax: data_type array_name[row_size] [column_size];


Description: data_type - specifies the type of the data that will be contained
in the array.
array_name - specifies the name of the array
[row size] - specifies the size of the row
[column size] - specifies the size of the column
Example: int a[3][3];

 Two dimensional arrays are stored in a row-column matrix, where the left index
indicates the row the right indicates the column.
 Where 'a' is the array name and it reserves 3 row and 3 columns of memory as
shown below

Declaring Two-Dimensional Array :-


The program shown uses a two-dimensional array to store the table values. Each value is
calculated using the control variables of the nested for loops as follows:
product(i,j) = row * column
where i denotes rows and j denotes columns of the product table. Since the indices i and j
ranges from 0 to 4, we have introduced the following transformation:

row = i+1
column = j+1
Data Structures using C: Module-2

Example: Program to calculate multiplication of two matrices


(The following program illustrates arrays.)
#include<stdio.h>
#include<stdlib.h>

#defineROW 3
#defineCOL 3

int main()
{
int i,j,k; // to use as index variables to access the array.
int a[ROW][COL],b[ROW][COL], c[ROW][COL]; //arrays for matrix 3x3
printf("\nEnter values for two 3x3 Matrices\n");
printf("\n Enter the Matrix A");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\n Enter the Matrix B");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("Matrix Multiplication\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
c[i][j]=0;
for(k=0;k<COL;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
printf("\t%d",c[i][j]);
}
Data Structures using C: Module-2

printf("\n");
}
return 0;
}

Output :
Enter values for two 3X3 Matrices
Enter the Matrix A
1 9 6
3 5 7
5 9 3
Enter the matrix B
1 8 5
6 4 9
3 6 2
Matrix Multiplication
73 80 98
54 86 74
68 94 112

Example: Program to calculate the addition of two matrices


(The following program illustrates the arrays.)
#include<stdio.h>
#include<stdlib.h>

#defineROW 3
#defineCOL 3

int main()
{
int i,j,k; // to use as index variables to access the array.
int a[ROW][COL],b[ROW][COL],addition, c[ROW][COL]; //arrays for matrix 3x3
printf("\nEnter values for two 3x3 Matrices\n");
printf("\n Enter the Matrix A");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\n Enter the Matrix B");
Data Structures using C: Module-2

for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("Matrix Addition\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
c[i][j]=0;
{
c[i][j]=a[i][j]+b[i][j];
}
}
}
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
printf("\t%d",c[i][j]);
}
printf("\n");
}
return 0;
}
Output :
Enter values for two 3X3 Matrices
Enter the Matrix A
7 6 2
9 5 3
6 4 1
Enter the Matrix B
8 6 2
4 3 7
8 6 1
Matrix Addition
15 12 4
13 8 10
14 10 2

Initializing an Two-Dimensional Array.

A Two-Dimensional Array can be also initialized. For that the array values are
specified within a Cmpound statement. (i.e.,) { and }.
Data Structures using C: Module-2

General form:
Storage-class data-type array-name[r][c] = { value1, value2, ........... , value n};

Example: float a[4][2]={{12.3,34,5},{23.4,45.6},{34.5,56.7},{45.6,67.8}};

 Here storage class may be static or extern by default. Storage-class is optional.


 Data-type refers to a valid C data type. Array-name refers to a valid array name.
 Here r stands for number of rows and c stands for number of columns.
 Each value in an array are separated by commas and terminated by semicolon.

3. MULTI-DIMENSIONAL ARRAY

Multi-dimensional Array consists of (or) requires more than two square brackets
and it may contain any number of values specified within square brackets. It may be three,
four, five, six and so on.
A Multi dimensional Array in general takes the following form.

General form data-type array-name[s1][s2] .................... [sn];


:
Example: int survey[3] [5] [12];
float table[5] [4] [5] [3];
Description: data_type - specifies the type of the data that will be contained in the
array.
array_name - specifies the name of the array
[s1], [s2], [s3]……[sn] – Memory size of the dimension

 Here storage class may be static or extern by default. Here Storage-class is optional.
 Data-type refers to a valid C data type. Array-name refers to a valid array name.
s1,s2,s3, ……… are sub scripts.

SORTING AN ARRAY

Sorting is the process of Arranging the set of data items in an order. Sorting may be
carried out in Ascending or Descending order. Sorting helps to increase the efficiency of a
program.
Data Structures using C: Module-2

//Sort number in ascending order


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,num[5],temp;
clrscr();
printf(“enter five numbers:\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&num[i]);
}
printf(“\n THE ORIGINAL LIST IS:\n”);
for(i=0;i<5;i++)
printf(“%d\t”,num[i]);
for(i=0;i<4;i++)
for(j=i+1;j<5;j++)
{
if num[i]>num[j]
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
printf(“\n the sorted numbers are:\n”);
for(i=0;i<5;i++)
printf(“%d\t”,num[i]);getch();
getch();
}

Features of Arrays :
 An array is a derived data type. It is used to represent a collection of elements of the
same data type
Data Structures using C: Module-2

 The elements can be accessed with base address (index) and the subscripts define the
position of the element
 In array the elements are stored in continuous memory location. The starting memory
location is represented by the array name and it is known as the base address of the
array
 It is easier to refer the array elements by simply incrementing the value of the
subscript

3.1 FUNCTION

FUNCTION DEFINITION
 C language supports wide range of built in functions, which are useful for performing
specified tasks.
 However C languages allow us to define our own function to carryout different individual
tasks. This topic elaborates such user defined functions.
 A function is a set of instructions that are used to perform specified tasks which
repeatedly occurs in the main program.
 Function is used to provide modularity to the software. By using function we can divide
complex tasks into manageable tasks.
 The function can also helps to avoid duplication of work.
 The function definition is an independent program module that is specially written to
implement to the requirements of the function. A function definition, also known as
function implementation shall include the following elements
1. Function name
2. Function type
3. List of parameters
4. Local variable declarations
5. Function statements
6. A return statement
All the six elements are grouped into two parts; namely,
 Function header (First three elements)
 Function body (Second three elements)
Function Header
Data Structures using C: Module-2

The function header consists of three parts; function type, function name and list of
parameter.
(a) Function Type
The function type specifies the type of value (like float or double) that the function is
expected to return to the calling program. If the return type is not explicitly specified, C will
assume that it is an integer type.
(b) Function name
The function name is any valid C identifier and therefore must follow the same rules of
formation as other variable names in C. The name should be appropriate to the task
performed by the function.
(c) List of Parameter
The parameter list declares the variables that will receive the data sent by the calling
program. They serve as input data to the function to carry out the specified task.
Example :
Float mul (float x, float y) {….}
t sum (int a, int b) {….}
Function body
The function body is enclosed in braces, contains three parts, in the order given below:
1. Local variable declaration : Local variable declarations are statements that specify the
variables needed by the function.
2. Function Statements : Function statements are statements that perform the task of the
function.
3. Return Statements : A return statement is a statement that returns the value evaluated by
the function to the calling program. If a function does not return any value, one can omit the
return statement.
Functions are classified into two types as shown below

Functions

Pre-defined/ User – defined


Library/ built-in Functions
Functions
Data Structures using C: Module-2

The difference between these two categories of functions is that pre-defined or library
functions are not requires to be written by the programmer, whereas the user defined function
has to be written by the programmer at the time of programming.

DECLARING, DEFINING AND ACCESSING FUNCTIONS

USER DEFINED FUNCTIONS

 The functions defined by the user according to their requirements are called user-
defined functions. The user can modify the function according to their requirements.
 The user has full scope to implement their own ideas in the function. Thus the set of
such user-defined functions can be useful to another programmer.
 These are written by the programmer to perform a particular task, that is
repeatedly used in main program. These functions are helpful to break down a
large program in to a number of smaller functions.

Need for User-defined functions

While it is possible to write any complex program under the main()


Function and it leads to a number of problems, such as
i) The program becomes too large and complex
ii) The users can’t go through at a glance
iii) The task of debugging, testing and maintenance becomes difficult
If a program is divided into parts, then each part may be independently coded and later
combined into a single program. These sub-programs are called functions and much easier to
understand, debug and test.
Advantages of User-defined functions
a) The length of the source program can be reduced by dividing it into the smaller
functions
b) By using functions it is very easy to locate and debug an error.
c) The user-defined function can be used in many other source programs whenever
necessary.
d) Functions avoid coding of repeated programming of the similar instructions
e) Function enables a programmer to build a customized library of repeatedly used
routines.
f) Functions facilitate top-down programming approach.
Data Structures using C: Module-2

ELEMENTS OF USER-DEFINED FUNCTIONS


In order to write an efficient user defined function, the programmer must familiar with the
following three elements
a) Function definition
b) Function declaration
c) Function call
Function definition: It is the process of specifying and establishing the user defined
function by specifying all of its elements and characteristics
Function declaration: Like the normal variables in a program, the function can also be
declared before they defined and invoked.

Syntax: datatype function_name(parameter list)


parameters declaration;
{
local variables declaration;
……………..
body of the function;
………………
return(expression);
}
Description Data type – Is the type of data that the function is going to return to its
main program
Function_name- Is the name of the function
Parameters list- These are the list of parameters that are transferred to
the function from the main program. These are called the arguments.
These list must be separated by commas and has no termination after the
parenthesis.
Function Call : The function can be called by simply specifying the
name of the function, return value and parameters if presence.

PARAMETERS
Parameters provide the data communications between the calling function and called
function.
There are two types of parameters,
i) Actual parameters – These are the parameters transferred from the calling
program (main program) to the called program (function)
Data Structures using C: Module-2

ii) Formal parameters- These are the parameters, transferred into the calling
function (main program) from the called program (function)

Ex: main()
{
……
……..
fun1(a,b);
…………
…………..
}
fun1(x,y)
{
……….
………
}
Where a,b are the Actual parameters
x,y are the Formal parameter

Local And Global Variable

There are two kinds of variables

 Local variables

 Global variables

Local variables – The local variables are defined within the body of the function or the
blocking. These variables are defined is local to that function or block only function can not
access these variables.

Example:
value (int a, int b)
{
int c,d; local variables
}

 Here c and d are the local variables which are defined in the body or the function,
they are local to that particular function only.

Global Variable: Global variable are defined outside the main() function multiple functions
can use these variables

Example :
int m=5,n=10; Global variables
Data Structures using C: Module-2

main()
{
int amb;
}
 Here the variables ‘m’ and ‘n’ are defined outside the main() function. Hence they are
global variables.
 They can use any other function. The same variables are used throughout the
program.
 The various modules can share information by using global variable

The return Statements

The return statement may or may not send back any values to the main program
(calling program). If it does, it can be done using the return statements.

Syntax: return; or return(exp);

Description return; - does not return any values

return(exp);- returns the specified exp value to main program

 A function can contain more than one return statements, when the return value
can return values based on certain condition.
 If a function can return some values other than int type, then we must specify the data
type to be return.
Points using return statements

1. the return statement can return only one value form the called function to the
calling function
2. The return statement can be present anywhere in the function
3. The return statement not necessary at the end of the function
4. If the called function does not return any value, then the keyword void must be used
as the return type specifier
5. Number of return statements used in a function are not restricted
6. Parenthesis used around the expression in a return statement is optional
Advantages:
 It reduces the length of source program.
 Breaks the complexity of a program.
Data Structures using C: Module-2

 Break small program into small program.


 It is easy to maintain, modify and understand.
 A program can be divided into smaller subprograms.
 It facilitates top down modular programming.
 The length of the source program can be reduced using functions
 Critical in microcomputers, where memory space is limited.
 Avoid rewriting the same sequence of code at two or more locations in a program.

FUNCTION DECLARATION :
The program or a function that called a function is referred to as the calling function
or calling program. The calling program should declare any function that is to be used later in
the program. This is known as the function declaration.
A function declaration consists of four parts. They are,
1. Function type
2. Function name
3. Parameter list
4. Terminating semicolon
They are coded in the following format :
Funtion_type function_name(parameter list);
Points to note :
1. The parameter list must be separated by commas.
2. If the function has no formal parameters, the list is written as void.
3. The return type is optional when the function returns int type data.
4. When the declared type does not match the types in the function definition compiler
will produce an error.

TYPES OF FUNCTIONS
In general, a function based on whether the Argument is present, whether the value is
returned or not is classified into 4 types. They are
 Functions with no Arguments and no return values.
 Functions with Arguments and no return values.
 Functions with no Arguments but with return values.
 Functions with Arguments and with return values.
 Functions with multiple return values
Data Structures using C: Module-2

1. Functions with no Arguments and no return values.

 When a function has no Argument it does not receive any data from the calling
function.
 When a function does not return value, calling function does not receive data from
the called function.
 There is no data transfer between calling function and called function. A function
that does not return any value cannot be used in an expression.

 The dotted lines indicates that, there is only transfer of control but no data
transfer

2. Functions with Arguments and no return values.

 When a function has Argument it receives data from the calling function and the
value is used inside the sub-function.
 Whenever a function call is made, a copy of the values in Actual argument is sent to
the Formal argument by using the called function.
 A calling function sends value to arguments by means of function call.
Data Structures using C: Module-2

 The Actual arguments and Formal arguments must be the same in number, order and
type.
 The values used in actual arguments must be assigned values before the function call
is made.

 The continuous line indicate data transfer and dotted line indicates transfer of control.

3. Functions with no Arguments but with return values.


 When a function has no arguments it does not receive any data from calling
function.
 But in called function some process takes place and value is returned to calling
portion of main program.
 To return value to the main function return statement is used.
 Hence there is data transfer between calling function and called function.
Data Structures using C: Module-2

4. Functions with Arguments and with return values.


 When a function has argument it receives data from calling function and does some
process and return value to the called function. Here main function has control over
the function.
 Whenever function is called, Actual argument values are copied and assigned to the
Formal arguments.
 Now from the values in the formal arguments sub-function is processed and value is
returned to the main function.

 Here, the continuous line indicates that, the data transfer takes place in between
calling program and called program

5. Functions that return multiple values.


Up till now, we have illustrated functions that return just one value using a return
statement. That is because; a return statement can return only one value. Suppose, however,
that we want to get more information from a function. We can achieve this in C using the
arguments not only to receive information but also to send back information to the calling
function. The arguments that are used to “send out” information are called output parameters.
The mechanism of sending back information through arguments is achieved using what
are known as address operator (&) and indirection operator (*). Let us consider an
example to illustrate this
void mathoperation(int x, int y, int *s, int d);
main()
{
Data Structures using C: Module-2

Int x=20, y=10, s, d;


mathoperation(x, y, &s, &d)
printf( “s=%d\n d=%d\n”, s, d);
}
void mathoperation(int a, int b, int *sum, int*diff);
{
*sum=a+b;
*diff=a-b;
}

The actual arguments x and y are inputs, s and d are output arguments. In the function call,
while we pass the actual values of x and y to the function, we pass the addresses of locations
where the values of s and d are stored in the memory.
value of x to a
value of y to b
address of s to sum
address of d to diff

3. RECURSION

 Recursion is the process of calling the same function itself again and again until
some condition is satisfied.
 This process is used for repetitive computation in which each action is satisfied in
terms of a previous result.
 In order to write a recursive program, the user must satisfy the following

 The problem must be analyzed and written in recursive form


 The problem must have the stopping condition

Syntax:
function1()
{
function1();
}

 In the above function the function1() is called themselves continuously, so the


above function is in recursive manner.
Data Structures using C: Module-2

 There are certain problems, that can be defined in terms of smaller problems of
similar types. Such problems as said to be recursive.

Example: Program to find the factorial of a given number using Recursive


functions
#include<stdio.h>
main()
{
int n;
long int fact();
printf("Enter the number whose factorial is to be found:");
scanf("%d", &n);
printf("The factorial of %4d is %8ld\n", n, fact(n));
}

long int fact(n)


int n;
{
if(n==0)
return(1);
else
return(n*fact(n-1));
}
OUTPUT:
Enter the number whose factorial is to be found: 5
The factorial of 5 is 120

For better visualization of recursion in this example:


factorial (5)
=5 * factorial(4)
=5 * 4 * factorial(3)
=5 * 4 * 3 * factorial(2)
=5 * 4 * 3 * 2 * factorial(1)
=5 * 4 * 3 * 2 * 1
=5 * 4 * 3 * 2
=5 * 4 * 6
=5 * 24
=120

Void functions:

The functions that do not return any values can be explicitly defined as void. This
prevents any accidental use of these functions in expressions.

Example:
#include<stdio.h>
void main()
Data Structures using C: Module-2

{
void starline();
void message();

}
void printline
{
statements;
}
void value
{
statements;
}

PARAMETER PASSING METHODS


In ‘C’ language there are two ways that the parameters can be passed to a function, they are
1. Call by value
2. Call by reference

1. Call by value :
 The process of passing the actual value of variables is known as “call by value”.
 When a function is called in program, the values to the arguments in the function are
taken by the calling program; the value taken can be used inside the function.
 Alteration to the value is not accepted inside the function in calling program but
change is locally available in the function.
2. Call by reference :
 The process of calling a function using pointers to pass the addresses of variables is
known as “call by reference”.
 A function can be declared with pointer as its arguments. Such functions are called
by calling program with the address of a variable as argument form it.
 The address of the variables is altered to the pointers and any change made to the
value inside the function is automatically carried out in the location. This change is
accepted by the calling program.

S.No. Call by value Call by reference


Different memory location are occupied Same memory location occupied by
1 by formal and actual arguments formal and actual arguments, so
there is a saving of memory location
Data Structures using C: Module-2

The usual method to call a function in The address of the variable is passed
2 which only the value of the variable is as an arguments
passed as an arguments
When a new location is created it is very The existing memory location is
3 slow used through its address, it very fast
There is no possibility of wrong data There is a possibility of wrong data
manipulation since the argument are manipulation since the addresses are
4 directly used in an expression used in a an expression. A good
skill of programming is required
here

PASSING ARRAYS TO FUNCTIONS

One-dimensional arrays:
An entire array can be transferred to a function as parameter. To transfer an array
to a function, the array name is enough without subscripts as actual parameters within the
function call.
The corresponding formal parameters are written in same fashion, and must be
declared as an array in formal parameters declaration.

Syntax: void fun1(int,int[]);


main()
{
int a[10],n;
..........
fun1(n,a);
.........
}
void fun1(x,ar[])
{
int x,ar[10];
........
....
}

Three rules to pass an array to a function

3. The function must be called by passing only the name of the array.
4. In the function definition, the formal parameter must be an array type; the size of the
array does not need to be specified.
5. The function prototype must show that the argument is an array.
Data Structures using C: Module-2

Example: Write a program that uses a function to sort an array of integers


void sort(int m, int x[ ]);
main()
{
int i;
int marks[5] = {40, 90, 73, 81, 35};

printf("Marks before sorting\n");


for(i = 0; i < 5; i++)
printf("%d ", marks[i]);
printf("\n\n");

sort (5, marks);


printf("Marks after sorting\n");
for(i = 0; i < 5; i++)
printf("%4d", marks[i]);
printf("\n");
}
void sort(int m, int x[ ])
{
int i, j, t;

for(i = 1; i <= m-1; i++)


for(j = 1; j <= m-i; j++)
if(x[j-1] >= x[j])
{
t = x[j-1];
x[j-1] = x[j];
x[j] = t;
}
}
OUTPUT:
Marks before sorting
40 90 73 81 35

Marks after sorting


35 40 73 81 90

Two dimensional arrays:


We also pass multidimensional arrays to functions. The approach is similar to one-
dimensional arrays. The rules are
1. The function must be called by passing only the array name.
2. In the function definition, we must indicate that the array has two dimensions by
including two sets of brackets.
Data Structures using C: Module-2

3. The size of the second dimension must be specified.


4. The prototype declaration must be similar to the function header.
The function given below calculates the average of the values in a two dimensional matrix
double average(int x[][N], int M, int N)
{
int I, j;
double sum= 0.0;
for(i=0;i<M;i++)
for(j=1;j<N;j++)
sum+=x[i][j];
return(sum/M*N);
}

This function can be used in a main function as illustrated below:

main()
{
int M=3, N=2;
double average(int[][N], int, int);
double main;
int matrix[M][N]= { {1,2}, {3,4}, {5,6}};
mean=average(matrix, M, N);
……………
……………
}

STORAGE CLASSES

 Variables in C programs are totally different from other languages. We can use the
same variable names in the C program in separate blocks.
 When we declare a variable it is available only to specific part or block of the
program. Remaining block or other function cannot get access to the variable.
 The area or block of the C program from where the variable can be accessed is
known as the scope of the variable.
Data Structures using C: Module-2

 Scope of a variable is also defined as the region over which variable is visible or
valid.
 The area or scope of the variable depends on its storage class, that is, where and how
it is declared.
 The storage class of a variable tells the compiler
 Storage area of the variable
 Initial value of the variable if not initialized
 Scope of the variable
 Life of the variable that is how long the variable would be active in the program.
There are four types of storage classes available in a C language. They are

1. Automatic Variables
2. Static Variables
3. External Variables (Global Variables)
4. Register Variables

The following table gives the detail information about various storage classes.

S. Storage Storage place Initial / default Scope Life


No. Specifier value
1 auto CPU Memory Garbage value local Within the function only.
2 extern CPU memory Zero Global Till the end of the main program.
Variable definition might be
anywhere in the C program
3 static CPU memory Zero local Retains the value of the variable
between different function calls.
4 register Register Garbage value local Within the function
memory

Note:

 For faster access of a variable, it is better to go for register specifiers rather than auto
specifiers.
 Because, register variables are stored in register memory whereas auto variables are
stored in main CPU memory.
 Only few variables can be stored in register memory. So, we can use variables as
register that are used very often in a C program.
Data Structures using C: Module-2

1. Automatic Variables

 Variables declared inside a block and local to block in which declared are said to be
Automatic variables. These variables can be accessed by block in which they are
declared. Another block cannot access its value.
 These variables created as new variable each time when function is called and destroyed
automatically when the function is exited.
 Compiler treat variable declared inside block as automatic variable by default. Automatic
variables are stored in memory. All variables declared inside the function is auto by
default.
 Auto variables are safe that is, they cannot be accessed directly by other functions.
Example
main()
{
int number;
- --------- ;
- --------- ;
}
We may also use the keyword auto to declare automatic variables explicitly.
main()
{
auto int number;
;
;
}
One important feature of automatic variables is that their value cannot be changed
accidentally by what happens in some other function in the program. This assures that
we may declare and use the same variable name in different functions in the same
program without causing any confusion to the compiler.

Example: ILLUSTRATION OF WORKING OF auto VARIABLES


void function1(void);
void function2(void);
main( )
{
int m = 1000;
function2();
Data Structures using C: Module-2

printf("%d\n",m); /* Third output */


}
void function1(void)
{
int m = 10;

printf("%d\n",m); /* First output */


}

void function2(void)
{
int m = 100;
function1();
printf("%d\n",m); /* Second output */
}
OUTPUT:
10
100
1000

2. Static Variables
 Static variable may be either an internal type or an external type depending on the
place of declaration.
 Static variables declared within individual block. They are local to the block in which
declared. It exists until the end of the program.
 Variable can be declared using the keyword static. Global and Local variable can be
declared static.
 Static variables are initialized only once when they are compiled in a program.
 When the program is closed the function associated with that program is also exited and
whenever it is visited again the same value exists.
 Internal static variable is declared inside a function.
 External static variable is declared outside a function. It is made available to all
functions in a C program.

Example: ILLUSTRATION OF WORKING OF static VARIABLES


void stat(void);
main ( )
{
int i;
for(i=1; i<=3; i++)
stat( );
}
void stat(void)
Data Structures using C: Module-2

{
static int x = 0;

x = x+1;
printf("x = %d\n", x);
}
OUTPUT:
x=1
x=2
x=3

3. External variables (Global Variables)


 Variables that are active throughout the entire program are called as external
variables (global variables).
 External variables are declared outside the function body. This storage class is
created when variable is declared global.
 No memory is reserved for the variable. Variable retain the value throughout the
execution of a program.
 This storage class can be accessed by any function in same or different program file
and change its value.
For example , the external declaration of integer number and float length might appear as
int number;
float length=6.2;
main()
{
;
;
}
function1()
{
;
;
}
function2()
{
;
;
Data Structures using C: Module-2

}
 The variables number and length are available for use in all the three functions.

Example: ILLUSTRATION OF PROPERTIES OF GLOBAL VARIABLES


int fun1(void);
int fun2(void);
int fun3(void);
int x ; /* global */
main( )
{
x = 10 ; /* global x */
printf("x = %d\n", x);
printf("x = %d\n", fun1());
printf("x = %d\n", fun2());
printf("x = %d\n", fun3());
}
fun1(void)
{
x = x + 10 ;
}
int fun2(void)
{
int x ; /* local */
x=1;
return (x);
}
fun3(void)
{
x = x + 10 ; /* global x */
}
OUTPUT:
x = 10
x = 20
x=1
x = 30

 Once a variable has been declared as global, any function can use it and change its value.
Then subsequent functions can reference only that new value.
 One other aspect of a global variable is that is available only from the point of declaration
to the end of the program. Consider the program segment shown below
main()
{
y=5;
;
;
Data Structures using C: Module-2

}
int y; /*Global Declaration*/
func1()
{
y=y+1;
}
We have a problem here. As far as main is concerned, y is not defined. So the
compiler will issue an error message.
External Declaration
 In the above program, the main cannot access the variable y as it has been declared after
the main function. This problem can be solved by declaring the variable with the storage
class named as “extern”

main()
{
extern int y; /*External declaration*/
;
;
}
func1() /*External declaration*/
{
extern int y;
}
int y; /*Definition*/

4. Register Variables
 Register is a special storage area in a Central Processing Unit (CPU).
 There are 8 registers available inside a Computer. Register variable can be accessed
only by block in which it is declared. It cannot be accessed by any other function.
 Register variable declared using keyword register.
 Both Local variable and formal parameter can be declared as a register.
 Register is used to increase the execution speed.
 Only integer or char variables are declared as register in most of the compilers but ANSI
C supports all the data types.

Example: ILLUSTRATION OF WORKING OF register VARIABLES


#include<stdio.h>
#include<conio.h>
Data Structures using C: Module-2

void main()
{
register int x;
clrscr();
for(x=1;x<=10;x++)
printf(“%d”,x);
getch();
}
MODULE -3
Structures, Unions
and Pointers
Data Structures using C: Module-3

3.1: STRUCTURE
3.2: ARRAY OF STRUCTURE
3.3: ARRAYS WITHIN STRUCTURE
3.4: STRUCTURE WITHIN STRUCTURE (NESTING OF STRUCTURE)
3.5: USER –DEFINED DATA TYPES
3.6: UNION
3.7: POINTERS
Data Structures using C: Module-3

3.1: STRUCTURE

 A Structure is a collection of one or more variables possibly of different data types


grouped together under a single name for convenient handling.
 The structure can be declared with the keyword struct following the name and opening
brace with data elements (members) of different type then closing brace with semicolon,
as shown below.

Syntax :-
struct structure_name
{
data-type member1;
data-type member2;
………………………………
………………………………
data-type membern;
}
struct structure_name v1, v2,……vn;

 Thus, a single structure may contain integer elements, floating point elements and
character elements, pointers, arrays and other structures can also be included as
elements within a structure.
 Structures help to organize data, particularly in large programs, because they allow a group
of related variables to be treated as a single unit.
 A structure is a convenient tool for handling a group of logically related data items.
 For example, it can be used to represent a set of attributes, such as student_name,
roll_number, and marks. The concept of a structure is analogous to that of a ‘record’ in
may other languages.
 Structure is a type of data structure in which each individual element differs in type. The
elements of a structure are called ‘members’.
 The structure elements contain integer, floating point numbers, character arrays, pointers
as their members. Structure act as a tool for handling logically related data items.
 Fields of structure are called structure elements or members. Each member may be of
different type.

Uses / Applications
 Database Management
 Positioning Cursors
 Receiving ascii and scan codes
 Displaying characters
 Printing on printer
Data Structures using C: Module-3

 Mouse Programming
 Graphics Programming
 All Disk Operations
 etc.

Declaring a Structure:

 Structure is declared using the keyword ‘struct’ followed by a ‘tag’ and is enclosed by
curly open ‘{’ and close ‘}’ braces.
 All members of a structure are specified within curly braces { }.

General Form struct structure_name


{
data-type member1;
data-type member2;
………………………………
………………………………
data-type member n;
};
Description structure_name - refers to the name of the structure.
Member1, member2… member n - are elements of a structure.
(;) - Structure is terminated with semicolon.
Example: struct lib_books
{
char book_name[50];
int pages;
float price;
};
Block diagram:

Important points to be noted while declaring a structure:

 The closing brace in the structure declaration must be followed by a semicolon.


 Usually structure type declaration appears at the top of the source code file, before any
variables or functions are defined.
Data Structures using C: Module-3

 Initialization is not allowed within a structure.

Declaring a structure variable:

 Structure variable is declared using keyword ‘struct’ followed by structure name and
structure elements name.
 All structure elements name are separated by commas. Structure variable declaration is
terminated with semicolon (;).

The syntax is
struct tag variable1, variable2, ......... variable m;

Here struct is a keyword. Tag specifies the name of the structure.

Defining a structure
 Defining a structure means creating a variable to access members of structure.
 Creating structure variable allows sufficient memory space to hold all the members of
structure.

Syntax :
struct tag
{
data-type member1;
data-type member2;
………………………………
………………………………
data-type membern;
}structure variable(s);

Accessing structure members:

 Members in a structure are accessed using the Period Operator ‘.’.


 Period Operator establishes a link between member and variable name.
 Structure members are processed by using a variable name with period ‘.’ and member
name.
 Period Operator is also known as member operator or dot operator.

Syntax structure_variable.member_name
Example struct employee
Data Structures using C: Module-3

{
char empname[20];
int empno; member_name
float sal;
}
struct employee emp1;
structure_variable
Accessing: emp1.empname
emp1.empno
emp1.sal member_name
structure_variable
example:
printf(“Enter employee name: ”);
scanf(“%s”, emp1.empname);

Members of a structure vary in type and size.


(Note): Before the dot (.) operator there must be a structure variable and after there
must be a structure element

C language does not permit the initialization of individual structure member within the
template. The initialization must be done only in the declaration of the actual variables. Note
that the compile-time initialization of a structure variable must have the following elements:
1. The keyword struct
2. The structure tag name
3. The name of the variable to be declared
4. The assignment operator =.
5. A set of values for the members of the structure variable, separated by commas and
enclosed in braces.
6. A termination with semicolon

INITIALIZING STRUCTURE

 Structure variable can be initialized at compile time.


Data Structures using C: Module-3

 The storage class must be static.


 Structure initialize must be enclosed within curly braces. The order of structure and
structure member must be the same.
main()
{
struct
{
int weight;
float height;
}

student = {60, 180.75};


……
……
}

This assigns the value 60 to student.weight and 180.75 to student.height. There is a


one-to-one correspondence between the members and their initializing values.

Rules of Initializing Structures


1. We cannot initialize individual members inside the structure template
2. The order of values enclosed in braces must match the order of members in the structure
definition
3. It is permitted to have a partial initialization. We can initialize only the first few
members and leave the remaining bank. The uninitialized members should be only at
the end of the list.
4. The uninitialized members will be assigned default values as follows
 Zero for integer and floating point number.
 ‘/0’ for characters and strings.

Example: C Program to create student details using structures

#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int rollno; char
name[20]; int
m1,m2,m3;
Data Structures using C: Module-3

float percent;
}s;

clrscr();
printf("\n enter the roll no.: ");
scanf("%d",&s.rollno);
printf("\n enter the name: ");
scanf("%s", &s.name);
printf("\n enter the mark 1 =");
scanf("%d",&s.m1);
printf("\n enter the mark 2 =");
scanf("%d",&s.m2);
printf("\n enter the mark 3 =");
scanf("%d",&s.m3);
s.percent=(s.m1+s.m2+s.m3)/3;

printf("\n rollno=%d",s.rollno);
printf("\n name=%s",s.name);
printf("\n mark1=%d",s.m1);
printf("\n mark2=%d",s.m2);
printf("\n mark3=%d",s.m3);
printf("\n percent=%.2f",s.percent);
getch();
}

STRUCTURE OPERATIONS

The period operator ‘.’ Has high precedence over unary operator, arithmetic operator,
relational operator, logical operator and assignment operator.

Expression Meaning
++(variable.member) preincrement
(variable.member)++ post increment
&variable Beginning address of the variable.
&variable.member Access address of variable.member
variable.member.submember refers member of structure within a structure.
Variable.member[expression] Refer individual element of array in a
structure.

4.2 : ARRAY OF STRUCTURE

 Array is a collection of similar data types. In the same way, we also define array of
structures.
Data Structures using C: Module-3

 Group of structure variable assigned with same type stored in an array. Arrays within
structures used to store array of values within a structure.

Syntax Example
struct structure_name struct marks
{ {
data_type member1; int sub1;
data_type member2; int sub2;
……………………… int sub3;
……………………… int total;
data_type member; };
}structure_variable[size]; main()
{
struct marks student[3] = { {45,68,81{, {75,53,69}, {57,36,71}};
The above example declares the student as an array of three elements student[0],
student[1], and student[2] and initializes their members as follows
student[0].subject1 = 45;
student[0].subject2 = 65;
…….
…….
student[2].subject3 = 71;
An array of structures is stored inside the memory in the same way as a multi-
dimensional array.
The array student actually looks as shown in figure given below:

Figure: The array student inside memory

student[0].subject1 45
student[0].subject2 68
student[0].subject3 81
student[1].subject1 75
student[1].subject2 53
student[1].subject3 69
student[2].subject1 57
student[2].subject2 36
student[2].subject3 71
Data Structures using C: Module-3

EXAMPLE PROGRAM FOR ARRAY OF STRUCTURES:

Example: ARRAYS OF STRUCTURES


#include< stdio.h >
{
struct info
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}
struct info std[100];

int i,n;
printf(“Enter the number of students”);
scanf(“%d”,&n);

printf(“ Enter Id_no,name address combination age\m”);


for(i=0;i<n;i++)
scanf(%d%s%s%s”,&std[i].id_no,std[i].name,std[i].address,std[i].combination);
Scanf(“%d”, &std[i].age);

printf(“\n Student information”);


for(i=0;i<n;i++)
printf(“%d%s%s%s \n”,,std[i].id_no,std[i].name,std[i].address,std[i].combination);
printf(“%d” ,std[i].age);
getch();
}

ARRAYS WITHIN STRUCTURES


C permits the use of arrays as structure members. We have already used arrays of
characters inside a structure. Similarly, we can use single-dimensional or multidimensional
arrays of type int or float. For example, the following structure declaration is valid:
struct marks
{
int number;
float subject[3];
} student[2];
Here the member structure subject contains three elements, subject[0], subject[1], subject[2].
These elements can be accessed using appropriate subscripts. For example, the name,
student[1].subject[2];
Data Structures using C: Module-3

would refer to the marks obtained in the third subject by the second student.

Example: ARRAYS WITHIN A STRUCTURE

struct marks
{
int sub[3];
int total;
};
Void main()
{

struct marks student[3] = {45,67,81,0,75,53,69,0,57,36,71,0};


struct marks total;
int i,j;

for(i = 0; i <= 2; i++)


{
for(j = 0; j <= 2; j++)
{
student[i].total += student[i].sub[j];
total.sub[j] += student[i].sub[j];
}
total.total += student[i].total;
}
printf("STUDENT TOTAL\n\n");
for(i = 0; i <= 2; i++)
printf("Student[%d] %d\n", i+1, student[i].total);

printf("\nSUBJECT TOTAL\n\n");
for(j = 0; j <= 2; j++)
printf("Subject-%d %d\n", j+1, total.sub[j]);

printf("\nGrand Total = %d\n", total.total);

}
Output:
STUDENT TOTAL
Student[1] 193
Student[2] 197
Student[3] 164

SUBJECT TOTAL
Subject-1 177
Subject-2 156
Subject-3 221

Grand Total = 554


Data Structures using C: Module-3

STRUCTURE WITHIN STRUCTURE (NESTED STRUCTURE)

 Nesting of structures are nothing but structure within another structure (i.e., a
structure can contain one or more structures as its members).
 A structure may be defined and/or declared inside another structure.
Syntax Example

struct structure_name1 struct stud_Res


{ {
<data-type> member 1; int rno;
<data-type> member 2; char nm[50];
-----------
----------- char std[10];
<data-type> member n;
struct structur_ name2 struct stud_subj
{ {
<data-type> member 1; char subjnm[30];
<data-type> member 2; int marks;
-----------
}subj;
-----------
<data-type> member n; }result;
}inner_struct_var;
}outer_struct_var;

Description:
 In above example, the structure stud_Res consists of stud_subj which itself is a structure
with two members.
 Structure stud_Res is called as 'outer structure' while stud_subj is called as 'inner
structure.'
 The members which are inside the inner structure can be accessed as follow :
result.subj.subjnm
result.subj.marks
Block diagram Example
struct stud_of_birth
{
int day;
int month;
int year;
};
struct person
{
char name[25];
struct stud_of_birth;
};
struct person p1;
Data Structures using C: Module-3

Description:
 In above example, the structure date_of_birth has three members day, month and year.
 There is another structure person, with two members name and dob of data type struct
date_of_birth.
 The struct variable p1 is declared for the structure person.
 The members which are inside the inner structure can be accessed as follow :
p1.dob.day
p1.dob.month
p1.dob.year
 The dot operator is used twice in the above statements, as we are accessing variables of
structure which are inside another structure.
EXAMPLE PROGRAM FOR NESTED STRUCTURES:
Example: C Program to create student details using Nested and array of structures
#include<stdio.h>
#include<conio.h>
void main()
{
struct stud
{
int rollno;
char sname[30];
struct dob
{
int date,mon,year;
}d;
int m1,m2,m3, tot;
float avg;
}s[10];

int n, i;
printf(“Enter the number of students”);
scanf(%d”,&n);

printf("\enter the student details\n");


for(i=1;i<=n;i++)
{
printf("\nenter the id and value:");
scanf("%d%s",&s[i].rollno,s[i].sname);
printf("\nenter dob:");
scanf("%d%d%d",&s[i].d.date,&s[i].d.mon,&s[i].d.year);
printf("\nenter marks:");
scanf("%d%d%d",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3;
}

printf("\n*** Display the details***\n");


printf("\nroolno\tsname\tdob\ttotal\tavg\n");
Data Structures using C: Module-3

for(i=1;i<=n;i++)
{
printf("\%d\t%s\t%d-%d-
%d\t%d\t%f\n",s[i].rollno,s[i].sname,s[i].d.date,s[i].d.mon,s[i].d.year,s[i].tot,s[i].avg);
}
getch();
}

USER –DEFINED DATA TYPES

TYPEDEF

C provides a capability that enables the programmer to assign an alternate name to


a data-type. This is done with a statement known as typedef.

Syntax: typedef type dataname;


Description typedef - keyword.
type – data-type
dataname – specifies the user defined name for that type.
Example: typedef int weeks;
(Here weeks is the another name for int)

EXAMPLE PROGRAM FOR TYPEDEF:

Example: C Program to create user defined data type weeks on int data type and
used it in the program.

Output:
#include<stdio.h> #define D 7 Enter weeks: 4 Number of days = 28

typedef int weeks;


void main
{

weeks wk; printf(“Enter weeks: ”);


scanf(“%d”, &wk);
printf(“Number of days = %d”, wk*D);
}
Data Structures using C: Module-3

ENUMERATED DATA TYPE:The enumerated data type is a user-defined data type.

 An enumeration is a set of named integer constants represented by identifier that


specifies all the legal values a variable of that type may have.
 Enumerated data type is declared using the enum keyword.

Syntax: enum tag{ member1, member2, ........member n };

Example: enum months{ January, February, march……December};


 enum is the key word,
 tag is the name that identifies enumeration having the
Description composition in the format.
 member1, member2, …...member n are the individual
identifiers (known as enumeration constants) that may be
assigned to the variables of this type.

UNION

 Union is a derived data type and it is declared like structure.


 The difference between union and structure is in terms of storage.
 In structure each member has its own storage location, whereas all the members of union
use the same location, although a union may contain many members of different types.
 When we use union the compiler allocates a piece of storage that is large enough to hold.
 union is also declared by using the keyword union.

Syntax union <union name>


{
data-type member 1;
. .
. .
data-type member N;
} union_variable;

Example union exam


{
int roll_no;
char name[15];
int mark1,mark2,mark3;
};
Data Structures using C: Module-3

Advantage:

 Used to conserve memory.


 Same memory shared by two or more variables.
 Variables that share memory location differ in type.
Declaring Union:
Union tag
{
data-type member1;
data-type member2;
………………………………
………………………………
data-type membern;
};

Union variable declaration:-

Storage-class union tag variable1, variable2, ........................ variable_m;

Union and union variable declaration

General Form union tag


{
data-type member1;
data-type member2;
………………………………
………………………………
data-type membern;
}; variable1, variable2, ........................ variable m;

Description union – Keyword


tag – union name
Data Structures using C: Module-3

Example #include<stdio.h>
void main()
{
printf(“The size of union is %d\n”,sizeof(u1));
printf(“The size of structure is %d\n”,sizeof(s1));
}
union exam
{
int rollno;
char name[15];
int m1,m2,m3;
}u1;
Struct exam1
{
int rollno;
char name[15];
int m1,m2,m3;
}

DIFFERENCE BETWEEN ARRAY AND STRUCTURE

S.No. Array Structure


An array is a collection of similar A structure is a collection of
1. data items dissimilar data items
2. An array is derived data type It is a user defined data type
It behaves like a built in data types It must be declared and defined
3.

An array can be increased or A structure element can be added if


4. decreased necessary

COMPARISON OF STRUCTURE AND UNION

Structure Union
 Every member has its own memory  All the members use the same
space. memory space to store the values
 Keyword struct is used  Keyword union is used
 Any member can be accessed at  Different interpretations for the same
any time without the loss of data memory location is possible
 It can handle all the members or a  It can handle only one member at
few as required at a time time, even all the members use the
Data Structures using C: Module-3

same space
 It may be initialized with all its  Only one of its members may be
members initialized
 More memory space is used  Conservation of memory is possible

POINTERS

What Are Pointers?


A pointer is a variable that holds a memory address. This address is the location of
another object (typically another variable) in memory. For example, if one variable contains
the address of another variable, the first variable is said to point to the second.

 Generally computer uses memory for storing instruction and values of the variables with
in the program, but the pointers has memory address as their values.
 The memory address is the location where program instructions and data are stored,
pointers can be used to access and manipulate data stored in the memory
 The computer’s memory is a sequential collection of storage cells as shown below:
Data Structures using C: Module-3

 In computer’s memory each cell is 1 byte, and it has a number called address, this address
is numbered consecutively starting form zero to last address (depends upon the memory
size, in 64 memory having the last address as 65,535).
 While declaring variable, the computer allocates appropriate memory to hold the value of
the variable. Since every memory has a unique address, this address location will have its
own address number somewhere in the memory area.
Example :
int sno=39;

sno Variable Name


39 Value of variable
3977 Address of variable

 The above statement instructs the system to specify a location for the integer variable ‘sno’
and put the value 39 in the location. Assume that the system has chosen the address
location 3911 for ‘sno’ this may be represented as during the execution of the program,
the system always associates the variable ‘sno’ with the address 3977. We may have access
to the value 39 by using either the name of the variable ‘sno’ or the address 3977.

Features of Pointers

 Pointers are efficient in handling data and associated with array.


 Pointers are used for saving memory space.
Data Structures using C: Module-3

 Pointers reduce length and complexity of the program.


 Use of pointer assigns the memory space and also releases it. It helps to make better use
of the available memory ( dynamic memory allocation).
 Since the pointer data manipulation is done with address, the execution time is faster
 The two-dimensional and multi-dimensional array representation is easy in pointers
 Pointers allows for references to function, this may facilitating passing of function as
arguments to other functions.

Example: Program to find the sum of an integer array using pointers

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10];
int i,sum=0;
int *ptr;
printf("Enter 10 elements:\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
ptr = a; /* a=&a[0] */
for(i=0;i<10;i++)
{
sum = sum + *ptr; //*p=content pointed by 'ptr'
ptr++;
}
printf("The sum of array elements is %d",sum);
}
Output:
Enter 10 elements:
8
6
5
3
45
62
51
9
2
4
The sum of array elements is: 195

Declaring a Pointer Variable:


Data Structures using C: Module-3

Syntax data-type *pt-name;

Description Pt-name - refers to valid pointer variable name.


* - is called as indirection operator also known as dereferencing
operator.
Data-type - refers to a valid C data type.
Pointer variable must be followed by ‘*’ sign.
Example int *ptr;

POINTER OPERATOR

 To manipulate with data items directly from Memory Location two operators are used.
 They are
( i ) Address Operator (&) and
( ii ) Indirection Operator ( * ).
 Address Operator acts upon variables, array elements and not on Arithmetic Operators.
 Indirection Operator is also called as “value at address” operator. It operates only on
operands called pointer variables.

Pointer Variable:
 Variables that hold memory address are called pointer variables.
 Pointer variable contains address which is the location of another variable in the
memory.

Accessing the Address of a variable:


 Address of a variable can be accessed using the ‘&’ operator.
 Address operator is specified together followed by a variable name. It can be also used
together with arrays and also in expression.

ACCESSING ADDRESSES OF VARIABLES

main()
{
char a;
int x;
float p, q;

a = 'A';
x = 125;
Data Structures using C: Module-3

p = 10.25, q = 18.76;
printf("%c is stored at addr %u.\n", a, &a);
printf("%d is stored at addr %u.\n", x, &x);
printf("%f is stored at addr %u.\n", p, &p);
printf("%f is stored at addr %u.\n", q, &q);

}
Output:
A is stored at addr 4436.
125 is stored at addr 4434.
10.250000 is stored at addr 4442.
18.760000 is stored at addr 4438.

Note :-
A pointer variable can be also specified in different ways. They are
int* p;
int *p;
int * p;

ACCESSING VARIABLE THROUGH POINTERS


 Once the pointer is declared and assigned to the address of another variable, the variable
can be accessed through its pointers. This is done by using another unary operator *
(asterisk), usually known as the indirection operator.
 Another name for the indirection operator is the dereferencing operator.
Example : int *p;
x=15;
p=&x;

Variable Value Address


x 15 2001
p 2001 2005

ACCESSING VARIABLES USING POINTERS

main()
{
int x, y;
int *ptr;
x = 10;
ptr = &x;
Data Structures using C: Module-3

y = *ptr;
printf("Value of x is %d\n\n",x);
printf("%d is stored at addr %u\n", x, &x);
printf("%d is stored at addr %u\n", *&x, &x);
printf("%d is stored at addr %u\n", *ptr, ptr);
printf("%d is stored at addr %u\n", y, &*ptr);
printf("%d is stored at addr %u\n", ptr, &ptr);
printf("%d is stored at addr %u\n", y, &y);
*ptr = 25;
printf("\nNow x = %d\n",x);

}
Output:
Value of x is 10
10 is stored at addr 4104
10 is stored at addr 4104
10 is stored at addr 4104
10 is stored at addr 4104
4104 is stored at addr 4106
10 is stored at addr 4108
Now x = 25

Rules of Pointer operations:-

 Pointer variable can be assigned to Address of another variable or value of another


pointer variable.
 Pointer variable can be initialized with NULL or zero value.
 Pointer variable can be pre-fixed or post-fixed with increment/decrement operators.
Pointer variable cannot be multiplied by constant.

Null Pointer

 A pointer is said to be null pointer when its right value is 0.


 A null pointer can never point to a valid data. For checking a pointer, if it is assigned to
0, then it is a null pointer and is not valid.
Example:
int *a;

int *b;

b=a=0;

Here b and a become null pointers after the integer value of 0 is assigned to them.
Data Structures using C: Module-3

Pointer to Pointer

Pointer is a variable that contains the address of another variable. Similarly another
pointer variable can store the address of this pointer variable. So we can say, this is a pointer
to pointer variable

Note: *(&a) = (‘a’ means the value at address) of the variables

POINTER ARITHMETICS

What is Pointer Arithmetic in C?


Pointer arithmetic in C means to perform operations like addition, subtraction, increment, or
decrement on pointers to move through memory locations. Since a pointer holds an address, changing
its value means pointing to a different location in memory.

The operations are based on the data type of the pointer—adding 1 to an int pointer moves it by 4
bytes, not 1. This is because it jumps by the size of the data type it points to.

Pointer Arithmetic Operations in C

1. Pointer Addition (ptr + n)


This operation moves the pointer forward by n elements. The actual movement in memory
depends on the size of the data type the pointer is pointing to.

Example:
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;

printf("Value at ptr: %d\n", *ptr); // Output: 10


printf("Value at ptr + 2: %d\n", *(ptr + 2)); // Output: 30
return 0;
}

Explanation: *(ptr + 2) moves 2 elements forward, which for int (usually 4 bytes) means +8 bytes.

2. Pointer Subtraction (ptr - n)


Subtracting n from a pointer moves it backward by n elements.
Example:
#include <stdio.h>
int main() {
int arr[] = {5, 15, 25, 35, 45};
int *ptr = &arr[4]; // Pointing to 45

printf("Current value: %d\n", *ptr); // Output: 45


Data Structures using C: Module-3

printf("Value at ptr - 2: %d\n", *(ptr - 2)); // Output: 25


return 0;
}

Explanation: *(ptr - 2) moves 2 elements back in the array, landing at index 2.

3. Incrementing a Pointer (ptr++)


The increment operator moves the pointer to the next element of its type.

Example:
#include <stdio.h>
int main() {
int arr[] = {100, 200, 300};
int *ptr = arr;

printf("Before increment: %d\n", *ptr); // Output: 100


ptr++;
printf("After increment: %d\n", *ptr); // Output: 200
return 0;
}

Explanation: ptr++ increases the pointer by one element (4 bytes for int).

4. Decrementing a Pointer (ptr--)


This moves the pointer one element back.

Example:
#include <stdio.h>
int main() {
int arr[] = {7, 14, 21};
int *ptr = &arr[2]; // Pointing to 21

printf("Before decrement: %d\n", *ptr); // Output: 21


ptr--;
printf("After decrement: %d\n", *ptr); // Output: 14
return 0;
}

Explanation: ptr-- moves to the previous element in memory.

Pointer Arithmetic in C with Arrays


When using pointer arithmetic with arrays in C, you're working directly with memory
addresses instead of traditional indexing. Since the name of an array acts like a pointer to its first
element, you can use arithmetic to move through the array by incrementing or offsetting the pointer.

Accessing Array Elements with Pointer Arithmetic


#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50};int *ptr = arr;
Data Structures using C: Module-3

printf("First element: %d\n", *ptr); // 10


printf("Second element: %d\n", *(ptr + 1)); // 20
printf("Fourth element: %d\n", *(ptr + 3)); // 40

return 0;
}

ptr + 1 points to the second element, and *(ptr + 1) gives the value at that position.

Traversing an Array Using a Pointer


#include <stdio.h>

int main() {
int arr[] = {5, 10, 15, 20, 25};
int *p = arr;

for (int i = 0; i < 5; i++) {


printf("Element %d: %d\n", i, *(p + i));
}

return 0;
}

This method is functionally the same as using arr[i], but it highlights how pointer arithmetic moves
through memory.
MODULE -4
Stacks and Queues
Data Structures using C- Module 4

4.1 :OVERVIEW OF DATA STRUCTURES

4.2 : REPRESENTATION OF A STACK

4.3 :PRIMITIVE OPERATIONS ON A STACK

4.4 :REPRESENTATIONS OF ARITHMETIC EXPRESSIONS

4.5 : EVALUATION OF POSTFIX EXPRESSION

4.6 :INTRODUCTION TO QUEUE

4.7 :REPRESENTATION OF A QUEUE

4.8 : PRIMITIVE OPERATIONS ON A QUEUE.


Data Structures using C- Module 4

4.1 OVERVIEW OF DATASTRUCTURE

What are Data Structures in C?

Data Structures in C is a way of storing and organizing data in the computer memory so
that it can be processed efficiently. Using the data structures in C, we can make our program
to be able to utilize the memory efficiently as well as improve it’s performance.

Depending on how the elements are organized into the memory, data structures can be
broadly classified into two types:

1. Primitive Data Structures: These are the data types which are defined by the C
programming language. Primitive types can only store a value of single type. These are
also known as system-defined data types. int, float, char, double are some primitive
types of data types.
2. Non-Primitive Data structures: These are the data structures in C which are derived
from the primitive data types. Non-primitive data structures are also known as user-
defined data types. Non-primitive data structures in C are able to store values of
multiple data type. Arrays, trees, stack, queue, etc. are some of the user defined data
structures in C.
Further the non-primitive data structures in C can be classified into two categories:

1. Linear data structures: Data is stored and accessed in a sequential manner.


2. Non-Linear data structures: Data is stored and accessed in a non-linear fashion.

 Array
 Stack
 Queue
 Linked List
 Tree
 Graph

4.2 STACK

What is Stack?

A stack is an Abstract Data Type (ADT), commonly used in most programming


languages. It is named stack as it behaves like a real-world stack, for example – a deck of
cards or a pile of plates, etc.
Data Structures using C- Module 4

A real-world stack allows operations at one end only. For example, we can place or remove a card
or plate from the top of the stack only. Likewise, Stack ADT allows all data operations at one end
only. At any given time, we can only access the top element of a stack. This feature makes it
LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted
or added) last, is accessed first. In stack terminology, insertion operation is called PUSH
operation and removal operation is called POP operation.

Stack Representation
The following diagram depicts a stack and its operations −

A stack can be implemented by means of Array, Structure, Pointer, and Linked List. Stack can
either be a fixed size one or it may have a sense of dynamic resizing. Here, we are going to
implement stack using arrays, which makes it a fixed size stack implementation.

4.3 STACK OPERATIONS


Stack operations may involve initializing the stack, using it and then de-initializing it. Apart
from these basic stuffs, a stack is used for the following operations −
 push() − Pushing (storing) an element on the stack.
 pop() − Removing (accessing) an element from the stack.
 peek() − get the top data element of the stack, without removing it.
 isFull() − check if stack is full.
 isEmpty() − check if stack is empty.
Data Structures using C- Module 4

Push Operation
The process of putting a new data element onto stack is known as a Push Operation. Push
operation involves a series of steps −
 Step 1 − Checks if the stack is full.

 Step 2 − If the stack is full, produces an error and exit.

 Step 3 − If the stack is not full, increments top to point next empty space.

 Step 4 − Adds data element to the stack location, where top is pointing.

Algorithm for Push()

void push() {

if (top == MAX - 1) {

printf("Stack Overflow!\n");}

else { int value;

printf("Enter the value to push: ");

scanf("%d", &value); // Get the value from the user

stack[++top] = value; // Increment top and insert value

printf("Pushed %d to stack\n", value); }}


Data Structures using C- Module 4

Pop Operation
Accessing the content while removing it from the stack, is known as a Pop Operation. In an
array implementation of pop() operation, the data element is not actually removed, instead top is
decremented to a lower position in the stack to point to the next value. But in linked-list
implementation, pop() actually removes data element and deallocates memory space.
A Pop operation may involve the following steps −

 Step 1 − Checks if the stack is empty.

 Step 2 − If the stack is empty, produces an error and exit.

 Step 3 − If the stack is not empty, accesses the data element at which top is pointing.

 Step 4 − Decreases the value of top by 1.

Algorithm for Pop()

void pop() {

if (top = = -1) {

printf("Stack Underflow!\n");

} else {

int value = stack[top--]; // Return the top element and decrement top

printf("Popped element: %d\n", value); }}


Data Structures using C- Module 4

Algorithm for Peek()

void peek() {

if (top = = -1) {

printf("Stack is empty!\n");

} else { printf("Top element is: %d\n", stack[top]); }}

Algorithm for display()

void display() {

if (top = = -1) {

printf("Stack is empty!\n");

} else { int i;

printf("Stack elements are:\n");

for (i = top; i >= 0; i--) {

printf("%d ", stack[i]);

} printf("\n"); }}

Algorithm for isFull() Algorithm for isEmpty()

void isFull() { void isEmpty() {

if (top == MAX - 1){ if (top == -1) {

printf("Stack Overflow!\n"); printf("Stack is empty!\n");

}} }}
Data Structures using C- Module 4

Implementation of stack using Array

#include <stdio.h>
#include <stdlib.h>

#define MAX 5 // Define maximum size of the stack

// Declare the stack as a global array and top variable


int stack[MAX];
int top = -1; // Initially, the stack is empty

// Push an element onto the stack


void push() {
if (top == MAX - 1) {
printf("Stack Overflow!\n");
} else {
int value;
printf("Enter the value to push: ");
scanf("%d", &value); // Get the value from the user
stack[++top] = value; // Increment top and insert value
printf("Pushed %d to stack\n", value);
}}

void pop() {
if (top == -1) {
printf("Stack Underflow!\n");
} else {
int value = stack[top--]; // Return the top element and
decrement top
printf("Popped element: %d\n", value); }}

void peek() {
if (top == -1) {
printf("Stack is empty!\n");
} else {
printf("Top element is: %d\n", stack[top]); }}

void display() {
if (top == -1) {
printf("Stack is empty!\n");
} else {
printf("Stack elements are:\n");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
printf("\n"); }}
Data Structures using C- Module 4

// Main function to test the stack implementation with a menu and while loop
Void main() {
int choice;

while (1) {
printf("\nStack Operations Menu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
push(); break;
case 2:
pop(); break;
case 3:
peek();break;
case 4:
display();break;
case 5:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
} }}
Data Structures using C- Module 4

4.4 REPRESENTATION OF EXPRESSIONS

1). Infix notation: A + B


Infix notation is the most familiar format, where operators are placed between operands. For
example, the simple arithmetic operation “2 + 3” is in infix notation.
When we write any arithmetic expression in infix notation, operators are written in-between their
operands.
For example
(A+B) or A * ( B + C ) / D is in infix notation.

2). Postfix notation (“Reverse Polish notation”): A B +


Postfix notation, or Reverse Polish notation, places the operator after the operands. Thus, “2 + 3” in
infix becomes “2 3 +” in postfix. When we write any arithmetic expression in Postfix notation,
operators are written after their operands.
For example
A B C + * D / is in postfix notation
The order of evaluation of operators is always left-to-right, and brackets cannot be used to change
this order. Because the “+” is to the left of the “*” in the example above, the addition must be
performed before the multiplication.
Operators act on values immediately to the left of them. For example, the “+” above uses the “B” and
“C”.
We can add (totally unnecessary) brackets to make this explicit:
( (A (B C +) *) D /)
3). Prefix notation (“Polish notation”): + A B
When we write any arithmetic expression in Prefix notation, operators are written before their
operands.
For example
/ * A + B C D is in Prefix notation
Data Structures using C- Module 4

Example of Infix, Postfix and Prefix

Infix Postfix Prefix Notes

multiply A and B,
A*B+C/D AB*CD/+ +*AB/CD divide C by D,
add the results

add B and C,
A * (B + C) / D ABC+*D/ /*A+BCD multiply by A,
divide by D

divide C by D,
A * (B + C / D) ABCD/+* *A+B/CD add B,
multiply by A
Data Structures using C- Module 4

4.5 Evaluation of Postfix Expressions Using Stack


What is a Postfix Expression?
As Postfix expression is without parenthesis and can be evaluated as two operands and an operator at
a time, this becomes easier for the compiler and the computer to handle.

Evaluation Rules of Postfix Expression


The following are the rules for evaluation of a postfix expression:
1. While reading the expression from left to right,
2. Push the element in the stack if it is an operand.
3. Pop the two operands from the stack, if the element is an operator and then evaluate it.
4. Push back the result of the evaluation.
5. Repeat it till the end of the expression.
Algorithm for Evaluation of Postfix Expression
1. Add ) to postfix expression.
2. Read postfix expression Left to Right until ) encountered
3. If operand is encountered, push it onto Stack
4. [End If]
5. If operator is encountered, Pop two elements
6. A -> Top element
7. B-> Next to Top element
8. Evaluate B operator A
9. Push B operator A onto Stack
10. Set result = pop
Example for Evaluation of Postfix Expression

Problems for practices:


1. 57+67+* Answer: 156
2. 452*+5+ Answer: 19
3. 456*+ Answer: 34
4. 31+2^74-2*+5- Answer: 17
Data Structures using C- Module 4

C Program for Evaluation of Postfix Expressions Using Stack

#include <stdio.h> }
#include <ctype.h> else if (ch == '+' || ch == '-' || ch == '*' ||
#define MAXSTACK 100 ch == '/') {
#define POSTFIXSIZE 100 A = pop();
int stack[MAXSTACK]; B = pop();
switch (ch)
int top = -1; {
case '*':
void push(int item) val = B * A; break;
{ case '/':
if (top >= MAXSTACK - 1) { val = B / A; break;
printf("stack over flow"); case '+':
return; val = B + A; break;
}
else { case '-':
top = top + 1; val = B - A; break;
stack[top] = item; }
}} push(val);
int pop() }
{ }
int item; printf(" Result of expression evaluation :
if (top < 0) { %d \n", pop());
printf("stack under flow"); }
}
else { int main()
item = stack[top]; {
top = top - 1; int i;
return item; char postfix[POSTFIXSIZE];
}} for (i = 0; i <= POSTFIXSIZE - 1; i++) {
scanf("%c", &postfix[i]);
void EvalPostfix(char postfix[])
{ if (postfix[i] == ')')
int i; {
char ch; break;
int val; }
int A, B,num; }

for (i = 0; postfix[i] != ')'; i++) { EvalPostfix(postfix);


ch = postfix[i]; return 0;
if (isdigit(ch)) { }
num=int(ch);
push(ch);
Data Structures using C- Module 4

4.3 QUEUE

Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at
both its ends. One end is always used to insert data (enqueue) and the other is used to remove data
(dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be
accessed first.

A real-world example of queue can be a single-lane one-way road, where the vehicle enters first,
exits first. More real-world examples can be seen as queues at the ticket windows and bus-stops.

Queue Representation

As we now understand that in queue, we access both ends for different reasons. The following
diagram given below tries to explain queue representation as data structure −

As in stacks, a queue can also be implemented using Arrays, Linked-lists, Pointers and Structures.
For the sake of simplicity, we shall implement queues using one-dimensional array.

Basic Operations
Queue operations may involve initializing or defining the queue, utilizing it, and then completely
erasing it from the memory. Here we shall try to understand the basic operations associated with
queues −
 enqueue() − add (store) an item to the queue.
 dequeue() − remove (access) an item from the queue.
 peek() − Gets the element at the front of the queue without removing it.
 isfull() − Checks if the queue is full.
 isempty() − Checks if the queue is empty.

In queue, we always dequeue (or access) data, pointed by front pointer and while
enqueing (or storing) data in the queue we take help of rear pointer.
Data Structures using C- Module 4

Enqueue Operation

Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively
difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
 Step 1 − Check if the queue is full.
 Step 2 − If the queue is full, produce overflow error and exit.
 Step 3 − If the queue is not full, increment rear pointer to point the next empty space.

 Step 4 − Add data element to the queue location, where the rear is pointing.

Algorithm for Enqueue()

void enqueue() {

if (rear = = MAX - 1) {

printf("Queue Overflow!\n");

} else {

int value;

printf("Enter the value to enqueue: ");

scanf("%d", &value);

if (front == -1) {

front = 0;}

queue[++rear] = value;

printf("Enqueued %d to queue\n", value); }}


Data Structures using C- Module 4

Dequeue Operation
Accessing data from the queue is a process of two tasks − access the data where front is pointing
and remove the data after access. The following steps are taken to perform dequeue operation −

 Step 1 − Check if the queue is empty.


 Step 2 − If the queue is empty, produce underflow error and exit.
 Step 3 − If the queue is not empty, access the data where front is pointing.
 Step 4 − Increment front pointer to point to the next available data element.

Algorithm for dequeue()

void dequeue() {

if (front = = -1) {

printf("Queue Underflow!\n");

} else {

int value = queue[front++];

printf("Dequeued element: %d\n", value);

if (front > rear) {

front = rear = -1; } } }


Data Structures using C- Module 4

Algorithm for front() Algorithm for rear()

void front () { void rear () {

if (front == -1 || front > rear) { if (front == -1 || front > rear) {

printf("Queue is empty!\n"); printf("Queue is empty!\n");

} else { } else {

printf("Front element:%d\n", queue[front]); printf("Rear element: %d\n", queue[rear]);

}} }}

Algorithm for display()

void display() {

if (front = = -1) {

printf("Queue is empty!\n");

} else {

printf("Queue elements are:\n");

for (int i = front; i <= rear; i++) {

printf("%d ", queue[i]);

} printf("\n"); }}

Algorithm for isFull() Algorithm for isEmpty()

void isFull() { void isEmpty() {

if (rear = = MAX - 1){ if (front = = -1) {

printf("Queue Overflow!\n"); printf("Queue is empty!\n");

}} }}
Data Structures using C- Module 4

Implementation of Queue using Array

#include <stdio.h>
#include <stdlib.h>

#define MAX 5

int queue[MAX];
int front = -1;
int rear = -1;

void enqueue() {
if (rear == MAX - 1) {
printf("Queue Overflow!\n");
} else {
int value;
printf("Enter the value to enqueue: ");
scanf("%d", &value);
if (front == -1) front = 0;
queue[++rear] = value;
printf("Enqueued %d to queue\n", value);
}
}

void dequeue() {
if (front == -1 || front > rear) {
printf("Queue Underflow!\n");
} else {
int value = queue[front++];
printf("Dequeued element: %d\n", value);
if (front > rear) {
front = rear = -1; // Reset to initial state
}
}
}

void peek() {
if (front == -1 || front > rear) {
printf("Queue is empty!\n");
} else {
printf("Peek: %d\n", queue[front]);
}
}
void frontElement() {
if (front == -1 || front > rear) {
printf("Queue is empty!\n");
} else {
printf("Front element is: %d\n", queue[front]);
}
}
Data Structures using C- Module 4

void rearElement() {
if (front == -1 || front > rear) {
printf("Queue is empty!\n");
} else {
printf("Rear element is: %d\n", queue[rear]);
}
}

void display() {
if (front == -1 || front > rear) {
printf("Queue is empty!\n");
} else {
printf("Queue elements: ");
for (int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
printf("\n");
}
}

int main() {
int choice;

while (1) {
printf("\nQueue Operations Menu:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Peek (Front Element)\n");
printf("4. Display\n");
printf("5. Front\n");
printf("6. Rear\n");
printf("7. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1: enqueue(); break;
case 2: dequeue(); break;
case 3: peek(); break;
case 4: display(); break;
case 5: frontElement(); break;
case 6: rearElement(); break;
case 7: printf("Exiting...\n"); exit(0);
default: printf("Invalid choice. Try again.\n");
}
}

return 0;}
MODULE -5
Searching and
Sorting
MODULE 5:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy