0% found this document useful (0 votes)
89 views98 pages

PROGRAMMING IN C AND DATA STRUCTURES - Unit1&2

The document discusses the history and importance of the C programming language. It was developed in 1972 and standardized in 1988 and 2000. C is important because it is efficient, portable, and can be used to write system software. The document then describes the basic structure of a C program, including documentation, link, definition, global declaration, main function, and subprogram sections. It also discusses data types in C like integer, floating point, character, and derived types. Finally, it covers variables, constants, and data types for variables in C.

Uploaded by

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

PROGRAMMING IN C AND DATA STRUCTURES - Unit1&2

The document discusses the history and importance of the C programming language. It was developed in 1972 and standardized in 1988 and 2000. C is important because it is efficient, portable, and can be used to write system software. The document then describes the basic structure of a C program, including documentation, link, definition, global declaration, main function, and subprogram sections. It also discusses data types in C like integer, floating point, character, and derived types. Finally, it covers variables, constants, and data types for variables in C.

Uploaded by

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

PROGRAMMING IN C AND DATA STRUCTURES

Course – B.Sc (Computer Science) Semester – I

UNIT – I
History of C and its importance:
History of C:
 C language is developed by Mr. Dennis Ritchie in the year 1972 at bell laboratory
at USA.
 C is a simple and structure Oriented Programming Language.
 In the year 1988 C programming language standardized by ANSI (American
national standard institute),
 that version is called ANSI-C.
 In the year of 2000 C programming language standardized by ISO that version is
called C-99.
 All other programming languages were derived directly or indirectly from C
programming concepts.
Importance of ‘C’ language :
 It is robust language whose rich setup of built in functions and operator can be used to
write any complex program.
 Program written in C are efficient due to several variety of data types and powerful
operators.
 The C compiler combines the capabilities of an assembly language with the feature of
high level language. Therefore it is well suited for writing both system software and
business package.
 There are only 32 keywords; several standard functions are available which can be
used for developing program.
 C is portable language; this means that C programs written for one computer system
can be run on another system, with little or no modification.
 C language is well suited for structured programming, this requires user to think of a
problems in terms of function or modules or block. A collection of these modules
make a program debugging and testing easier.
 C language has its ability to extend itself. A c program is basically a collection of
functions that are supported by the C library. We can continuously add our own
functions to the library with the availability of the large number of functions. In India
and abroad mostly people use C programming language because it is easy to learn and
understand.
Structure of C Program :
 The components of the basic structure of a C program consists of 6 parts.

Documentation section:
 The documentation section consists of a set of comment lines giving the name of the
program, the author and other details.
Link section:
 The link section provides instructions to the compiler to link functions from the
system library such as using the #include directive.
Definition section:
 The definition section defines all symbolic constants such using the #define directive.
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.
main () function section:
Every C program must have one main function section. This section contains two parts;
declaration part and executable part.
Declaration part:
 The declaration part declares all the variables used in the executable part.
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.
Subprogram section:
 If the program is a multi-function program then 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.
Data Types:
 Data types specify how we enter data into our programs and what type of data we
enter.
 C language has some predefined set of data types to handle various kinds of data that
we can use in our program.
 These data types have different storage capacities.
 C language supports 2 different type of data types:
Primary data types:
 These are fundamental data types in C namely integer(int), floating point(float),
character(char) and void.
Derived data types:
 Derived data types are nothing but primary data types but a little twisted or grouped
together like array, structure, union and pointer.
 Data type determines the type of data a variable will hold.
 If a variable x is declared as int. it means x can hold only integer values.
 Every variable which is used in the program must be declared as what data-type it is.
 Primary data types in c Integer type Integers are used to store whole numbers.
Integer type on 16-bit machine:
 int or signed int 2 -32,768 to 32767
 unsigned int 2 0 to 65535
 short int or signed short int 1 -128 to 127
 unsigned short int 1 0 to 255
 long int or signed long int 4 -2,147,483,648 to 2,147,483,647
 unsigned long int 4 0 to 4,294,967,295
Floating point type:
 Floating types are used to store real numbers.
 Size and range of Integer type on 16-bit machine Type Size(bytes) Range
 Float 4 3.4E-38 to 3.4E+38
 double 8 1.7E-308 to 1.7E+308
 long double 10 3.4E-4932 to 1.1E+4932
Character type:
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine Type Size(bytes) Range
char or signed char 1 -128 to 127
unsigned char 1 0 to 255
int - data type int is used to define integer numbers.
{ int Count; Count = 5; }
float - data type:
float is used to define floating point numbers.
{ float Miles; Miles = 5.6; Programming in C 10 }
double - data type:
double is used to define BIG floating point numbers.
It reserves twice the storage for the number.
On PCs this is likely to be 8 bytes. { double Atoms; Atoms = 2500000; }
char - data type:
char defines characters. { char Letter; Letter = 'x'; }
Derived data types :
 The derived data type consists of Arrays (used to manage large numbers of objects of
the same type) ,
 Functions (does a specific job), Pointers (represents the address and type of a variable
or a function).
Constants:
 Constants refer to fixed values.
 They are also called as literals. Constants are categorized into two basic types.

Integer Constant:
 Integer constants are whole numbers without any fractional part.
 Thus integer constant consist of a sequence of digits.
 Integer constant can be written in three different number systems:
 Decimal, b) Octal and c) Hexadecimal.
Decimal Integer:
 It consists of any combination of digits taken from the set 0 through 9.
 It can either be positive or negative.
For Example:
0 -321 1234 +786
Embedded spaces, commas, and non-digit characters are not permitted between digits.
For example, 15 750 20,000 $10000 are illegal numbers .
Octal Integer:
 It consist of any combination of digits taken from the set 0 through 7.
 However, the first digit must be 0, in order to identify the constant as an octal number.
For Example:
0 01 0125 055
Hexadecimal Integer:
 A hexadecimal integer constant must begin with either 0x or 0X.
 It can then be followed by any combination of digits taken from the set 0 through 9
and A through F (either upper-case or lower-case).
 The following are valid hexadecimal integer
constants. 0X0 0x1 0XAB125 -0x5bcd
Real Constant:
 A real constant is combination of a whole number followed by a decimal point and
the fractional part.
Example: 0.0083 -0.75 .95215.
 Integer numbers are inadequate to represent quantities that vary continuously,
 Such as distances, heights, temperatures, prices and soon.
 Constants refer to fixed values.
Single Character Constants :
 It simply contains a single character enclosed within ' and ' (a pair of single quote).
 It is to be noted that the character '8' is not the same as 8.
 Character constants have a specific set of integer values known as ASCII values
(American Standard Code for Information Interchange).
Example: 'X' '5' ';'
String Character Constants :
 These are a sequence of characters enclosed in double quotes, and they may include
letters, digits, special characters, and blank spaces.
 It is again to be noted that "G" and 'G 'are different – because "G" represents a string
as it is enclosed within a pair of double quotes whereas 'G' represents a single
character.
Example: "Hello!", "2015", "2+1"
Backslash character constant:
 Although it consists of two characters, it represents single character.
 Each and Every combination starts with back slash(),.
 They are non-printable characters.
 They are used in output functions.
For Example: \t is used to give a tab space is used to give a new line.

VARIABLES:
 Variable is a data name that may be used to store a data value.
 variables are changeable, we can change value of a variable during execution of a program.
 A programmer can choose a meaningful variable name.
 A variable must be declared before it can be defined.
Datatype of Variable:
 A variable in C language must be given a type, which defines what type of data the variable
will hold.
char:
 Can hold/store a character init.
int:
 Used to hold an integer.
float:
 Used to hold a float value.
double:
 Used to hold a double value.
Void
Rules to name a Variable:
1. Variable name must not start with a digit.
2. Variable name can consist of alphabets, digits and special symbols like underscore_
3. Blank or spaces are not allowed in variable name.
4. Keywords are not allowed as variable name.
5. Upper and lower case names are treated as different, as C is case-sensitive, so it is
suggested to keep the variable in lowercase.
Declaration of variables:
 Declaration of variables must be done before they are used in the program.
 Declaration does two things.
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
 Until the variable is defined the compiler doesn't have to worry about allocating memory
space to the variable.
Syntax:
 v1,v2,…..vn are the names of variables.
 Variables are separated by commas( ,).
 A declaration statement must end with a semicolon( ;).
For example:
Initialization of Variable: (Assigning a value to a variable)
 Variable initialization means assigning a value to the variable.
 C variables declared can be initialized with the help of assignment operator‘=’.
Example:
int a = 10; int a = b+c; a = 10; a = b+c;
Operators and Expressions:
Operators:
 An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations.
 Operators require some data to operate on and such data is called operands.
Operators in C can be classified into following categories:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment and Decrement Operators
 Conditional Operators
 Bitwise Operators
 Special Operators.
Arithmetic Operators:
 C programming language provides all basic arithmetic operators.
 These are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus.
 The ‘/’ is integer division which only gives integer part as result after division.
 ‘%’ is modulo division which gives the remainder of integer division as result.

Relational Operators:
 Relational Operators These operators are used to compare the value of two variables.
 If the relation is true then it will return value 1 or if the relation is false then it will
return value 0.
 C programming offers 6 relational operators.
Logical Operators :
 These operators are used to perform logical operations on the given two variables.
 Logical operators are used when more than one conditions are to be tested and based
on that result, decisions have to be made.
 An expression which combines two or more relational expressions is known as logical
expression.

Assignment Operators:
 Assignment operators are used to assign result of an expression to a variable.
 ‘ = ’ is the assignment operator in C.
 Furthermore, C also allows the use of shorthand assignment operators.
 Shorthand operators take the form: var op = exp; where var is a variable, op is arithmetic
operator, exp is an expression.
 In this case, ‘op=’ is known as shorthand assignment operator. The above assignment.
 x + =y ; Here, the above statement means the same as x = x + y;

Increment and Decrement Operators:


 C programming allows the use of ++ and – operators which are increment and
decrement operators respectively.
 Both the increment and decrement operators are unary operators.
 The increment operator ++ adds 1 to the operand and the decrement operator –
subtracts 1 from the operand.
 The general syntax of these operator
sare: Increment Operator: m++ or ++m;
Decrement Operator: m- - or - - m;
 In the example above, m++ simply means m=m+1; and m-- simply means m=m-1;
 Increment and decrement operators are mostly used in for and while loops.
 ++m is known as prefix operator and m++ is known as postfix operator.
 A prefix operator firstly adds 1 to the operand and then the result is assigned to the
variable on the left.
 A postfix operator firstly assigns value to the variable on the left and then increases
the operand by 1.
 Same is in the case of decrement operator.
 For example, X=10; Y=X++;
 In this case, the value of Y will be 10 and the value of X will be 11.
Conditional Operator :
 The operator pair “?” and “:” is known as conditional operator.
 These pair of operators are ternary operators.
 The general syntax of conditional operator is:
expression1 ? expression2 : expression3 ;
The conditional operator works as follows:
 The first expression conditionalExpression is evaluated first.
This expression evaluates to 1 ifit's true and evaluates to 0 if it'sfalse.
 If conditionalExpression is true, expression1 isevaluated.
 If conditionalExpression is false, expression2 is evaluated.
This syntax can be understood as a substitute of if else
statement.
For example,
a =3; b = 5
x = (a > b) ? a : b ;
Bitwise Operators:
 In C programming, bitwise operators are used for testing the bits or shifting them left
or right.
 The bitwise operators available in Care:
Special Operators:
 C programming supports special operators like comma operator, size of operator,
pointer operators (& and *) and member selection operators (. and->).
 The comma operator and size of operator are discussed in this section whereas the
pointer and member selection operators are discussed in later sections.
1. Comma Operator:
 The comma operator can be used to link the related expressions together.
 A comma linked expression is evaluated from left to right and the value of the
right most expression is the value of the combined expression.
For example: x=(a = 2, b=4,a+b)
 In this example, the expression is evaluated from left to right. So at first,
variable a is assigned value 2, then variable b is assigned value 4 and then
value 6 is assigned to the variable x.
 Comma operators are commonly used in for loops, while loops, while
exchanging values,etc.
2 .Sizeof( ) operator :
 The sizeof operator is usually used with an operand which may be variable,
constant or a data type qualifier.
 This operator returns the number of bytes the operand occupies.
 Sizeof operator is a compile time operator.
 Some examples of use of sizeof operator are: x = sizeof (a); y
=sizeof(float);
 The sizeof operator is usually used to determine the length of arrays and
structures when their sizes are not known. It is also used in dynamic memory
allocation.
Expressions:
 Arithmetic expression in C is a combination of variables, constants and operators
written in a proper syntax.
 C can easily handle any complex mathematical expressions but these mathematical
expressions have to be written in a proper syntax.
Some examples of mathematical expressions written in proper syntax of C are:

Evaluation of Expressions:
 Expressions are evaluated using an assignment statement of the form:
Variable = expression;
 In the above syntax, variable is any valid C variable name.
 When the statement like the above form is encountered, the expression is evaluated first
and then the value is assigned to the variable on the left hand side.
 All variables used in the expression must be declared and assigned values before evaluation
is attempted.
Examples of expressions are:
x=a*b–c;
y = b / c * a;
z = a – b / c + d;
 Expressions are evaluated based on operator precedence and associativity rules when an
expression contains more than one operator.
Rules for evaluation of expression:
•First parenthesized sub expression left to right are evaluated.
• If parenthesis are nested, the evaluation begins with the innermost sub expression.
• The precedence rule is applied in determining the order of application of operators in
evaluating sub expressions.
• The associability rule is applied when two or more operators of the same precedence level
appear in the sub expression.
• Arithmetic expressions are evaluated from left to right using the rules of precedence.
• When Parenthesis are used, the expressions within parenthesis assume highest priority.
Order of Precedence:
 At first, the expressions within parenthesis are evaluated.
 If no parenthesis is present, then the arithmetic expression is evaluated from left to
right.
 There are two priority levels of operators in C.
High priority: * / %
Low priority: + -
 The evaluation procedure of an arithmetic expression includes two left to right passes
through the entire expression.
 In the first pass, the high priority operators are applied as they are encountered and in
the second pass, low priority operations are applied as they are encountered.
 we have an arithmetic expression as: x = 9 – 12 / 3 + 3 *2 – 1.
This expression is evaluated in two left to right passes as:
First Pass
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10
 But when parenthesis is used in the same expression, the order of evaluation gets changed.
For example ,x = 9 – 12 / (3 + 3) * (2 – 1)
 When parentheses are present then the expression inside the parenthesis are evaluated
first from left to right.
 The expression is now evaluated in three passes as:
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3: x= 7.
 There may even arise a case where nested parentheses are present (i.e. parenthesis
inside parenthesis).
 In such case, the expression inside the innermost set of parentheses is evaluated first
and then the outer parentheses are evaluated.
For example, we have an expression as: x = 9 – ((12 / 3) + 3 * 2) – 1.
The expression is now evaluated as:
First Pass:
Step 1: x = 9 – (4 + 3 * 2) – 1
Step 2: x= 9 – (4 + 6) – 1
Step 3: x= 9 – 10 -1
Second Pass
Step 1: x= - 1 – 1
Step 2: x = -2.
Evaluation of Arithmetic expression:
1. First, parenthesized sub expressions from left to right are evaluated.
2. If parentheses are nested, the evaluation begins with the innermost sub-expression.
3. The precedence rule is applied in determining the order of application of operators in
evaluating sub-expressions.
4. The associativity rule is applied when to or more operators of the same precedence appear
in a subexpression.
5. Arithmetic expressions are evaluated from left to right using the rules of precedence.
6. When parentheses are used, the expressions within parentheses assume highest priority.
Type conversion in expressions :
Implicit Type Conversion :
 C automatically converts any intermediate values to the proper type so that expression
can be evaluated without losing any significance.
 This automatic conversion is known as implicit type conversion.
 During evaluation, if the operands are of different types, the lower type is
automatically converted to the higher type before the operation proceeds.
 And the result is always of the higher type.
 For example: 5/2 = 2
 5/2.0 = 2.5 (Implicit type conversion)
 5.0/2 = 2.5 (Implicit type conversion)
Explicit Type Conversion:
 There are instances when we want to force a type conversion in a way that is different
from the automatic conversion.
 This problem is solved by converting locally one of the variables to the higher type.
 For Example: 5/2 = 2 (float)
 5/2 = 2.5 (Explicit type conversion)
 5/ (float)2 = 2.5 (Explicit type conversion)
 Explicit type conversion is also known as type casting.
 There are instances when we want to force a type conversion in a way that is different
from the automatic conversion.
 This problem is solved by converting locally one of the variables to the higher type.
Decision Statements: if, if-else, and nested if statements:
 Decision making and branching statement transfers the control from one line to
another line, based on some condition and the execution continues from there.
IF STATEMENT:
 if statement is a conditional control statement.
 Based on some condition(Boolean value of an expression), it executes one block of
statements, ignoring another block of statements.
If …… else:
 The condition is checked.
 If it is true, the Statement Block 1 is executed,( ignoring Statement Block 2 and
comes to the next statement.)
 If it is false, the Statement B lock 2 is executed, (ignoring Statement Block 1 and
comes to the next statement.)
Nested if:
 If, an if statement contains another if block inside it, then it is known as Nested if
statement.
 The condition 1 is checked. If it is true, Condition2 is checked.
 If condition1 and 2 are true Statement Block1 is executed, (ignoring Statement Block
2 and Statement Block3 and comes to the Next Statement).
 if condition1 is true and Condition2 is false, Statement Block2 is executed, (ignoring
Statement Block 1 and Statement Block3 and comes to the Next Statement.)
 If condition1 is false, the Statement B lock3 is executed, (ignoring Statement Block 1
and Statement Block2 and comes to the Next Statement).
SWITCH STATEMENT :
 A switch statement allows a variable to be tested for equality against a list of values.
 Each value is called a case, and the variable being switched on is checked for each
switch case.
 The expression is evaluated.
 The value is matched with the case value
 If match occurs, that statement block is executed until break statement is reached and
comes to the next statement’
 If no match occurs, the default block is executed.
Rules:
 The expression used in a switch statement must have an integral value
 Any number of case statements are allowed within a switch.
 Each case is followed by the value to be compared to and a colon.
 The constant value for a case must be the same data type as the variable in the switch.
 It must be a constant or a literal.
 If no break appears, the flow of control will fall through to subsequent cases until a
break is reached. A switch statement can have an optional default case, which must
appear at the end of the switch.
 The default case can be used for performing a task when none of the cases is true.
 No break is needed in the default case.

UNIT – II

Function:
 A large C program is divided into basic building blocks called C function.
 C function contains set of instructions enclosed by “{ }” which performs specific
operation in a C program.
 Collection of these functions creates a C program.
Types of Function in C:
1) Library Functions in C:
 C provides library functions for performing some operations.
 These functions are present in the c library and they are predefined.
 For example :
sqrt( ) is a mathematical library function which is used for finding the square root of
any number .
scanf( ) and printf( ) are input and output library function.
strcmp() and strlen() for string manipulations.
2) User Defined Functions in C:
 A user can create their own functions for performing any specific task of program
are called user defined functions.
 To create and use these function we have to know these 3 elements.
1.Function Declaration
2.Function Definition
3.Function Call
Function Declaration:
A function must also be declared before its used.
Function declaration informs the compiler about the function name, parameters and
its return type.
The actual body of the function can be defined separately.
Function declaration consists of 4 parts.
 return type (function type).
 function name.
 parameter list.
 terminating semicolon
Eg:
int add (int x, int y);
Function Definition:
 The function definition consists of the whole description and code of a
function.
 It tells that what the function is doing and what are the input outputs for
that.
 A function is called by simply writing the name of the function followed
by the argument list inside the parenthesis.
Eg:
return-type function-name(parameters)
{
declarations
statements
return value;
}

Function Call:
 A function can be called by simply using the function name followed by a list
of actual parameters(or arguments).
Example:
Void main( )
{
int c;
c = add(10 , 5); // function calls
printf("%d\n", c);
}
Category of Functions:
(i ) Functions with no arguments and no return values.
(ii) Functions with arguments and no return values.
(iii) Functions with arguments and return values.
(iv) Functions with no arguments and return values.
v) Functions that return multiple values.

(i ) Functions with no arguments and no return values:


 When a function has no arguments, it does not return any data from calling
function.
 When a function does not return a value, the calling function does not receive
any data from the called function.
 That is there is no data transfer between the calling function and the called
function.

Example:
#include<stdio.h>
void printmsg()
{
printf ("Hello ! I Am A Function .");
}
int main()
{
printmsg( );
return 0;
}
(ii) Functions with arguments and no return values:
 When a function has arguments data is transferred from calling function to
called function.
 The called function receives data from calling function and does not send back
any values to calling function.
 Because it doesn’t have return value.
Example:
#include<stdio.h>
void add(int,int);
void main( )
{
int a, b;
printf(“Enter two values: ”);
scanf(“%d%d”,&a,&b);
add(a,b);
}
void add (intx, inty)
{
int z ;
z=x+y;
printf ("\n The sum =%d",z);
}
(iii) Functions with arguments and return values:-
 In this data is transferred between calling and called function.
 That means called function receives data from calling function and called
function also sends the return value to the calling function.
Example:
#include<stdio.h>
void add(int,int);
void main()
{
int a, b, c;
printf(“Enter two values: ”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf ("The sum =%d",c);
}
int add (int x, int y)
{
int z; z=x+y;
return z;
}

(iv)Functions with no arguments but return types:-


 When function has no arguments data cannot be transferred to called function.
 But the called function can send some return value to the calling function.
Example:
#include<stdio.h>
void add(int,int);
void main( )
{
int c;
c=add( );
printf ("The sum =%d",c);
}
int add ( )
{
int x,y,z;
printf(“Enter two values: ”);
scanf(“%d%d”,&a,&b);
z=x+y;
return z;
}

Nested Functions:
 It provides a facility to write one function with in another function.
 There is no limit as to how deeply functions can be nested.
 This is called nesting of function.
Eg:
#include<stdio.h>
Void main()
{
func1();
getch();
}
Void func1()
{
for(int i=1;i<=10;i++)
{
Func2();
}
}
Void func2()
{
Printf(“\n%d”,i)
}
Recursion:
 A function that calls itself is known as a recursive function.
 Recursion is the process of repeating items in a self-similar way.
 A function inside the same function, then it is called a recursive call of the
function.
Eg:
#include<stdio.h>
int factorial(int n)
{
if(n==0)
return 1;
else
return(factorial(n-1)*n);
}
int main()
{
int num,f;
printf("Enter a number: ");
scanf("%d",&num);
f=factorial(num);
printf("Factorial of %d = %d",num,f);
getch();
}

Passing Parameters to Functions:


 When a function is called, the calling function has to pass some values to the
called functions.
 There are two ways for pass the parameters to the functions:
Call by value:
 Here the values of the variables are passed by the calling function to the called
function.
 If any value of the parameter in the called function has to be modified the change
will be reflected only in the called function.
Eg:
#include<stdio.h>
int sum (int n);
void main( )
{
int a = 5;
printf("\n The value of 'a' before the calling function is = %d", a);
a = sum(a);
printf("\n The value of 'a' after calling the function is = %d", a);
}
int sum (int n)
{
n = n + 20;
printf("\n Value of 'n' in the called function is = %d", n);
return n;
}

Call by reference:
 Here, the address of the variables are passed by the calling function to the called
function.
 The address which is used inside the function is used to access the actual argument.
 If there are any changes made in the parameters, they affect the passed argument.
 For passing a value to the reference, the argument pointers are passed to the
functions just like any other value.
Example:
#include<stdio.h>
int sum (int *n);
void main()
{
int a = 5;
printf("\n The value of 'a' before the calling function is = %d", a);
sum(&a);
printf("\n The value of 'a' after calling the function is = %d", a);
} t
int sum (int *n)
n
{ u
m
*n = *n + 20;
[
printf("\n value of 'n' in 1
the called function is = 0
%d", n); ]
)
}
;

Functions with Arrays: m


a
 When an array is an i
argument to a n
function, only the (
address of the first )
element of the array {
is passed, not a i
copy of the entire n
array. t

 There are three ways to t


declare a parameter that [
is to receive an array 1
pointer. 0
]
 First it can be ,
declared as an array i
of the same type ;
and size as that
used to call the f
function, o
r
Example: (
i
=
#include <stdio.h> 0
v ;
o i
i <
d 1
0
d ;
i +
s +
p i
l )
a t
y [
( i
i ]
n =
i
;
UNIT-III
C Pointers
d
i
s
p
l
a
y
(
t
)
;
return 0;
}
void display(int num[10])
{
int i;
for(i=0;i<10;i++) cout
<<num[i]<<' ';
}

Introduction to pointers
The pointer in C language is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other pointer.
The size of the pointer depends on the architecture. However, in 32-bit architecture
the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.

int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of
type integer.
Advantage of pointer
1. Pointers save memory space.
2. Execution time with pointers is faster because data are manipulated with the address,
that is, direct access to memory location.
3. Pointers are used with data structures. They are useful for representing two-
dimensional and multi-dimensional arrays.
4. An array, of any type, can be accessed with the help of pointers, without considering
its subscript range.
5. Pointers are used for file handling.
6. Pointers are used to allocate memory dynamically.
7. We can return multiple values from a function using the pointer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also
known as indirection pointer used to dereference a pointer.

int *a;//pointer
to int char
*c;//pointer to
char

Pointer Example
An example of using pointers to print the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number
variable, i.e., fff4. The value of number variable is 50. But the address of pointer
variable p is aaa3.
Example:
#include<
stdio.h>
int main()
{
int
number
=50; int
*p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number
therefore pr inting p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference
a pointe r therefore if we print *p, we will get the value stored at the address
contained by p.
return 0;
}
Output
Address of number
variable is fff4 Address of
p variable is fff4 Value of
p variable is 50
C Double Pointer (Pointer to Pointer)
As we know that, a pointer is used to store the address of a variable in C. Pointer
reduces the access time of a variable. However, In C, we can also define a pointer to
store the address of another pointer. Such pointer is known as a double pointer
(pointer to pointer). The first pointer is used to store the address of a variable
whereas the second pointer is used to store the address of the first pointer. Let's
understand it by the diagram given below.

The syntax of declaring a double pointer is given below.


int **p; // pointer to a pointer which is pointing to an integer.

Consider the following example.


#include<
stdio.h>
void main
()
{
int a = 10;
int *p;
int **pp;
p = &a; // pointer p is pointing to the address of a
pp = &p; // pointer pp is a double pointer pointing to the address of pointer p
printf("address of a: %x\n",p); // Address of a will be printed
printf("address of p: %x\n",pp); // Address of p will be printed
printf("value stored at p: %d\n",*p); // value stoted at the address contained by p
i.e. 10 wil l be printed
printf("value stored at pp: %d\n",**pp); // value stored at the address contained by
the poin ter stoyred at pp
}
Output
address of a:
d26a8734
address of p:
d26a8738 value
stored at p: 10
value stored at
pp: 10

Pointers and arrays


Pointers and Array representations are very much related to each other and can
be interchangeably used in the right context. Arrays can be single or multidimensional
and are stored in contiguous memory blocks in our system, so it is easy for pointers to
get associated with the arrays.
An array name is generally treated as a pointer to the first element of the array
and if we store the base address of the array in another pointer variable then we can
easily manipulate the array using pointer arithmetic in a C Program.
Let us now look at how an array is stored in our system's memory and how to
declare and initialize an array then we will move to the relationship of pointers with
arrays.
In C Language, we can declare an integer array using the below

statement : int arr[5];

The above statement will allocate 5 integer blocks and will occupy a
memory of 20 Bytes in the system (5 * 4 = 20, 5 is size of the array and 44 bytes is
the space occupied by an integer block, total = 20).
Below is the representation of how the array is stored in the system's memory.
Let the base address allocated by the system to the array is 300.
Example:
#include <stdio.h>

int main()
{
// array declaration and initialization
int arr[5] = {3, 5, 7, 9, 11}, i;

// both `arr` and `&arr` return the address of the first element of the
array. int *ptr = arr;

// printing the elements of array using addition arithmetic on pointer


for(i = 0; i < 5; i++)
{
printf("%d ", *(ptr + i));
}

return 0;
}
OUTPUT :
3 5 7 9 11

Array of Pointers
As we know, arrays are collections of elements stored in contiguous memory
locations. An array of pointers is similar to any other array in C Language. It is an
array which contains numerous pointer variables and these pointer variables can store
address values of some other variables having the same data type.

Syntax to declare a normal array :

data_type (array_name)[sizeof_array];

Example :

int arr[10];

Syntax to declare a pointer array :

data_type (*array_name)[sizeof_array];
Example :

int *ptr[10];

We are using * operator to define that the ptr array is an array of pointers.
An application of an array of pointers is that it becomes easy to store strings in a char
pointer array and it also reduces the memory consumption.
Example:
#include <stdio.h>

int main()
{
char *fruits[5] = {"apple", "banana", "mango", "grapes", "orange"}, i;

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


{
printf("%s\n", fruits[i]);
}

return 0;
}

Output:
a
p
p
l
e

b
a
n
a
n
a

m
a
n
g
o

g
r
a
p
e
s

o
r
a
n
g
e

Explanation :
*) We have declared and initialized an array of pointers named fruits. It can contain
addresses of char type variables only. Array representation and comparison of
simple char array with char pointers array in the memory:
*) We are printing the strings pointed by the pointers in the array using the printf()
statement.
Pointers as Function Argument
Pointer as a function parameter is used to hold addresses of arguments passed
during function call. This is also known as call by reference. When a function is
called by reference any change made to the reference variable will effect the original
variable.

Example: Swapping two numbers using Pointer


#include <stdio.h>
void swap(int *a,
int *b); int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
swap(&m, &n); //passing address of m and n to the swap
function printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}
/*
pointer 'a' and 'b' holds and
points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
m = 10
n = 20

After

Swappin

g: m =

20
n = 10
Functions returning Pointer variables
A function can also return a pointer to the calling function. In this case you
must be careful, because local variables of function doesn't live outside the function.
They have scope only inside the function. Hence if you return a pointer connected to a
local variable, that pointer will be pointing to nothing when the function ends.
Example:
#include
<stdio.h> int*
larger(int*,
int*); void
main()
{
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
int* larger(int *x, int *y)
{
if(*x > *y)
return x;
else
return y;
}
Output:
92 is larger

Pointer to functions
It is possible to declare a pointer pointing to a function which can then be used as
an argument in another function. A pointer to a function is declared as follows,
Syntax:
type (*pointer-name)(parameter);

Example :

int (*sum)(); //legal declaration of pointer to function


int *sum(); //This is not a declaration of pointer to function
A function pointer can point to a specific function when it is assigned the name of that
function. int sum(int, int);
int (*s)
(int,
int); s =
sum;
Here s is a pointer to a function sum. Now sum can be called using function pointer
s along with providing the required argument values.
s (10, 20);

Example of Pointer to Function


#include
<stdio.h>
int sum(int
x, int y)
{
return x+y;
}
int main( )
{
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d", s);
return 0;
}
Output:
Sum is 25

Structures
Introduction:
Structure in c is a user-defined data type that enables us to store the collection
of different data types. Each element of a structure is called a member. Structures can
simulate the use of classes and templates as it can store various information
The ,struct keyword is used to define the structure. Let's see the syntax to define the
structure in c.
Syntax:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

Let's see the example to define a structure for an entity employee in c.

struct employee
{ int id;
char name[20];
float salary;
};

The following image shows the memory allocation of the structure employee that is
defined in the above example.

Here, struct is the keyword; employee is the name of the structure; id, name, and
salary are the members or fields of the structure. Let's understand it by the diagram
given below:

Declaring Structure and its variables


Structure data type is declared using the keyword ‘ struct ‘ . The variables
declared in the structure are called structure elements or members. Each member may
belong to a different type of data. Also a structure member declaration is similar to the
declaration of variables of any other data type. Declaration of structure includes the
following elements
The keyword
struct.
The structure
tag name.
List of variable names separated by
commas. A termination semicolon.
Following is the syntax to define a structure and it’s
members – struct tag_name
{
data_type member1;
data_type member2;
--- ---
--- ---
};
After defining the structure, declare the structure as follow –

struct tag_name variable_1, variable_2;

You can also define and declare the structure at the one place only. Also remember
that the members of the structure themselves are not variables. They don’t occupy any
memory until they are associated with the
structure variable. Example of declaring a structure –
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
struct book_bank book1, book2, book3;

Here book1, book2 and book3 are the structure variables representing three books.
Each structure variable will contain the title, author, pages and price data items
respectively.
Accessing Structure Members
As mentioned earlier, the members of the structure themselves are not
variables. So we cannot access these members as we access the variables. In C
programming language to access the members of the structure, they should be linked
to the structure variables. To do this (.) dot operator also known as member operator,
is used for linking the members with the structure variable. Syntax for this is as
follows –
structure_variable.member_name

For ex -
book1.price
book1.pages
These are the variables representing the price and page of book1, and this full variable
now can be treated like any other ordinary variable.
C Structure example
#include<st
dio.h>
#include
<string.h>
struct
employee
{ int id;
char name[50];
}e1; //declaring e1 variable for
structure int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Mithush");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n",
e1.name); return 0;
}
Output:
employee 1 id : 101
employee 1 name :
Mithush

Structure Initialization
Structure members cannot be initialized like other variables inside the
structure definition. This is because when a structure is defined, no memory is
allocated to the structure’s data members at this point. Memory is only allocated when
a structure variable is declared. Consider the following code snippet.
struct rectangle
{
// structure definition
int length = 10; // COMPILER ERROR: cannot initialize members here.
int breadth = 6; // COMPILER ERROR: cannot initialize members here.
};
A compilation error will be thrown when the data members of the structure are
initialized inside the structure.
To initialize a structure’s data member, create a structure variable. This
variable can access all the members of the structure and modify their values. Consider
the following example which initializes a structure’s members using the structure
variables.
struct rectangle
{
// structure definition
int length;
int breadth;
};
int main()
{
struct rectangle my_rect; // structure variables;
my_rect.length = 10;
my_rect.breadth = 6;
}
In the above example, the structure variable my_rect is modifying the data
members of the structure. The data members are separately available to my_rect as a
copy. Any other structure variable will get its own copy, and it will be able to modify
its version of the length and breadth.
Rules for Initialization structure
There are few rules to keep in mind while initializing structure variables at compile-time.
 We cannot initialize individual members inside the structure template.
 The order of values enclosed in braces must match the order of members in the
structure definition.
 It is permitted to have a partial initialization. We can initialize only the first few
members and leave the remaining blank. The uninitialized members should be only at
the end of the list.
 The uninitialized members will be assigned default values, i.e – Zero for integer and
floating point numbers and ‘\0’ for characters and strings

Arrays of Structures
The main advantage of an array is we can represent multiple values with a
single variable. So the reusability of code improves; also, readability is increased. If
there is no array of structure, we need to store many values in multiple structure
variables, which is redundant. For example, We don't need to remember structure
variables like:

struct student s1, s2, s3;


Instead, we can use an array of structures like:
struct student s[3];

Before, we created 3 different variables to store 3 students. Now all this can be
done efficiently in one single array.
An array of structres in C can be defined as the collection of multiple
structures variables where each variable contains information about different
entities. The array of structures in C are used to store information about multiple
entities of different data types. The array of structures is also known as the collection
of structures.
Let's see an example of an array of structures that stores information of 5 students and prints
it.
#include<st
dio.h>
#include
<string.h>
struct
student{
int rollno;
char name[10];
};
int
mai
n()
{ in
t i;
struct student st[5];
printf("Enter Records of 5
students"); for(i=0;i<5;i++){
printf("\nEnter
Rollno:");
scanf("%d",&st[i].
rollno); printf("\
nEnter Name:");
scanf("%s",&st[i].
name);
}
printf("\nStudent Information
List:"); for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5
students Enter
Rollno:1
Enter
Name:Sono
o Enter
Rollno:2
Enter
Name:Rata
n Enter
Rollno:3
Enter
Name:Vima
l Enter
Rollno:4
Enter
Name:Jame
s Enter
Rollno:5
Enter
Name:Sarfr
az

Student Information List:


Rollno:1,
Name:Sonoo
Rollno:2,
Name:Ratan
Rollno:3,
Name:Vimal
Rollno:4,
Name:James
Rollno:5,
Name:Sarfraz

Pointer to Structure
Pointer to structure holds the address of the entire structure.
It is used to create complex data structures such as linked lists, trees, graphs and so on.
The members of the structure can be accessed using a special operator called as
an arrow operator ( -> ).
Declaration
Following is the declaration for pointers to structures in C
programming − struct tagname *ptr;
For example
struct student *s
It is explained below how to access the pointers to
structures. Ptr-> membername;
For example : s->sno, s->sname, s->marks;
Example Program
The following program shows the usage of pointers to
structures − #include<stdio.h>
struct student{
int sno;
char sname[30];
float marks;
};
main ( ){
struct student s;
struct student *st;
printf("enter sno, sname, marks:");
scanf ("%d%s%f", & s.sno, s.sname, &s. marks);
st = &s;
printf ("details of the student are");
printf ("Number = %d", st ->sno);
printf ("name = %s", st->sname);
printf ("marks =%f", st ->marks);
getch ( );
}
Output
enter sno, sname, marks:1
Lucky 98 details of the
student are:
Numbe
r=1
name =
Lucky
marks =98.000000

Structures and Functions in C


The C Programming allows us to pass the structures as the function
parameters. Please refer to Functions in C Post before reading this post. We can pass
the C structures to functions in 3 ways:
 Passing each item of the structure as a function argument. It is similar to passing
normal values as arguments. Although it is easy to implement, we don’t use this
approach because if the size of a structure is a bit larger, then our life becomes
miserable.
 Pass the whole structure as a value.
 We can also Pass the address of the structure (pass by reference).
Pass Structure Members To Functions:
Sometimes we don’t want to pass the entire structure to the function. We want
to pass only a few members of the structure. We can use the dot (.) operator to access
the individual members of the structure and pass them to the function.
Let us create a structure to hold the details of a student, such as the name of
the student, roll number, and marks, and print out just the roll number and marks
using a function. Passing the entire structure to the function is unnecessary when we
want to print only a few structure members.
In the above example, the structure contains the name of the student as well, but we
need to print only the percentage and roll number. Therefore we pass only the
required structure members to function.
Let us look at the code and understand how to pass structure members to the function.

#include
<stdio.h>
struct
student {
char name[50];
int per,rno;
};

void display(int

a, int b); int

main() {
struct student s1;

printf("Enter name: ");


gets(s1.name);
printf("Enter the roll number: ");
scanf("%d",&s1.rno);
printf("Enter percentage: ");
scanf("%d", &s1.per);
display(s1.rno,s1.per);
return 0;
}

void display(int a, int b ) { printf("\


nDisplaying information\n");
printf("Roll number: %d", a);
printf("\nPercentage: %d", b);
}
Output
Enter name:
Gourav Enter the
roll number: 42
Enter percentage:
98

Displaying
information
Roll number:
42
Percentage: 98

In the above code, we created a structure to hold the name, roll number, and
percentage of the student. The input from the user is stored in the structure. A function
named display() is
created, which takes the roll number and the percentage of the student as the
parameter. Using the dot (.) operator, we accessed the member of structure and passed
it to the function.

Pass Structure to a Function by Value in C


If the structure is passed to the function by the value, then Changes made to
the structure variable members within the function will not reflect the original
structure members.
This program for Structures and Functions in C, User is asked to enter, Student Name,
First Year Marks, and Second Year Marks. By using these values, this program will
check whether the student is eligible for a scholarship or not.
#include
<stdio.h>
struct
Student
{
char Student_Name[50];
float First_Year_Marks;
float Second_Year_Marks;
};
void PassBy_Value(struct Student
Students); int main()
{
struct Student Student1;
printf("\nPlease Enter the Student Name \n");
scanf("%s",&Student1.Student_Name);
printf("\nPlease Enter Student Inter First Year Marks \n");
scanf("%f",&Student1.First_Year_Marks);
printf("\nPlease Enter Student Inter Second Year Marks \n");
scanf("%f",&Student1.Second_Year_Marks);
PassBy_Value(Student1);
return 0;
}
void PassBy_Value(struct Student Students)
{
float Sum, Average;
Sum = Students.First_Year_Marks + Students.Second_Year_Marks;
Average = Sum/2;
if(Average > 900)
{
printf("\n %s is Eligible for Scholorship",Students.Student_Name);
}
else
{
printf("\n %s is Not Eligible for Scholorship",Students.Student_Name);
}

}
Output:
Student Name =
Pavin First Year
Marks = 800;
Second Year
Marks = 750; Sum
= 1550
Average = 775
He is Not Eligible for Scholarship

In these Structures and Functions in C example, Declared the Student structure


with Student Name, First Year Marks, Second Year Marks members with appropriate
Data Types.
Within the main(), we created the Student structure variable
Student1 struct Student Student1;
Printf and scanf statements in the next lines used to ask the users to enter the Student
Name, First Year Marks, Second Year Marks.
In the next line, we called the user-defined function
PassBy_Value(Student1);
When the compiler reaches this, then it will traverse to the top. And check for the
function definition or else declaration of the PassBy_Value (struct). If the function
fails to identify the function with PassBy_Value name, then it will throw an error.
We declared 2 float local variables Sum and Average to calculate the Sum and
average of every student’s first-year marks and second-year marks. Depending upon
the result, this program will find whether the student is eligible for Scholarship or
Not.
Sum = Students.First_Year_Marks +

Students.Second_Year_Marks; Sum = 800 + 750 = 1550

Average = Sum/2;

Average = 1550/2 = 775


In the next line, We used If statement to check whether the calculated average is
greater than 900 or not
If the calculated Average is Greater than 900 then, He is Eligible for Scholarship
If the calculated Average is Less than or Equal to 900 then, He is Not Eligible for
Scholarship
Passing Structure to a Function By Reference
It employs a concept called pointers to pass the structure as an argument. In this case,
the address location of the structure is passed to the called function. The function can
access indirectly the entire structure and work on it. This is similar to the way arrays
are passed to function.
#include
<stdio.h>
struct
Student
{
char Student_Name[50];
float First_Year_Marks;
float Second_Year_Marks;
};
void PassBy_Ref(struct Student
*Students); int main()
{
struct Student *Student1;
printf("\nPlease Enter the Student Name \n");
scanf("%s",&Student1.Student_Name);
printf("\nPlease Enter Student Inter First Year Marks \n");
scanf("%f",&Student1.First_Year_Marks);
printf("\nPlease Enter Student Inter Second Year Marks \n");
scanf("%f",&Student1.Second_Year_Marks);
PassBy_Value(Student1);
return 0;
}
void PassBy_Ref(struct Student *Students)
{
float Sum, Average;
Sum = Students.First_Year_Marks + Students.Second_Year_Marks;
Average = Sum/2;
if(Average >=900)
{
printf("\n %s is Eligible for Scholorship",Students.Student_Name);
}
else
{
printf("\n %s is Not Eligible for Scholorship",Students.Student_Name);
}

}
Output:
Student Name =
Mithush First Year
Marks = 900;
Second Year
Marks = 900; Sum
= 1800
Average = 900
He is Eligible for Scholarship

typedef in C
The typedef is a keyword used in C programming to provide some meaningful
names to the already existing variable in the C program. It behaves similarly as we
define the alias for the commands. In short, we can say that this keyword is used to
redefine the name of an already existing variable.
Syntax of typedef
typedef <existing_name> <alias_name>
In the above syntax, 'existing_name' is the name of an already existing variable while
'alias name' is another name given to the existing variable.
For example, suppose we want to create a variable of type unsigned int, then it
becomes a tedious task if we want to declare multiple variables of this type. To
overcome the problem, we use a typedef keyword.
typedef unsigned int unit;
In the above statements, we have declared the unit variable of type unsigned int by
using a typedef keyword.
Now, we can create the variables of type unsigned int by writing the following statement:
unit a, b;
instead of writing:
unsigned int a, b;
Till now, we have observed that the typedef keyword provides a nice shortcut by
providing an alternative name for an already existing variable. This keyword is useful
when we are dealing with the long data type especially, structure declarations.
Let's understand through a simple example.
#include
<stdio.h>
int main()
{
typedef unsigned
int unit; unit i,j;
i
=
1
0
;

j
=
2
0
;
printf("Value of i is :
%d",i); printf("\
nValue of j is :%d",j);
return 0;
}
Output
Value of
i is :10
Value of
j is :20

Using typedef with structures


Consider the below structure declaration:
struct student
{
char
name[2
0]; int
age;
};
struct student s1;
In the above structure declaration, we have created the variable of student type by writing
the following statement:
struct student s1;
The above statement shows the creation of a variable, i.e., s1, but the statement is quite big. To
avoid such a big statement, we use the typedef keyword to create the variable of type student.
Now, we can use the stud variable in a program to create the variables of
type struct student.
The above typedef can be written as:
typedef struct student
{
char
name[2
0]; int
age;
}
stu
d;
stu
d
s1,
s2;
From the above declarations, we conclude that typedef keyword reduces the length of
the code and complexity of data types. It also helps in understanding the program.
Let's see another example where we typedef the structure declaration.
#include
<stdio.h>
typedef struct
student
{
char
name[2
0]; int
age;
}stud;
int main()
{
stud s1;
printf("Enter the details of student
s1: "); printf("\nEnter the name of
the student:");
scanf("%s",&s1.name);
printf("\nEnter the age of
student:");
scanf("%d",&s1.age);
printf("\n Name of the student is : %s",
s1.name); printf("\n Age of the student
is : %d", s1.age); return 0; }
Output
Enter the details of student s1:
Enter the name of the
student: Peter Enter the age
of student: 28
Name of the student
is : Peter Age of the
student is : 28
Using typedef with pointers
We can also provide another name or alias name to the pointer variables with the help of
the typedef.
For example, we normally declare a pointer, as shown below:
int* ptr;
We can rename the above pointer variable as given below:
typedef int* ptr;
In the above statement, we have declared the variable of type int*. Now, we can create
the variable of type int* by simply using the 'ptr' variable as shown in the below statement:
ptr p1, p2 ;
In the above statement, p1 and p2 are the variables of type 'ptr'.
Enum in C
The enum in C is also known as the enumerated type. It is a user-defined data
type that consists of integer values, and it provides meaningful names to these values.
The use of enum in C makes the program easy to understand and maintain. The enum
is defined by using the enum keyword.
The following is the way to define the enum in C:

enum flag{integer_const1, integer_const2,. integter_constN};

In the above declaration, we define the enum named as flag containing 'N' integer
constants. The default value of integer_const1 is 0, integer_const2 is 1, and so on. We
can also change the default value of the integer constants at the time of the
declaration.
For example:
enum fruits{mango, apple, strawberry, papaya};
The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3. If we want
to change these default values, then we can do as given below:
enu
m
fruits
{ ma
ngo=
2,
appl
e=1,
strawberry=5,
papaya=7,
};
Example:
#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
enum weekdays w; // variable declaration of weekdays type
w=Monday; // assigning value of Monday to w.
printf("The value of w is %d",w);
return 0;
}
In the above code, we create an enum type named as weekdays, and it contains the
name of all the seven days. We have assigned 1 value to the Sunday, and all other
names will be given a value as the previous value plus one.

Output

Union
A union is a collection of different types of data elements in a single entity. It
is a collection of primitive and derived data type variables. By using a union, we can
create user- defined data type elements. The size of a union is the max size of a
member variable.
In the implementation, for manipulation of the data, if we are using only one
member then it is recommended to go for the union. When we are working with
unions, all member variables will share the same memory location. By using union,
when we are manipulating multiple members then actual data is lost.
The union is also a collection of dissimilar elements in contiguous memory
locations, under a single name. They are user-defined data types. The name of the
union (or the tag name) is treated as a data type, and the elements of the structure are
known as its members. No memory is allocated during the definition of the union.
Memory is only allocated when its variables are created (which is usually preceded by
the keyword union). The variables of the union types occupy the memory size which
is the maximum size among all its members. At one time simultaneously data can be
stored in only one of its members. The members can be accessed by using the dot (.)
operator.
The union is quite similar to the structures in C. The union is also a derived
type of structure. A union can be defined in the same manner as structures just the
keyword used in defining union in the union where the keyword used in defining
structure was struct.
Syntax of Union in C Language:
Example of Union:

Union variables can be created in a similar manner as structure variables.

In both the cases, union variables c1, c2, and union pointer variable c3 of type union
car is created.
Accessing members of a union
The member of unions can be accessed in a similar manner as that structure.
Suppose, you want to access the price for union variable c1 in the above example, it
can be accessed as c1.price. If you want to access the price for union pointer variable
c3, it can be accessed as (*c3).price or as c3->price.
Example:
#include
<stdio.h>
#include
<string.h>
union Data
{
int i;
float f;
char str[20];
};
int main ()
{
union Data data;
data.i = 10;
printf ("data.i : %d\n", data.i);
data.f = 220.5;
printf ("data.f : %f\n", data.f); strcpy
(data.str, "C Programming"); printf
("data.str : %s\n", data.str); return 0;
}
Output:

Difference between Structure and Union in C


UNIT IV

STRING HANDLING FUNCTIONS

There are many important string functions defined in "string.h" library.

No Function Description
.

1) strlen(string name) returns the length of string name.

2) strcpy(string1, string2) copies the contents of source string to destination string.

3) strcat(string1, string2) concats or joins first string with second string. The result of the string is stored in
first string.

4) strcmp(string1,string2) compares the first string with second string. If both strings are same, it returns 0.

5) strrev(string) returns reverse string.

STRING LENGTH

The strlen() function returns the length of the given string. It doesn't count null character.

Syntax

strlen(Varibale name);

Example

#include<stdio.h>
#include <string.h>
void main()
{
char ch[20];
int x;
ch=”HELLO”;
x= strlen(ch);
printf("Length of string is: %d",x);
}

Output:

Length of string is: 5

COPY STRING

The strcpy(destination, source) function copies the source string in destination.

Syntax

Strcpy(variable1,variable2);

#include<stdio.h>
#include <string.h>
void main()
{
char ch1[20]=”Main”,ch2[20]=”Program”;
strcpy(ch1,ch2);
printf("Value of second string is: %s",ch1);
}

Output:

Value of second string is: program

STRING CONCATENATION

The strcat(first_string, second_string) function concatenates two strings and result is returned to
first_string.
Syntax

strcat(variable1,variable2);

#include<stdio.h>
#include <string.h>
void main()
{
char ch1[10], ch2[10];
ch1=”Hai”;
ch2=”Hello”;
strcat(ch1,ch2);
printf("Value of first string is: %s",ch1);
}

Output:

Value of first string is: hello

COMPARE STRING

The strcmp (first_string, second_string) function compares two string and returns 0 if both strings are equal.

Syntax

strcmp(variable1,variable2);

#include<stdio.h>
#include <string.h>
void main()
{
char str1[20],str2[20];
str1[20]=”Hello”;
str2[20]=”Hello”;
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
}

Output:

Enter 1st string: hello


Enter 2nd string: hello
Strings are equal

STRING REVERSE

The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev() function.

Syntax

strrev(variable1);

Example

#include<stdio.h>
#include <string.h>
void main()
{
char str1[20], str2;
str1=”Name”;
printf("String is: %s",str1);
str2= strrev(str1) ;
printf("\nReverse String is: %s",str2);
}

Output:

Enter string: name


String is: name
Reverse String is: eman

String Handling Input and Output Functions


1) getchar() - Read a single character from the user
2) putchar() - Write a single character to the user
3) gets() - Read a string from the user
4) puts() - Write a string to the user

getchar() and putchar() functions

The getchar() and putchar() are declared in the header file stdio.h. Both the functions are involved in the
input/output operations of the character.

getchar() function

The getchar() function enables the user to enter a character. getchar() function help us to get a single character
as a input for instead of scanf() function.

Syntax

Variable name=getchar();

Reading a character using getchar()


#include<stdio.h>
void main ()
{
char s;
printf("Enter A Character ");
s=getchar();
printf("You entered %c",s);
}
Output
Enter A Character
X
You entered x

The getchar() function help us to reading and writing the character in easy manner.
putchar() function

The putchar() function enables the user to print a character. putchar() function help us to print a single character
as a output for instead of printf() function.

syntax

putchar(variable name);

Let's see an example to write a character using putchar() and print it on the console using putchar().

Example

#include<stdio.h>
#include <string.h>
void main()
{
char id;
printf("Enter A character: ");
id=getchar(); //read a character from user
printf("Your ID is: ");
putchar(id); //display a character
}
Output:
Enter A character: X
Your ID is: X

gets() and puts() functions

The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in the input/output
operations of the strings.

gets() function

The gets() function enables the user to enter some characters followed by the enter key. All the characters
entered by the user get stored in a character array. The null character is added to the array to make it a string.
The gets() allows the user to enter the space-separated strings. It returns the string entered by the user.
Syntax
gets(variable name);
Reading string using gets()
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
Output
Enter the string?
javatpoint is the best
You entered javatpoint is the best

The gets() function is risky to use since it doesn't perform any array bound checking and keep reading
the characters until the new line (enter) is encountered. It suffers from buffer overflow, which can be avoided
by using fgets(). The fgets() makes sure that not more than the maximum limit of characters are read. Consider
the following example.

puts() function

The puts() function is very much similar to printf() function. The puts() function is used to print the string
on the console which is previously read by using gets() or scanf() function. The puts() function returns an
integer value representing the number of characters being printed on the console. Since, it prints an additional
newline character with the string, which moves the cursor to the new line on the console, the integer value
returned by puts() will always be equal to the number of characters present in the string plus 1.

syntax

puts(variable name);

Let's see an example to read a string using gets() and print it on the console using puts().
Example:

#include<stdio.h>

#include <string.h>
void main()
{
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
}
Output:
Enter your name: Sonoo Jaiswal
Your name is: Sonoo Jaiswal

File Handling in C

In programming, we may require some specific input data to be generated several numbers of times.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large,
and only a limited amount of data can be displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again and again. However, if we need to do so, we
may store it onto the local file system which is volatile and can be accessed every time. Here, comes the need
of file handling in C.

File handling in C enables us to create, update, read, and delete the files stored on the local file system through
our C program. The following operations can be performed on a file.

o Creation of the new file

o Opening an existing file


o Reading from the file

o Writing to the file

o Deleting the file

Functions for file handling

There are many functions in the C library to open, read, write, search and close the file. A list of file functions
are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write set of data into the file

3 fscanf() Reads set of data from the file

4 putc() writes a character into the file

5 getc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 putw() writes an integer to file

9 getw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Opening File

We must open a file before it can be read, write, or update. The fopen() function is used to open a file. The
syntax of the fopen() is given below.
Syntax
FILE *fp;
fp=fopen( “filename”, “mode” );

The fopen() function accepts two parameters:

1) File Name

2) Data Structure

3) Purpose

We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

The fopen function works in the following way

o Firstly, It searches the file to be opened.

o Then, it loads the file from the disk and place it into the buffer. The buffer is used to provide efficiency
for the read operations.
o It sets up a character pointer which points to the first character of the file.

Closing File:

The fclose() function is used to close a file. The file must be closed after performing all the operations on it.
The syntax of fclose() function is given below:
Syntax

fclose( *fp );

Consider the following example which open and close a file in write and read mode.

Example

#include<stdio.h>
void main( )
{
FILE *fp ;
char ch;
fp = fopen("Input","w") ;
ch = getc ( fp ) ;
fp = fopen("Input","r") ;
printf("%c",ch) ;
fclose (fp ) ;
}
Output

The content of the file will be printed.

DISPLAY THE CONTENT OF THE FILE

Input and Output Operations on Files:

Once a file is opened, reading or writing to a file is accomplished using the standard I/O routines in file. File
supports list of I/O operations are below,

1)getc() - reads a character from file

2)putc() - writes a character into the file

3)getw() - writes an integer to file

4)putw() - writes an integer to file

5)fprintf() - write a set of data into the file

6)fscanf() - reads set of data from the file


putc() and getc() Functions in File

Writing a character in File

The putc() function is used to write a single character into file. It outputs a character to a stream.

Syntax:

putc(c,fp);

Example:

#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("Input", "w");//opening file
putc('a',fp);//writing single character into file
fclose(fp);//closing file
}
file1.txt
Reading a character in File

The getc() function returns a single character from the file. It gets a character from the stream. It returns EOF at
the end of file.

Syntax:

Variable name=getc(fp);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
fp=fopen("Read","r");

c=getc(fp);
printf("%c",c);
fclose(fp);
}

this is simple text message

putw() and getw() Functions in File

Writing integer value in File (putw())

The putw() function is used to write integer value into file. It outputs integer to a stream. This function would
be useful to deal with integer data.

Syntax:

putw(variable,fp);

Reading integer value in File (getw())

The getw() function returns integer data from the file. It gets integer from the stream. This function would be
useful to deal with integer data.

Syntax:

getw(fp);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int num;
num=10;
fp=fopen("Data","r");
printf(“Inserting a data in FILE”);
putw(number,fp);
printf(“Gettng a data from FILE”);
getw(fp);
fclose(fp);
}

Inserting a data in FILE


Gettng a data from FILE
10

fprintf() and fscanf()

Writing File (fprintf())

The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.

Syntax:

fprintf (fp, “control string”, list);

Example:

#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("Item", "w"); //opening file
fprintf(fp, "Hello file by fprintf"); //writing data into file
fclose(fp); //closing file
}

Reading File (fscanf())

The fscanf() function is used to read set of characters from file. It reads a word from the file and returns EOF at
the end of file.
Syntax:

fscanf(fp,”control string”,list)

Example:

#include <stdio.h>
main()
{
FILE *fp;
char name[20]; //creating char array to store data of file
fp = fopen("Item", "r");
fscanf(fp, "%s", name);
printf(“Result%s”,name);
fclose(fp);
}

Output:

Hello file by fprintf...

Random Access to files


1. fseek()
2. ftell()
3. rewind()

fseek() function

The fseek() function is used to set the file pointer to the specified offset. It is used to write data into file at
desired location.

Syntax:

fseek(fp, offset, position);


fp : Pointer to a FILE object that identifies the stream.

Offset : Number of bytes to offset from position

position: Position from where offset is added.

fseek() function for position

Value Meaning
0 Beginning of the file
1 Current position
2 End of the file

fseek() function for offset

Statement Meaning
fseek(fp,0L,0); Beginning of the file
fseek(fp,0L,1); Current position
fseek(fp,0L,2); End of the file

Example:

#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("Data","w+");
fputs("This is c program", fp);
fseek( fp, 7, 0 );
fputs("sonoo jaiswal", fp);
fclose(fp);
}

This is sonoo jaiswal

rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to use stream
many times.

Syntax:

rewind(fp);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("file","r");
c=fgetc(fp);
printf("%c",c);
rewind(fp); //moves the file pointer at beginning of the file
c=fgetc(fp)
printf("%c",c);
fclose(fp);
getch();
}

Output:

X
X

As you can see, rewind() function moves the file pointer at beginning of the file that is why "this is simple text"
is printed 2 times. If you don't call rewind() function, "this is simple text" will be printed only once.

ftell() function
The ftell() function returns the current file position of the specified stream. We can use ftell() function to get the
total size of a file after moving file pointer at the end of file. We can use SEEK_END constant to move the file
pointer at the end of file.

Syntax:

ftell(fp);

Example:

#include <stdio.h>
#include <conio.h>
void main ()
{
FILE *fp;
int length;
clrscr();
fp = fopen("file", "r");
fseek(fp, 0, 2);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
getch();
}

Output:

Size of file: 21 bytes

UNIT - V
Stack: LIFO concept, Stack operations, Array implementation of stack – Queue: FIFO concept, Queue operations, Array
implementation of queue – Singly Linked List: concepts, operations – Doubly Linked List: concepts, operations – Trees:
General trees, Binary trees.

STACKS
Stack Model :
A stack is a linear data structure which follows Last In First Out (LIFO) principle, in which both insertion and deletion
occur at only one end of the list called the Top.

Fig. 2.22 Stack Model

Example : - Pile of coins, a stack of trays in cafeteria.

Stack Representation
The following diagram depicts a stack and its operations

Basic 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 two primary operations −

 push() − Pushing (storing) an element on the stack.


 pop() − Removing (accessing) an element from the stack.

When data is PUSHed onto stack.

To use a stack efficiently, we need to check the status of stack as well. For the same purpose, the following
functionality is added to stacks −

 peek() − get the top data element of the stack, without removing it.
 isFull() − check if stack is full.
 isEmpty() − check if stack is empty.

At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointer always represents the
top of the stack, hence named top. The top pointer provides top value of the stack without actually removing it.

Fig. 2.23 Operations on stack

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.
 Step 5 − Returns success.

If the linked list is used to implement the stack, then in step 3, we need to allocate space dynamically.

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.
 Step 5 − Returns success.

Array Implementation of Stack


Stack can be implemented using arrays and pointers.
Array Implementation(PUSH)
In this implementation each stack is associated with a pop pointer, which is -1 for an empty
stack.

 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.
 Step 5 − Returns success.

Push an Element onto a Stack


void push (int x, Stack S)
{
if (IsFull (S))
Error (“Full Stack”);
else
{
Top = Top + 1;
S[Top] = X;
}
}
Array Implementation(POP)

 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.
 Step 5 − Returns success.

Pop an Element from the Stack

void pop (Stack S)


{
If(Isempty(S))
Error(“Empty Stack”);
Else
Top=Top-1;
S[Top]=Top++;
}
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.

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.

Few more functions are required to make the above-mentioned queue operation efficient. These are −

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

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.
 Step 5 − return success.
Sometimes, we also check to see if a queue is initialized or not, to handle any unforeseen situations.

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.
 Step 5 − Return success.
Array Implementation of Queue
Queue can be implemented using arrays and pointers.

Array Implementation(Enqueue)

 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.
 Step 5 − return success.

Enqueue an Element from the Stack


Void Enqueue (int x)
{
If(Rear>=Max_Arraysize)
Printf(“Queue is Overflow”);
Else
Rear=Rear+1;
Queue[Rear]=x;
}

Dequeue an Element from the Stack


Void Dequeue ()
{
If(Front<0)
Printf(“Queue is Underflow”);
Else
Front=Front-1;
Queue[Front]=Front+1;
}
Linked List
 A linked list is a Non Linear data structures
 A linked list is a collection of objects stored in a list form.
 A linked list is a sequence of items (objects) where every item is linked to the next.
 Elements of linked list are called “nodes”
 where each node contains two things, data and pointer to next node.

Linked List Representation


Linked list can be visualized as a chain of nodes, where every node points to the next node.

 Linked List contains collections of nodes, which interconnected each other by a link.
 Each link contains two fields
1) Data field
2) Link field
 Data field contains the items.
 Link field contains the link of the next item.
 Last node of the list contain null pointer.

Basic Operations
Following are the basic operations supported by a list.

 Insertion − Adds an element at the beginning of the list.


 Deletion − Deletes an element at the beginning of the list.
 Display − Displays the complete list.
 Search − Searches an element using the given key.
 Delete − Deletes an element using the given key.
Types of Linked List
Following are the various types of linked list.

 Singly Linked List − Item navigation is forward only.


 Doubly Linked List − Items can be navigated forward and backward.
 Circular Linked List − Last item contains link of the first element as next and the first element has a link to
the last element as previous.

Singly Linked List: Representation and Operations


• It is basic type of linked list.
• Each node contains data and pointer to next node.
• Last node’s pointer is null.
• Limitation of singly linked list is we can traverse only in one direction, forward direction.

Fig. 2.9Linked List

Fig. 2.10 Linked Listwith a Header

Routine to Insert an Element in the List


void Insert (int X, List L, Position P)
/* Insert after the position P*/
{

positionNewnode;
Newnode = malloc (size of (Struct
Node)); If (Newnode! = NULL)
{
Newnode Element = X;
Newnode Next =
PNext; P Next =
Newnode;
}
}

INSERT (25, P, L)

Routine To Check Whether The List Is Empty


intIsEmpty (List L) /*Returns 1 if L is empty */
{
if (L Next = =
NULL)

Print(“List
is Empty”);
}

Routine to Delete an Element from the List


void Delete(int X, List L)
{
/* Delete the first occurence of X from the List
*/ position P, Temp;
If (!IsLast(P,L))
{
Temp = PNext;
P Next = TempNext; Free
(Temp);
}
}

Doubly Linked List and Representation


• Each node of doubly linked list contains data and two pointers to point previous and next node.
• Main advantage of doubly linked list is we can traverse in any direction, forward or reverse.
• Other advantage of doubly linked list is we can delete a node with little trouble, since we have pointers to the
previous and next nodes
• doubly linked list is it requires more memory compared to singly linked list because we need an extra pointer to
point previous node.
• L and R in image denotes left most and right most nodes in the list.
• Left link of L node and right link of R node is NULL, indicating the end of list for each direction. N

As per the above illustration, following are the important points to be considered.

Routine to Insert an Element in the List


void Insert (int X, List L, Position P)
/* Insert after the position P*/
{

positionNewnode;
Newnode = malloc (size of (Struct
Node)); If (Newnode! = NULL)
{
Newnode Element = X;
Newnode Next =
PNext; P Next =
Newnode;
}
}

Routine To Check Whether The List Is Empty


intIsEmpty (List L) /*Returns 1 if L is empty */
{
if (L Next = =
NULL)

print(“List is
Empty”);
}

Routine to Delete an Element from the List


void Delete(int X, List L)
{
/* Delete the first occurence of X from the List
*/ position P, Temp;
P = Findprevious
(X,L); If (!IsLast(P,L))
{
Temp = PNext;
P Next = TempNext;
Free (Temp);
}
}

TREES
 A tree data structure is a non-linear data structure because it does not store in a
sequential manner.
 It is a hierarchical structure as elements in a Tree are arranged in multiple levels.
 In the Tree data structure, the topmost node is known as a root node

Terminologies

 Path − Path refers to the sequence of nodes along the edges of a tree.
 Root − The node at the top of the tree is called root. There is only one root per tree and
one path from the root node to any node.
 Parent − Any node except the root node has one edge upward to a node called parent.
 Child − The node below a given node connected by its edge downward is called its child
node.
 Leaf − The node which does not have any child node is called the leaf node.
 Subtree − Subtree represents the descendants of a node.
 Visiting − Visiting refers to checking the value of a node when control is on the node.
 Traversing − Traversing means passing through nodes in a specific order.
 Levels − Level of a node represents the generation of a node. If the root node is at level
0, then its next child node is at level 1, its grandchild is at level 2, and so on.
Tree Node

The code to write a tree node would be similar to what is given below. It has a data part and
references to its left and right child nodes.

struct node
{
int data;
struct node *leftChild;
struct node *rightChild;
};

In a tree, all nodes share common construct.

Basic Operations

The basic operations that can be performed on a binary search tree data structure, are the
following −

 Insert − Inserts an element in a tree/create a tree.


 Search − Searches an element in a tree.
 Traversal − Traverses a tree in a order manner.

Tree Traversal
Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all
nodes are connected via edges (links) we always start from the root (head) node. That is, we
cannot randomly access a node in a tree. There are three ways which we use to traverse a tree −

 In-order Traversal
 Pre-order Traversal
 Post-order Traversal

Generally, we traverse a tree to search or locate a given item or key in the tree or to print all the
values it contains.

In-order Traversal

In this traversal method, the left subtree is visited first, then the root and later the right sub-tree.
We should always remember that every node may represent a subtree itself.

If a binary tree is traversed in-order, the output will produce sorted key values in an ascending
order.
We start from A, and following in-order traversal, we move to its left subtree B. B is also
traversed in-order. The process goes on until all the nodes are visited. The output of inorder
traversal of this tree will be −

D→B→E→A→F→C→G

Pre-order Traversal

In this traversal method, the root node is visited first, then the left subtree and finally the right
subtree.

We start from A, and following pre-order traversal, we first visit A itself and then move to its left
subtree B. B is also traversed pre-order. The process goes on until all the nodes are visited. The
output of pre-order traversal of this tree will be −

A→B→D→E→C→F→G

Post-order Traversal
In this traversal method, the root node is visited last, hence the name. First we traverse the left
subtree, then the right subtree and finally the root node.

We start from A, and following Post-order traversal, we first visit the left subtree B. B is also
traversed post-order. The process goes on until all the nodes are visited. The output of post-order
traversal of this tree will be −

D→E→B→F→G→C→A

Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all nodes are
connected via edges (links) we always start from the root (head) node. That is, we cannot random access
a node in a tree.

Binary Trees
Definition :-
Binary Tree is a tree in which no node can have more than two
children. Maximum number of nodes at level i of a binary tree is 2i+1.

15

18 20

8 5 10

3
Fig. 3.2 Binary Tree
Binary Tree Node Declarations

StructTreeNode
{
int Element;
StructTreeNode
*Left ;
StructTreeNode
*Right;

Types of Binary Trees


The following are the types of binary trees:

• Full binary tree: A Binary Tree is full if every node has 0 or 2 children. In a Full
binary tree, the number of leaf nodes is number of internal nodes +1.

Fig: 3.10 Full binary tree

• Complete binary tree: A Binary Tree is complete Binary Tree if all levels are
completely filled except possibly the last level and the last level has all keys as left as
possible.

Fig: 3.11 Complete binary tree

• Perfect binary tree: A Binary tree is Perfect Binary Tree in which all internal nodes have
two children and all leaves are at same level.

Fig: 3.12 Perfect binary tree


• Balanced binary tree: A balanced binary tree has the height of the tree in O(log n).

Fig: 3.13 Balanced binary tree


• Skewed binary tree: The internal nodes of this tree has atmost only one child node. This
is functionally similar to linked list.

Fig: 3.14 Skewed binary tree

You might also like