PROGRAMMING IN C AND DATA STRUCTURES - Unit1&2
PROGRAMMING IN C AND DATA STRUCTURES - Unit1&2
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;
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.
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();
}
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); ]
)
}
;
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 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;
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.
data_type (array_name)[sizeof_array];
Example :
int arr[10];
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;
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.
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 :
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;
};
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:
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:
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
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
#include
<stdio.h>
struct
student {
char name[50];
int per,rno;
};
void display(int
main() {
struct student s1;
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.
}
Output:
Student Name =
Pavin First Year
Marks = 800;
Second Year
Marks = 750; Sum
= 1550
Average = 775
He is Not Eligible for Scholarship
Average = Sum/2;
}
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
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:
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:
No Function Description
.
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.
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:
COPY STRING
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:
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:
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:
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:
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();
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
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.
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:
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” );
1) File Name
2) Data Structure
3) Purpose
Mode Description
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
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,
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);
}
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);
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);
}
The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.
Syntax:
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
}
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:
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:
Value Meaning
0 Beginning of the file
1 Current position
2 End of the file
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);
}
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:
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.
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 −
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.
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 −
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.
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 −
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 −
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 −
Array Implementation(Enqueue)
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.
positionNewnode;
Newnode = malloc (size of (Struct
Node)); If (Newnode! = NULL)
{
Newnode Element = X;
Newnode Next =
PNext; P Next =
Newnode;
}
}
INSERT (25, P, L)
Print(“List
is Empty”);
}
As per the above illustration, following are the important points to be considered.
positionNewnode;
Newnode = malloc (size of (Struct
Node)); If (Newnode! = NULL)
{
Newnode Element = X;
Newnode Next =
PNext; P Next =
Newnode;
}
}
print(“List is
Empty”);
}
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;
};
Basic Operations
The basic operations that can be performed on a binary search tree data structure, are the
following −
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;
• 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.
• 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.
• 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.