0% found this document useful (0 votes)
21 views64 pages

PROGRAMMING IN C AND DATA STRUCTURES - Unit1&2

The document provides an overview of the C programming language, including its history, importance, structure, data types, variables, and operators. It details the components of a C program, the various data types (primary and derived), and the rules for naming and declaring variables. Additionally, it explains different categories of operators and their functions in C programming.

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)
21 views64 pages

PROGRAMMING IN C AND DATA STRUCTURES - Unit1&2

The document provides an overview of the C programming language, including its history, importance, structure, data types, variables, and operators. It details the components of a C program, the various data types (primary and derived), and the rules for naming and declaring variables. Additionally, it explains different categories of operators and their functions in C programming.

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

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);
}
int sum (int *n)
{
*n = *n + 20;
printf("\n value of 'n' in the called function is = %d", n);
}

Functions with Arrays:

 When an array is an argument to a function, only the address of the first element of the array is
passed, not a copy of the entire array.

 There are three ways to declare a parameter that is to receive an array pointer.

 First it can be declared as an array of the same type and size as that used to call the function,

Example:

#include <stdio.h>
void display(int num[10]); main()
{
int t[10],i; for(i=0;i<10;++i)t[i]=i;
display(t);
return 0;
}
void display(int num[10])
{
int i;
for(i=0;i<10;i++) cout <<num[i]<<' ';
}
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(destination, source) copies the contents of source string to destination string.

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

4) strcmp(first_string, compares the first string with second string. If both strings are same, i
second_string) 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];
char ch2[20];
ch2=”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.
 keys − Key represents a value of a node based on which a search operation is to be
carried out for a node.
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


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

Fig: 3.14 Pathological binary tree

You might also like