24CSE24 - Data Structures Using C
24CSE24 - Data Structures Using C
24CSE24
VISION
MISSION
QUALITY POLICY
To provide educational services of the highest quality both curricular and co-
curricular to enable students integrate skills and serve the industry and society
equally well at global level.
VALUES
• Academic Freedom
• Integrity Inclusiveness
• Innovation
• Professionalism
• Social Responsibility
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING (DATA SCIENCE)
PO5 Modern tool usage: Create, select and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
modelling to complex Computer Science and Data Science engineering activities
with an understanding of the limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice in
Computer Science and Data Science Engineering.
PO8 Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO12 Life-Long Learning: Recognize the need for, and have the preparation
and ability to engage in independent and life-long learning in the broadest context
of technological change.
PO PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO1 PO1 PO1
1 0 1 2
CO1 3 3 3 - - - - - - - - 3
CO2 3 3 3 - - - - - - - - 3
CO3 3 3 3 - - - - - - - - 3
CO4 3 - 2 2 - - - - - - - -
CO5 3 3 1 2 - - - - - - - -
CO6 3 3 2 2 - - - - - - - 3
MODULE-1 Programming Essentials CO1 6 Hours
Structure of a Program, Data Types, Operators and Expressions, Managing Input and Output operations, Decision
Making, Branching and Looping Statements.
2.3 : C TOKENS.
2.4 : VARIABLES
Importance of C:
C is a very important language because of its many useful features. The increasing
popularity of C is due to its many desirable qualities. It is a robust language whose rich set of
built in functions and operators can be used to write any complex program. It allows software
developers to develop software without worrying about the hardware platforms where they will
be implemented. The C compiler combines the capabilities of an assembly language with the
features of a higher level language and therefore it is well suited for both system software and
business packages. Else these,
I. C language is efficient and fast.
II. C is highly portable.
III. C language is well suited for structured programming.
IV. C is a machine independent language.
V. C has the ability to extend itself.
C language is used for developing software packages, system software, database systems,
graphics packages, spread sheets, CAD/CAM applications, word processors, office
automation, scientific and engineering applications.
To write a C program, we first create functions and then put them together. A C program
may contain one or more sections. They are illustrated below.
Documentation section
Link section
Definition section
Global declaration section
main () Function section
{
Declaration part
Executable part
}
Subprogram section
Function 1
Function 2 (User defined functions)
…………..
…………..
Function n
i) Documentation section :
The documentation section consists of a set of comment lines giving the name of
the program, the author and other details, which the programmer would like to use later.
2.3 C TOKENS:
Individual words and punctuation marks in a passage of text are termed as Tokens.
In a C program, the smallest individual units are termed as C tokens.
2.6.1 C KEYWORDS
C keywords are reserved words by the compiler.
All the c keywords have been assigned a fixed meaning.
Keywords cannot be used as variable names because they have been assigned fixed jobs.
For utilizing the keywords in a program, no header files are to be included.
2.6.2 IDENTIFIERS
Identifier is a name given to program elements such as variables, functions, procedure,
arrays and soon. First character must be an Alphabet or Underscore. Identifier consists of
sequence of letters, digits or combination of both.
1. NUMERIC CONSTANTS:
These quantities are represented by numbers containing fractional parts like 26.082. Example
of real constants is
0.0026
-0.97
435.29
+487.0
Real Numbers can also be represented by exponential notation. The general form for
exponential notation is mantissa exponent. The mantissa is either a real number expressed in decimal
notation or an integer. The exponent is an integer number with an optional plus or minus sign.
2. CHARACTER CONSTANTS:
(i) Single Character Constants
A Single Character constant represent a single character which is enclosed in a pair of quotation
symbols. Example for character constants are
'5'
'x'
';'
‘’
All character constants have an equivalent integer value which is called ASCII Values.
Character M Y ” a g e i s
#
ASCII Code 77 121 34 97 103 101 35 105 115
Character % 2 blank ( t w o ) @
A string constant is a set of characters enclosed in double quotation marks. The characters in a
string constant sequence may be a alphabet, number, special character and blank space. Example of
string constants are
"VISHAL"
"1234"
"God Bless"
3. SYMBOLIC CONSTANT
2.7 VARIABLES
A variable is a data name that may be used to store a data value. Unlike constants that
remain unchanged during the execution of a program, a variable may take different
values at different times during execution. It is a memory location used to store a data
value.
Variables can be of different data types. The data types are integers, real or character
constants
A variable name consists of alphabets, digits and underscores character.
Rules for defining variables:
1. The variable name should not start with a digit
2. White space is not allowed
3. The length of a variable must not be more than 8 characters
4. A variable should not be a Keyword
5. The variable names may be a combination of upper and lower characters.
Sun
number
Salary
Emp_name
average1
123
(area)
6th
%abc
A variable is a named location in memory, used to store a value of any data type, that can
be modified by the program.
All variables must be declared before they are used in the program.
Basic data type declaration
Data Type is a term refers to a kind of data used in a program. The data types
supported in a language dictates the type of values.
C consists of three classes of data types
1. Primary data type
2. User defined data type
3. Derived data types
PRIMARY DATA TYPES
All C compilers supports four primary data types namely.
1. Character data type represented as char
2. Integer data type represented as Int
3. Floating point data type reprinted as float
4. Double
5. void
EMPTY DATA TYPE
VOID is the empty data type. This data type is used before main function in a C
Language. The word void refers no return data type. It is used before the main function to
specify the type of function. If a function is of type void it does not return any value to the
calling function.
Example:
typedef int integer;
typedef float floating-point;
typedef char character;
Where
integer symbolizes int.
character symbolizes char.
floating-point symbolizes float.
they can later used to declare variables as
character c1, c2;
integer int1, int2, int3, total;
floating-point r1, r2, rate;
The main advantage of type definition is that, you can create meaningful data type
names for increasing the readability of the program.
TYPE CONVERSION
Implicit Explicit
Automatic Assignment
In the case of implicit type conversion one data type is automatically converted into
another type as per the rules described in the C language,
There are two types of implicit type conversion
1. automatic type conversion and
2. assignment type conversion
Where expression is converted to the target data_type enclosed within the parentheses. The
expression may be a constant or a variable. The data type must be any scalar type or void. If
it is void, the operand must be other the void type expression. The name of the data type to
which the conversion is to be made is enclosed in parentheses and placed directly to the left of
the expression
Sl.
OPERATOR MEANING
No.
1 + Addition or unary plus A+B
2 - Subtraction or unary minus A-B
3 * Multiplication A*B
4 / Division A/B
5 Modulo division or A%B
%
remainder after division
RELATIONAL OPERATORS
These operators are used to distinguish between two values depending on their relations.
These operators provide the relationship between the two expressions. Often it is required to
compare the relationship between operands and bring out a decision and program accordingly.
This is when the relational operator come into picture. C supports the following relational
operators.
Table given below shows the relational operators,
OPERATOR MEANING
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
The general format for relational expression is
Relational expressions are used in decision making statements of C language such as if,
while and for statements to decide the course of action of a running program.
LOGICAL OPERATORS
C has the following logical operators, they compare or evaluate logical and relational
expressions.
OPERATOR MEANING
&& Logical AND
|| Logical OR
! Logical NOT
Example:
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole expression is true
only if both expressions are true i.e., if a is greater than b and x is equal to 10.
Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if
any one of the 2 expressions is true.
Example:
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It
evaluates to true if a is less than either m or n and when a is less than both m and n.
Example: (x >= y) the NOT expression evaluates to true only if the value of x is neither greater
than nor equal to y.
ASSIGNMENT OPERATOR
Assignment is the most commonly used operation to assign either a value or result of an
expression to a variable.
OPERATOR MEANING
= Equal to
+= Addition or equal to
-= Subtraction or equal to
*= Multiplication or equal to
/= Division or Equal to
%= Modulo division or equal to
Increment Operators
It is used to increase the value of the Operand by 1. There are two types of Increment
Operators in C Language. They are pre Increment operator and post Increment operator.
Decrement Operators
It is used to decrease the value of the Operand by 1. There are two types of Decrement
Operators in C Language. They are pre decrement operator and post decrement operator.
Pre decrement Operator
It is used to decrease the value of the variable by 1. Here the value of 1 is subtracted
to the variable first along with the given variable value.
Eg: --g ------> pre decrement
Post Decrement Operator
It is used to decrease the value of the variable by 1. Here the value of 1 is subtracted
to the variable first along with the given variable value.
Eg: g-- ----> post Decrement
S.No Operator type Operator Description
1 Pre increment ++i Value of i is incremented first then incremented is
2 Post-increment i++ Value is assigned to the variable first and then
3 Pre decrement – –i Value of i is decremented first then incremented is
4 Post decrement i– – Value is assigned to the variable first and then
Assigned value get decremented.
CONDITIONAL OPERATORS
An expression that evaluates conditions are called as conditional expressions.
The operator used to evaluate conditional expression is called as a conditional operator
Denoted by (? :).
This operator is represented as ‘&’ and operates on two operands of integer type.
Eg:
x = 7 = 0000 0111
y = 8 = 0000 1000
x&y = 0000 0000
Bitwise OR (|)
Similar to AND operator in all aspects, but this operator gives if either of the operand
bit is ‘1’ then result is ‘1’ or both operands are ‘1’ s then also given ‘1’.
Eg:
x = 7 = 0000 0111
y = 8 = 0000 1000
x|y = 0000 1111
i) COMMA OPERATOR:
The comma operator can be used to link the related expressions together. A comma- linked
list of expressions is evaluated left to right and the value of right-most expression is the value
of the combined expression. For example, the statement
Value = (x = 10, y = 5, x+y)
First assigns value 10 to x, then assigns 5 to y, and finally assigns 15 to value. Since comma
operator has the lowest precedence of all operstors, the parentheses are necessary.
Example:
EVALUATION OF EXPRESSIONS
PRECEDENCE OF OPERATORS
Precedence refers to what comes first. Several operators may appear in one
expression. It is important to know the order in which they are executed. Execution tekes
place according to certain predefined rules, known as hierarchy rules. These rules specify
the order of execution, known as precedence level or priority of operators.
We know that input, process, output are the three essential features of computer
program. The program takes some input data, processes it and gives the output.
We have two methods for providing data to the program
Assigning the data to the variable in a program
By using the Input/output statements
In ‘C’ language, two types of Input/output statements are available, and all input and
output operation are carried out through function calls. Several functions are available for
input/output operations in ‘C’. These functions are collectively known as the standard I/O
library.
1. Unformatted Input/output Statements
2. Formatted Input/output Statements
Unformatted Input/output Statements
These statements are used to Input/output a single/group of characters form/ to the
input/output devices. Here the user cannot specify the type of data that is going to be
input/output.
The following are the unformatted Input/Output statements available in ‘C’
Input Output
getchar() putchar()
getch() putch()
gets() puts()
The getchar() function is written in standard I/O library. It reads a single character
from a standard input device. This function do not require any arguments, through a
pair of empty parentheses, must follow the statements getchar().
The first statement declares x as a character type variable. The second statement causes
a single character to be entered from the standard input device and then assigned to
variable x.
Example Program:
The program displays a question of YES/NO type to the user and reads the user's
response in a single character (Y or N). If the response is Y, it outputs the message
Otherwise, outputs.
Note there is one line space between the input text and output message.
Description Character variable is the valid ‘C’ variable of the type of char data
type
Description Character variable is the valid ‘C’ variable of the type of char data
type
Example gets(s);
Example put(s);
Input Output
scanf() printf()
i) The scanf() function
Input data can be entered into the computer using the standard input ‘C’ library function
called scanf(). This function is used to enter any combination of input.
The scanf() function is used to read information form the standard input
device(keyboard), scanf() function starts with a string arguments and may contain
additional arguments. Any additional argument must be pointer
Example int n;
scanf(“%d”,&n);
2. If there is an number of input data items, items must be separated by commas and
must be preceded with (&) sign except for string input
3. The control string and the variables going to input should match with each other
4. It must have termination with semicolon
5. The scanf() reads the data values until the blank space in numeric input or maximum
number of character have been read or an error is detected
CONTROL STRING:
It is the type of data that the user going to accept via the input statements, this can be
formatted and always preceded with a ‘%’ sign. The below table illustrates code formats
(control strings) in Input/output statements.
Each variable name (argument) must be preceded by an ampersand (&). The (‘&’) symbol
gives the meaning “address of” the variable.
The scanf control string or placeholder consists of % at the beginning and type indicator at
the end. Apart from that it can have *, a maximum field width indicator and a type indicator
modified.
FORMAT TYPE OF
INPUT
SPECIFIER ARGUMENT
%c Character Reads a single character
%d or %i Integer Reads a decimal integer
%e or %E or Floating point Reads a floating point value
%f or %g or
%G
%hd or %hi Short integer Reads decimal short integer
%hu Short integer Reads decimal unsigned short integer
%ld or %li Long integer Reads decimal long integer
%le or %lf or Double Reads signed double
%lg
%Le or %Lf Long double Reads signed long double
or %Lg
%lo Long integer Reads an octal long integer
%lu Long integer Reads decimal unsigned long integer
%lx Long integer Reads hexadecimal long integer
%o Octal integer Reads an unsigned octal integer
%s Sequence of Reads a string
characters
%u Integer Reads an unsigned decimal integer
%x or %X Hexadecimal Reads a unsigned hexadecimal integer
integer
In the following table the required functions and their tests are given.
Function Test
isalnum(c) Is c an alphanumeric character?
isalpha(c) Is c an alphabetic character?
isdigit(c) Is c a digit?
islower(c) Is c a lower case letter?
isprint(c) Is c a printable character?
ispunct(c) Is c a punctuation mark?
isspace(c) Is c a white space character?
isupper(c) Is c an upper case later?
Sl.
puts() printf()
no.
It can display only one It can display any number of characters, integers or
1.
String at a time. Strings at a time.
All data types are Each data type is considered separately, depending upon
2.
Considered as characters. The conversion specifications.
ASCII Escape
Sl. no Meaning
Value Sequences
1. 000 \0 Null
2. 007 \a Audible alter (bell)
3. 008 \b Backspace
4. 009 \t Horizontal tab
5. 010 \n New line
6. 011 \v Vertical tab
7. 012 \f Form feed
8. 013 \r Carriage return
9. 034 \” Double quote
10. 039 \’ Single quote
11. 063 \? Question mark
12. 092 \\ Backslash
CONTROL STATEMENTS
Ex: i=i+1;
c=a+b;
ii) Selection structure: here the sequence of the instructions are determined by using
the result of the condition
Ex: if(x>y)
i=i+1;
else
j=j+1;
iii) Iteration Structure: in which statements are repeatedly executed. These forms
program loops.
Ex: for(i=1;i<=5;i++)
{
i=i+1;
}
iv) Encapsulation structure : in which the other compound structures are included
Ex: we can include an if statement in a for loop or a for loop in a if statement.
In practice, users may have a number of situations where they may have to change the
order of statements based on certain conditions. This is decision making. C language
possesses such decision making capabilities by supporting the following statements :
Decision making with if Statement
It is used to control the flow of execution of the statements and also used to test
logically whether the condition is true or false.
SYNTAX FLOWCHART
if (test expression)
{
Statement-block;
}
Statement-x;
If statement executes if the given condition is true otherwise it does not produces any
output.
Output:
This is basically two way decision making statement and always used in Conjunction
with condition.
It is used to control the flow of execution and also used to carry out the logical test and
then pick up one of the two possible actions depending on the logical test.
SYNTAX FLOWCHART
if (test expression)
{
True-block
statements;
}
else
{
False-block
statements;
}
Statement-x
In these statement both if part and else part will not be executed at the same time.
Either anyone of the both will be executed during run time.
Output:
SYNTAX FLOWCHART
Output:
Enter three values
23445 67379 88843
SYNTAX FLOWCHART
SELECTION STATEMENT
SWITCH STATEMENT:
switch(expression)
{
case value-1:
block1;
break;
case value-2:
block-2;
break;
……………………………………
……………………………………
default:
default-block
break;
}
Ststement-x;
Example: C program to count the number of vowels and digits in a given string
using switch case statement.
(The following program illustrates the use of switch statement.)
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
char ch;
int digits, vowels=0;
clrscr();
printf("Enter a string with digits\n");
while((ch=getchar())!='\n')
{
switch(ch)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
digits++;
break;
case 'a':case 'A':
case 'e':case 'E':
case 'i':case 'I':
case 'o':case 'O':
case 'u':case 'U':
vowels++;
break;
}
}
printf("\n No. of vowels in the given string %d",vowels);
printf("\n No. of digits in the given string %d",digits);
getch();
}
Output:
Enter a string with digits
engineering 123456
No. of vowels in the given string 5
No. of digits in the given string 6
What is a loop ?
In some situations there is a need to repeat a set of instructions in specified number
of times or until a particular condition is being satisfied. These repetitive operations
are done through a loop control structure.
The loop is defined as the block of statements which are repeatedly executed for
certain number of times.
The loop in a program consists two parts,
one is body of the loop and
another one is control statement.
The control statement is used to test the condition and then directs the repeated
execution of the statements in the body of the loop.
Any looping statement would include the following steps:
i) Initialization of a condition variable
ii) Test the control statements
iii) Executing the body of the loop depending on the condition
iv) Updating the condition variable
while loop
do-while loop
for loop.
Next statement
While statement executes only if the given condition is true.
If it is not true the next statement will be executed.
If there is only one while statement then there is do need for having curly braces.
The execution of while statement comes to end when the condition becomes false.
Therefore while loop must be finite.
While loop is also called entry-controlled loop. Entry-controlled loop also
known as pre-test
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,sum=0 ; /* Local definitions */
/* Statements */
Output :
The sum of number upto 10 is 55
do…while Loop
In do while loop, statement is executed first then the condition is checked. If the
given condition is not true at-least one statement will be definitely executed.
If the condition is true then the while loop will be executed and corresponding
statements will be displayed as output.
In do-while loop condition is terminated (or) ends with semicolon. Even if the given
condition is true or false do-while loop executes atleast once in the program.
/* Statements */
do
{
sum =sum+i;
i++;
} while (i<=10);
printf ("The sum of number upto 10 is %d",sum);
getch();
} /* main */
Output :
The sum of number upto 10 is 55
The for loop is another repetitive control structure, and is used to execute set of
instructions repeatedly until the condition becomes false.
General form: for (initialization; test condition; increment/decrement)
{
program statement;
}
Explanation: 1. Initialization: is used to initialize counter variable
Here initialization is done in the beginning of the for loop. It is done using the
assignment operator ‘=’.
Test condition is the place where the given condition is being checked. Condition is
checked every time using the initialization value.
Based on the condition initialized value will be incremented/decremented.
If the initialization value and test condition value does not match the loop gets
terminated and statements will not be executed.
for loop executes until the test condition is true. When it becomes false the loop
terminates. Both increment and decrement is possible in a for loop.
Loops containing more than one loops within itself is known as nested loop.
Here outermost loop will start to execute first but the process of outermost loop
ends only when the condition of innermost loop ends. E
ach loop must have a unique index variable. Each index variable must not coincide
with each other. Loops should not overlap with each other.
Each loop should be embedded with each other. Loops can have any number of exit
point but should not permit entry into it. Loops should not overlap each other.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j ; /* Local definitions */
/* Statements */
for(i=1;i<=3;i++)
{
printf(“\n”);
for(j=1;j<=3;j++)
printf(“%d\t”,j);
} /* main */
Output :
123
123
123
Comparison between …
1 This is the top tested loop This is the bottom tested loop
2 The condition is first tested if the condition It executes the body once, after it checks
is true then the block is executed until the the condition, if it is true the body is
condition becomes false executed until the condition becomes
false
3 Loop will not be executed if the condition Loop is executed atlases once even
is false through the condition is false
The differences between the entry and exit controlled loops are as follows.
The differences between the counter and sentinel controlled loops are as follows.
The number of times a loop is repeated is decided in advance and the test condition is
written to achieve this. Sometimes, When executing a loop it becomes desirable to skip a part
of the loop or to leave the loop as soon as a certain condition is occurs.
Break STATEMENT
Break statement is used to terminate the control from one place to another in a
program.
When a break statement is encountered then the loop gets terminated or come to an
end.
Break statement exits only single loop. Hence it is used together with the statements
wherever necessary.
It is also used to exit from a loop.
A break causes the innermost enclosing loop or switch to be exited immediately. It is
also used together with while, dowhile, for and switch statement.
Syntax:
break;
Example: The following program illustrates the break statement.
#include<stdio.h>
#include<conio.h>
void main ()
{
/* Local definitions */
int i;
/* Statements */
for(i=1;i<=10;i++)
{
if(i==6)
break; /* break statement */
printf("%d", i);
} /* for */
} /* main */
Output :
12345
Continue STATEMENT
Syntax:
continue;
Output :
2.1: ARRAYS
1. SINGLE DIMENSIONAL ARRAY
2. TWO DIMENSIONAL ARRAY
3. MULTI DIMENSIONAL ARRAY
2.2: FUNCTION
1. TYPES OF FUNCTIONS (PROTOTYPES)
2. PARAMETER PASSING METHODS
3. PASSING ARRAYS TO FUNCTIONS
2.3: RECURSION
: STORAGE CLASSES
Data Structures using C: Module-2
2.1 ARRAYS
Array is a derived data type. When it is necessary to store more than one value under a
variable, user can make use of array. An array is a fixed-size sequence collection of elements
of the same data type. It is simply a grouping of like-data type.
Many applications require the processing of multiple data items that have common
characteristics. In such a situation it is convenient to place such data item in an
Array
A value in an array is identified by index or subscript enclosed in square brackets
with array name.
The individual data items can be integers, floating point numbers, and characters and
so on, but they must be the same type and same storage class.
Each array element is referred by specifying the array name with subscripts each
subscripts enclosed in square brackets and each subscript must be a non-negative
integer.
Thus ‘n’ elements array ‘A’ and the elements are
A[0],A[1],A[2]…..A[N-1]
The value of each subscript can be expressed as an integer constant or an integer
variable or an integer expression. The arrays can be used to represent not only simple
list of value but also task of data items in two and three or more dimensions.
The values can be initialized to an array, when they are declared like ordinary variable,
otherwise they hold garbage values.
i) At compile time
ii) At run time
Static arrays:
The process of allocating memory at compile time is known as static memory
allocation and the arrays that receives static memory allocation are called static arrays. This
approach works fine as long as user know that what the data requirements are.
Data Structures using C: Module-2
Dynamic arrays:
The process of allocating memory at run time is known as dynamic memory
allocation and the arrays that receive such kind of memory allocation are known as dynamic
arrays. Dynamic arrays are created using what are known as pointer variables and memory
management functions malloc, calloc and realloc.
At Compile Time
User can initialize the elements of an array in the same way as the ordinary variables
when they are declared. This is compile time initialization.
At Run time
An array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays.
sum[i]=0.0;
else
sum[i]=1.0;
Data Structures using C: Module-2
2. TWO-DIMENSIONAL ARRAY
Two dimensional arrays are used in situation where a table of values need to be stored
in an array These can be defined in the same fashion as in one dimensional arrays,
except a separate pair of square brackets are required for each subscript
Two pairs of square brackets required for to dimensional array and three pairs
required for three dimensional arrays and so on.
Two dimensional arrays are stored in a row-column matrix, where the left index
indicates the row the right indicates the column.
Where 'a' is the array name and it reserves 3 row and 3 columns of memory as
shown below
row = i+1
column = j+1
Data Structures using C: Module-2
#defineROW 3
#defineCOL 3
int main()
{
int i,j,k; // to use as index variables to access the array.
int a[ROW][COL],b[ROW][COL], c[ROW][COL]; //arrays for matrix 3x3
printf("\nEnter values for two 3x3 Matrices\n");
printf("\n Enter the Matrix A");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\n Enter the Matrix B");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("Matrix Multiplication\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
c[i][j]=0;
for(k=0;k<COL;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
printf("\t%d",c[i][j]);
}
Data Structures using C: Module-2
printf("\n");
}
return 0;
}
Output :
Enter values for two 3X3 Matrices
Enter the Matrix A
1 9 6
3 5 7
5 9 3
Enter the matrix B
1 8 5
6 4 9
3 6 2
Matrix Multiplication
73 80 98
54 86 74
68 94 112
#defineROW 3
#defineCOL 3
int main()
{
int i,j,k; // to use as index variables to access the array.
int a[ROW][COL],b[ROW][COL],addition, c[ROW][COL]; //arrays for matrix 3x3
printf("\nEnter values for two 3x3 Matrices\n");
printf("\n Enter the Matrix A");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\n Enter the Matrix B");
Data Structures using C: Module-2
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("Matrix Addition\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
c[i][j]=0;
{
c[i][j]=a[i][j]+b[i][j];
}
}
}
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
printf("\t%d",c[i][j]);
}
printf("\n");
}
return 0;
}
Output :
Enter values for two 3X3 Matrices
Enter the Matrix A
7 6 2
9 5 3
6 4 1
Enter the Matrix B
8 6 2
4 3 7
8 6 1
Matrix Addition
15 12 4
13 8 10
14 10 2
A Two-Dimensional Array can be also initialized. For that the array values are
specified within a Cmpound statement. (i.e.,) { and }.
Data Structures using C: Module-2
General form:
Storage-class data-type array-name[r][c] = { value1, value2, ........... , value n};
3. MULTI-DIMENSIONAL ARRAY
Multi-dimensional Array consists of (or) requires more than two square brackets
and it may contain any number of values specified within square brackets. It may be three,
four, five, six and so on.
A Multi dimensional Array in general takes the following form.
Here storage class may be static or extern by default. Here Storage-class is optional.
Data-type refers to a valid C data type. Array-name refers to a valid array name.
s1,s2,s3, ……… are sub scripts.
SORTING AN ARRAY
Sorting is the process of Arranging the set of data items in an order. Sorting may be
carried out in Ascending or Descending order. Sorting helps to increase the efficiency of a
program.
Data Structures using C: Module-2
Features of Arrays :
An array is a derived data type. It is used to represent a collection of elements of the
same data type
Data Structures using C: Module-2
The elements can be accessed with base address (index) and the subscripts define the
position of the element
In array the elements are stored in continuous memory location. The starting memory
location is represented by the array name and it is known as the base address of the
array
It is easier to refer the array elements by simply incrementing the value of the
subscript
3.1 FUNCTION
FUNCTION DEFINITION
C language supports wide range of built in functions, which are useful for performing
specified tasks.
However C languages allow us to define our own function to carryout different individual
tasks. This topic elaborates such user defined functions.
A function is a set of instructions that are used to perform specified tasks which
repeatedly occurs in the main program.
Function is used to provide modularity to the software. By using function we can divide
complex tasks into manageable tasks.
The function can also helps to avoid duplication of work.
The function definition is an independent program module that is specially written to
implement to the requirements of the function. A function definition, also known as
function implementation shall include the following elements
1. Function name
2. Function type
3. List of parameters
4. Local variable declarations
5. Function statements
6. A return statement
All the six elements are grouped into two parts; namely,
Function header (First three elements)
Function body (Second three elements)
Function Header
Data Structures using C: Module-2
The function header consists of three parts; function type, function name and list of
parameter.
(a) Function Type
The function type specifies the type of value (like float or double) that the function is
expected to return to the calling program. If the return type is not explicitly specified, C will
assume that it is an integer type.
(b) Function name
The function name is any valid C identifier and therefore must follow the same rules of
formation as other variable names in C. The name should be appropriate to the task
performed by the function.
(c) List of Parameter
The parameter list declares the variables that will receive the data sent by the calling
program. They serve as input data to the function to carry out the specified task.
Example :
Float mul (float x, float y) {….}
t sum (int a, int b) {….}
Function body
The function body is enclosed in braces, contains three parts, in the order given below:
1. Local variable declaration : Local variable declarations are statements that specify the
variables needed by the function.
2. Function Statements : Function statements are statements that perform the task of the
function.
3. Return Statements : A return statement is a statement that returns the value evaluated by
the function to the calling program. If a function does not return any value, one can omit the
return statement.
Functions are classified into two types as shown below
Functions
The difference between these two categories of functions is that pre-defined or library
functions are not requires to be written by the programmer, whereas the user defined function
has to be written by the programmer at the time of programming.
The functions defined by the user according to their requirements are called user-
defined functions. The user can modify the function according to their requirements.
The user has full scope to implement their own ideas in the function. Thus the set of
such user-defined functions can be useful to another programmer.
These are written by the programmer to perform a particular task, that is
repeatedly used in main program. These functions are helpful to break down a
large program in to a number of smaller functions.
PARAMETERS
Parameters provide the data communications between the calling function and called
function.
There are two types of parameters,
i) Actual parameters – These are the parameters transferred from the calling
program (main program) to the called program (function)
Data Structures using C: Module-2
ii) Formal parameters- These are the parameters, transferred into the calling
function (main program) from the called program (function)
Ex: main()
{
……
……..
fun1(a,b);
…………
…………..
}
fun1(x,y)
{
……….
………
}
Where a,b are the Actual parameters
x,y are the Formal parameter
Local variables
Global variables
Local variables – The local variables are defined within the body of the function or the
blocking. These variables are defined is local to that function or block only function can not
access these variables.
Example:
value (int a, int b)
{
int c,d; local variables
}
Here c and d are the local variables which are defined in the body or the function,
they are local to that particular function only.
Global Variable: Global variable are defined outside the main() function multiple functions
can use these variables
Example :
int m=5,n=10; Global variables
Data Structures using C: Module-2
main()
{
int amb;
}
Here the variables ‘m’ and ‘n’ are defined outside the main() function. Hence they are
global variables.
They can use any other function. The same variables are used throughout the
program.
The various modules can share information by using global variable
The return statement may or may not send back any values to the main program
(calling program). If it does, it can be done using the return statements.
A function can contain more than one return statements, when the return value
can return values based on certain condition.
If a function can return some values other than int type, then we must specify the data
type to be return.
Points using return statements
1. the return statement can return only one value form the called function to the
calling function
2. The return statement can be present anywhere in the function
3. The return statement not necessary at the end of the function
4. If the called function does not return any value, then the keyword void must be used
as the return type specifier
5. Number of return statements used in a function are not restricted
6. Parenthesis used around the expression in a return statement is optional
Advantages:
It reduces the length of source program.
Breaks the complexity of a program.
Data Structures using C: Module-2
FUNCTION DECLARATION :
The program or a function that called a function is referred to as the calling function
or calling program. The calling program should declare any function that is to be used later in
the program. This is known as the function declaration.
A function declaration consists of four parts. They are,
1. Function type
2. Function name
3. Parameter list
4. Terminating semicolon
They are coded in the following format :
Funtion_type function_name(parameter list);
Points to note :
1. The parameter list must be separated by commas.
2. If the function has no formal parameters, the list is written as void.
3. The return type is optional when the function returns int type data.
4. When the declared type does not match the types in the function definition compiler
will produce an error.
TYPES OF FUNCTIONS
In general, a function based on whether the Argument is present, whether the value is
returned or not is classified into 4 types. They are
Functions with no Arguments and no return values.
Functions with Arguments and no return values.
Functions with no Arguments but with return values.
Functions with Arguments and with return values.
Functions with multiple return values
Data Structures using C: Module-2
When a function has no Argument it does not receive any data from the calling
function.
When a function does not return value, calling function does not receive data from
the called function.
There is no data transfer between calling function and called function. A function
that does not return any value cannot be used in an expression.
The dotted lines indicates that, there is only transfer of control but no data
transfer
When a function has Argument it receives data from the calling function and the
value is used inside the sub-function.
Whenever a function call is made, a copy of the values in Actual argument is sent to
the Formal argument by using the called function.
A calling function sends value to arguments by means of function call.
Data Structures using C: Module-2
The Actual arguments and Formal arguments must be the same in number, order and
type.
The values used in actual arguments must be assigned values before the function call
is made.
The continuous line indicate data transfer and dotted line indicates transfer of control.
Here, the continuous line indicates that, the data transfer takes place in between
calling program and called program
The actual arguments x and y are inputs, s and d are output arguments. In the function call,
while we pass the actual values of x and y to the function, we pass the addresses of locations
where the values of s and d are stored in the memory.
value of x to a
value of y to b
address of s to sum
address of d to diff
3. RECURSION
Recursion is the process of calling the same function itself again and again until
some condition is satisfied.
This process is used for repetitive computation in which each action is satisfied in
terms of a previous result.
In order to write a recursive program, the user must satisfy the following
Syntax:
function1()
{
function1();
}
There are certain problems, that can be defined in terms of smaller problems of
similar types. Such problems as said to be recursive.
Void functions:
The functions that do not return any values can be explicitly defined as void. This
prevents any accidental use of these functions in expressions.
Example:
#include<stdio.h>
void main()
Data Structures using C: Module-2
{
void starline();
void message();
}
void printline
{
statements;
}
void value
{
statements;
}
1. Call by value :
The process of passing the actual value of variables is known as “call by value”.
When a function is called in program, the values to the arguments in the function are
taken by the calling program; the value taken can be used inside the function.
Alteration to the value is not accepted inside the function in calling program but
change is locally available in the function.
2. Call by reference :
The process of calling a function using pointers to pass the addresses of variables is
known as “call by reference”.
A function can be declared with pointer as its arguments. Such functions are called
by calling program with the address of a variable as argument form it.
The address of the variables is altered to the pointers and any change made to the
value inside the function is automatically carried out in the location. This change is
accepted by the calling program.
The usual method to call a function in The address of the variable is passed
2 which only the value of the variable is as an arguments
passed as an arguments
When a new location is created it is very The existing memory location is
3 slow used through its address, it very fast
There is no possibility of wrong data There is a possibility of wrong data
manipulation since the argument are manipulation since the addresses are
4 directly used in an expression used in a an expression. A good
skill of programming is required
here
One-dimensional arrays:
An entire array can be transferred to a function as parameter. To transfer an array
to a function, the array name is enough without subscripts as actual parameters within the
function call.
The corresponding formal parameters are written in same fashion, and must be
declared as an array in formal parameters declaration.
3. The function must be called by passing only the name of the array.
4. In the function definition, the formal parameter must be an array type; the size of the
array does not need to be specified.
5. The function prototype must show that the argument is an array.
Data Structures using C: Module-2
main()
{
int M=3, N=2;
double average(int[][N], int, int);
double main;
int matrix[M][N]= { {1,2}, {3,4}, {5,6}};
mean=average(matrix, M, N);
……………
……………
}
STORAGE CLASSES
Variables in C programs are totally different from other languages. We can use the
same variable names in the C program in separate blocks.
When we declare a variable it is available only to specific part or block of the
program. Remaining block or other function cannot get access to the variable.
The area or block of the C program from where the variable can be accessed is
known as the scope of the variable.
Data Structures using C: Module-2
Scope of a variable is also defined as the region over which variable is visible or
valid.
The area or scope of the variable depends on its storage class, that is, where and how
it is declared.
The storage class of a variable tells the compiler
Storage area of the variable
Initial value of the variable if not initialized
Scope of the variable
Life of the variable that is how long the variable would be active in the program.
There are four types of storage classes available in a C language. They are
1. Automatic Variables
2. Static Variables
3. External Variables (Global Variables)
4. Register Variables
The following table gives the detail information about various storage classes.
Note:
For faster access of a variable, it is better to go for register specifiers rather than auto
specifiers.
Because, register variables are stored in register memory whereas auto variables are
stored in main CPU memory.
Only few variables can be stored in register memory. So, we can use variables as
register that are used very often in a C program.
Data Structures using C: Module-2
1. Automatic Variables
Variables declared inside a block and local to block in which declared are said to be
Automatic variables. These variables can be accessed by block in which they are
declared. Another block cannot access its value.
These variables created as new variable each time when function is called and destroyed
automatically when the function is exited.
Compiler treat variable declared inside block as automatic variable by default. Automatic
variables are stored in memory. All variables declared inside the function is auto by
default.
Auto variables are safe that is, they cannot be accessed directly by other functions.
Example
main()
{
int number;
- --------- ;
- --------- ;
}
We may also use the keyword auto to declare automatic variables explicitly.
main()
{
auto int number;
;
;
}
One important feature of automatic variables is that their value cannot be changed
accidentally by what happens in some other function in the program. This assures that
we may declare and use the same variable name in different functions in the same
program without causing any confusion to the compiler.
void function2(void)
{
int m = 100;
function1();
printf("%d\n",m); /* Second output */
}
OUTPUT:
10
100
1000
2. Static Variables
Static variable may be either an internal type or an external type depending on the
place of declaration.
Static variables declared within individual block. They are local to the block in which
declared. It exists until the end of the program.
Variable can be declared using the keyword static. Global and Local variable can be
declared static.
Static variables are initialized only once when they are compiled in a program.
When the program is closed the function associated with that program is also exited and
whenever it is visited again the same value exists.
Internal static variable is declared inside a function.
External static variable is declared outside a function. It is made available to all
functions in a C program.
{
static int x = 0;
x = x+1;
printf("x = %d\n", x);
}
OUTPUT:
x=1
x=2
x=3
}
The variables number and length are available for use in all the three functions.
Once a variable has been declared as global, any function can use it and change its value.
Then subsequent functions can reference only that new value.
One other aspect of a global variable is that is available only from the point of declaration
to the end of the program. Consider the program segment shown below
main()
{
y=5;
;
;
Data Structures using C: Module-2
}
int y; /*Global Declaration*/
func1()
{
y=y+1;
}
We have a problem here. As far as main is concerned, y is not defined. So the
compiler will issue an error message.
External Declaration
In the above program, the main cannot access the variable y as it has been declared after
the main function. This problem can be solved by declaring the variable with the storage
class named as “extern”
main()
{
extern int y; /*External declaration*/
;
;
}
func1() /*External declaration*/
{
extern int y;
}
int y; /*Definition*/
4. Register Variables
Register is a special storage area in a Central Processing Unit (CPU).
There are 8 registers available inside a Computer. Register variable can be accessed
only by block in which it is declared. It cannot be accessed by any other function.
Register variable declared using keyword register.
Both Local variable and formal parameter can be declared as a register.
Register is used to increase the execution speed.
Only integer or char variables are declared as register in most of the compilers but ANSI
C supports all the data types.
void main()
{
register int x;
clrscr();
for(x=1;x<=10;x++)
printf(“%d”,x);
getch();
}
MODULE -3
Structures, Unions
and Pointers
Data Structures using C: Module-3
3.1: STRUCTURE
3.2: ARRAY OF STRUCTURE
3.3: ARRAYS WITHIN STRUCTURE
3.4: STRUCTURE WITHIN STRUCTURE (NESTING OF STRUCTURE)
3.5: USER –DEFINED DATA TYPES
3.6: UNION
3.7: POINTERS
Data Structures using C: Module-3
3.1: STRUCTURE
Syntax :-
struct structure_name
{
data-type member1;
data-type member2;
………………………………
………………………………
data-type membern;
}
struct structure_name v1, v2,……vn;
Thus, a single structure may contain integer elements, floating point elements and
character elements, pointers, arrays and other structures can also be included as
elements within a structure.
Structures help to organize data, particularly in large programs, because they allow a group
of related variables to be treated as a single unit.
A structure is a convenient tool for handling a group of logically related data items.
For example, it can be used to represent a set of attributes, such as student_name,
roll_number, and marks. The concept of a structure is analogous to that of a ‘record’ in
may other languages.
Structure is a type of data structure in which each individual element differs in type. The
elements of a structure are called ‘members’.
The structure elements contain integer, floating point numbers, character arrays, pointers
as their members. Structure act as a tool for handling logically related data items.
Fields of structure are called structure elements or members. Each member may be of
different type.
Uses / Applications
Database Management
Positioning Cursors
Receiving ascii and scan codes
Displaying characters
Printing on printer
Data Structures using C: Module-3
Mouse Programming
Graphics Programming
All Disk Operations
etc.
Declaring a Structure:
Structure is declared using the keyword ‘struct’ followed by a ‘tag’ and is enclosed by
curly open ‘{’ and close ‘}’ braces.
All members of a structure are specified within curly braces { }.
Structure variable is declared using keyword ‘struct’ followed by structure name and
structure elements name.
All structure elements name are separated by commas. Structure variable declaration is
terminated with semicolon (;).
The syntax is
struct tag variable1, variable2, ......... variable m;
Defining a structure
Defining a structure means creating a variable to access members of structure.
Creating structure variable allows sufficient memory space to hold all the members of
structure.
Syntax :
struct tag
{
data-type member1;
data-type member2;
………………………………
………………………………
data-type membern;
}structure variable(s);
Syntax structure_variable.member_name
Example struct employee
Data Structures using C: Module-3
{
char empname[20];
int empno; member_name
float sal;
}
struct employee emp1;
structure_variable
Accessing: emp1.empname
emp1.empno
emp1.sal member_name
structure_variable
example:
printf(“Enter employee name: ”);
scanf(“%s”, emp1.empname);
C language does not permit the initialization of individual structure member within the
template. The initialization must be done only in the declaration of the actual variables. Note
that the compile-time initialization of a structure variable must have the following elements:
1. The keyword struct
2. The structure tag name
3. The name of the variable to be declared
4. The assignment operator =.
5. A set of values for the members of the structure variable, separated by commas and
enclosed in braces.
6. A termination with semicolon
INITIALIZING STRUCTURE
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int rollno; char
name[20]; int
m1,m2,m3;
Data Structures using C: Module-3
float percent;
}s;
clrscr();
printf("\n enter the roll no.: ");
scanf("%d",&s.rollno);
printf("\n enter the name: ");
scanf("%s", &s.name);
printf("\n enter the mark 1 =");
scanf("%d",&s.m1);
printf("\n enter the mark 2 =");
scanf("%d",&s.m2);
printf("\n enter the mark 3 =");
scanf("%d",&s.m3);
s.percent=(s.m1+s.m2+s.m3)/3;
printf("\n rollno=%d",s.rollno);
printf("\n name=%s",s.name);
printf("\n mark1=%d",s.m1);
printf("\n mark2=%d",s.m2);
printf("\n mark3=%d",s.m3);
printf("\n percent=%.2f",s.percent);
getch();
}
STRUCTURE OPERATIONS
The period operator ‘.’ Has high precedence over unary operator, arithmetic operator,
relational operator, logical operator and assignment operator.
Expression Meaning
++(variable.member) preincrement
(variable.member)++ post increment
&variable Beginning address of the variable.
&variable.member Access address of variable.member
variable.member.submember refers member of structure within a structure.
Variable.member[expression] Refer individual element of array in a
structure.
Array is a collection of similar data types. In the same way, we also define array of
structures.
Data Structures using C: Module-3
Group of structure variable assigned with same type stored in an array. Arrays within
structures used to store array of values within a structure.
Syntax Example
struct structure_name struct marks
{ {
data_type member1; int sub1;
data_type member2; int sub2;
……………………… int sub3;
……………………… int total;
data_type member; };
}structure_variable[size]; main()
{
struct marks student[3] = { {45,68,81{, {75,53,69}, {57,36,71}};
The above example declares the student as an array of three elements student[0],
student[1], and student[2] and initializes their members as follows
student[0].subject1 = 45;
student[0].subject2 = 65;
…….
…….
student[2].subject3 = 71;
An array of structures is stored inside the memory in the same way as a multi-
dimensional array.
The array student actually looks as shown in figure given below:
student[0].subject1 45
student[0].subject2 68
student[0].subject3 81
student[1].subject1 75
student[1].subject2 53
student[1].subject3 69
student[2].subject1 57
student[2].subject2 36
student[2].subject3 71
Data Structures using C: Module-3
int i,n;
printf(“Enter the number of students”);
scanf(“%d”,&n);
would refer to the marks obtained in the third subject by the second student.
struct marks
{
int sub[3];
int total;
};
Void main()
{
printf("\nSUBJECT TOTAL\n\n");
for(j = 0; j <= 2; j++)
printf("Subject-%d %d\n", j+1, total.sub[j]);
}
Output:
STUDENT TOTAL
Student[1] 193
Student[2] 197
Student[3] 164
SUBJECT TOTAL
Subject-1 177
Subject-2 156
Subject-3 221
Nesting of structures are nothing but structure within another structure (i.e., a
structure can contain one or more structures as its members).
A structure may be defined and/or declared inside another structure.
Syntax Example
Description:
In above example, the structure stud_Res consists of stud_subj which itself is a structure
with two members.
Structure stud_Res is called as 'outer structure' while stud_subj is called as 'inner
structure.'
The members which are inside the inner structure can be accessed as follow :
result.subj.subjnm
result.subj.marks
Block diagram Example
struct stud_of_birth
{
int day;
int month;
int year;
};
struct person
{
char name[25];
struct stud_of_birth;
};
struct person p1;
Data Structures using C: Module-3
Description:
In above example, the structure date_of_birth has three members day, month and year.
There is another structure person, with two members name and dob of data type struct
date_of_birth.
The struct variable p1 is declared for the structure person.
The members which are inside the inner structure can be accessed as follow :
p1.dob.day
p1.dob.month
p1.dob.year
The dot operator is used twice in the above statements, as we are accessing variables of
structure which are inside another structure.
EXAMPLE PROGRAM FOR NESTED STRUCTURES:
Example: C Program to create student details using Nested and array of structures
#include<stdio.h>
#include<conio.h>
void main()
{
struct stud
{
int rollno;
char sname[30];
struct dob
{
int date,mon,year;
}d;
int m1,m2,m3, tot;
float avg;
}s[10];
int n, i;
printf(“Enter the number of students”);
scanf(%d”,&n);
for(i=1;i<=n;i++)
{
printf("\%d\t%s\t%d-%d-
%d\t%d\t%f\n",s[i].rollno,s[i].sname,s[i].d.date,s[i].d.mon,s[i].d.year,s[i].tot,s[i].avg);
}
getch();
}
TYPEDEF
Example: C Program to create user defined data type weeks on int data type and
used it in the program.
Output:
#include<stdio.h> #define D 7 Enter weeks: 4 Number of days = 28
UNION
Advantage:
Example #include<stdio.h>
void main()
{
printf(“The size of union is %d\n”,sizeof(u1));
printf(“The size of structure is %d\n”,sizeof(s1));
}
union exam
{
int rollno;
char name[15];
int m1,m2,m3;
}u1;
Struct exam1
{
int rollno;
char name[15];
int m1,m2,m3;
}
Structure Union
Every member has its own memory All the members use the same
space. memory space to store the values
Keyword struct is used Keyword union is used
Any member can be accessed at Different interpretations for the same
any time without the loss of data memory location is possible
It can handle all the members or a It can handle only one member at
few as required at a time time, even all the members use the
Data Structures using C: Module-3
same space
It may be initialized with all its Only one of its members may be
members initialized
More memory space is used Conservation of memory is possible
POINTERS
Generally computer uses memory for storing instruction and values of the variables with
in the program, but the pointers has memory address as their values.
The memory address is the location where program instructions and data are stored,
pointers can be used to access and manipulate data stored in the memory
The computer’s memory is a sequential collection of storage cells as shown below:
Data Structures using C: Module-3
In computer’s memory each cell is 1 byte, and it has a number called address, this address
is numbered consecutively starting form zero to last address (depends upon the memory
size, in 64 memory having the last address as 65,535).
While declaring variable, the computer allocates appropriate memory to hold the value of
the variable. Since every memory has a unique address, this address location will have its
own address number somewhere in the memory area.
Example :
int sno=39;
The above statement instructs the system to specify a location for the integer variable ‘sno’
and put the value 39 in the location. Assume that the system has chosen the address
location 3911 for ‘sno’ this may be represented as during the execution of the program,
the system always associates the variable ‘sno’ with the address 3977. We may have access
to the value 39 by using either the name of the variable ‘sno’ or the address 3977.
Features of Pointers
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10];
int i,sum=0;
int *ptr;
printf("Enter 10 elements:\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
ptr = a; /* a=&a[0] */
for(i=0;i<10;i++)
{
sum = sum + *ptr; //*p=content pointed by 'ptr'
ptr++;
}
printf("The sum of array elements is %d",sum);
}
Output:
Enter 10 elements:
8
6
5
3
45
62
51
9
2
4
The sum of array elements is: 195
POINTER OPERATOR
To manipulate with data items directly from Memory Location two operators are used.
They are
( i ) Address Operator (&) and
( ii ) Indirection Operator ( * ).
Address Operator acts upon variables, array elements and not on Arithmetic Operators.
Indirection Operator is also called as “value at address” operator. It operates only on
operands called pointer variables.
Pointer Variable:
Variables that hold memory address are called pointer variables.
Pointer variable contains address which is the location of another variable in the
memory.
main()
{
char a;
int x;
float p, q;
a = 'A';
x = 125;
Data Structures using C: Module-3
p = 10.25, q = 18.76;
printf("%c is stored at addr %u.\n", a, &a);
printf("%d is stored at addr %u.\n", x, &x);
printf("%f is stored at addr %u.\n", p, &p);
printf("%f is stored at addr %u.\n", q, &q);
}
Output:
A is stored at addr 4436.
125 is stored at addr 4434.
10.250000 is stored at addr 4442.
18.760000 is stored at addr 4438.
Note :-
A pointer variable can be also specified in different ways. They are
int* p;
int *p;
int * p;
main()
{
int x, y;
int *ptr;
x = 10;
ptr = &x;
Data Structures using C: Module-3
y = *ptr;
printf("Value of x is %d\n\n",x);
printf("%d is stored at addr %u\n", x, &x);
printf("%d is stored at addr %u\n", *&x, &x);
printf("%d is stored at addr %u\n", *ptr, ptr);
printf("%d is stored at addr %u\n", y, &*ptr);
printf("%d is stored at addr %u\n", ptr, &ptr);
printf("%d is stored at addr %u\n", y, &y);
*ptr = 25;
printf("\nNow x = %d\n",x);
}
Output:
Value of x is 10
10 is stored at addr 4104
10 is stored at addr 4104
10 is stored at addr 4104
10 is stored at addr 4104
4104 is stored at addr 4106
10 is stored at addr 4108
Now x = 25
Null Pointer
int *b;
b=a=0;
Here b and a become null pointers after the integer value of 0 is assigned to them.
Data Structures using C: Module-3
Pointer to Pointer
Pointer is a variable that contains the address of another variable. Similarly another
pointer variable can store the address of this pointer variable. So we can say, this is a pointer
to pointer variable
POINTER ARITHMETICS
The operations are based on the data type of the pointer—adding 1 to an int pointer moves it by 4
bytes, not 1. This is because it jumps by the size of the data type it points to.
Example:
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
Explanation: *(ptr + 2) moves 2 elements forward, which for int (usually 4 bytes) means +8 bytes.
Example:
#include <stdio.h>
int main() {
int arr[] = {100, 200, 300};
int *ptr = arr;
Explanation: ptr++ increases the pointer by one element (4 bytes for int).
Example:
#include <stdio.h>
int main() {
int arr[] = {7, 14, 21};
int *ptr = &arr[2]; // Pointing to 21
int main() {
int arr[] = {10, 20, 30, 40, 50};int *ptr = arr;
Data Structures using C: Module-3
return 0;
}
ptr + 1 points to the second element, and *(ptr + 1) gives the value at that position.
int main() {
int arr[] = {5, 10, 15, 20, 25};
int *p = arr;
return 0;
}
This method is functionally the same as using arr[i], but it highlights how pointer arithmetic moves
through memory.
MODULE -4
Stacks and Queues
Data Structures using C- Module 4
Data Structures in C is a way of storing and organizing data in the computer memory so
that it can be processed efficiently. Using the data structures in C, we can make our program
to be able to utilize the memory efficiently as well as improve it’s performance.
Depending on how the elements are organized into the memory, data structures can be
broadly classified into two types:
1. Primitive Data Structures: These are the data types which are defined by the C
programming language. Primitive types can only store a value of single type. These are
also known as system-defined data types. int, float, char, double are some primitive
types of data types.
2. Non-Primitive Data structures: These are the data structures in C which are derived
from the primitive data types. Non-primitive data structures are also known as user-
defined data types. Non-primitive data structures in C are able to store values of
multiple data type. Arrays, trees, stack, queue, etc. are some of the user defined data
structures in C.
Further the non-primitive data structures in C can be classified into two categories:
Array
Stack
Queue
Linked List
Tree
Graph
4.2 STACK
What is Stack?
A real-world stack allows operations at one end only. For example, we can place or remove a card
or plate from the top of the stack only. Likewise, Stack ADT allows all data operations at one end
only. At any given time, we can only access the top element of a stack. This feature makes it
LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted
or added) last, is accessed first. In stack terminology, insertion operation is called PUSH
operation and removal operation is called POP operation.
Stack Representation
The following diagram depicts a stack and its operations −
A stack can be implemented by means of Array, Structure, Pointer, and Linked List. Stack can
either be a fixed size one or it may have a sense of dynamic resizing. Here, we are going to
implement stack using arrays, which makes it a fixed size stack implementation.
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 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.
void push() {
if (top == MAX - 1) {
printf("Stack Overflow!\n");}
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 3 − If the stack is not empty, accesses the data element at which top is pointing.
void pop() {
if (top = = -1) {
printf("Stack Underflow!\n");
} else {
int value = stack[top--]; // Return the top element and decrement top
void peek() {
if (top = = -1) {
printf("Stack is empty!\n");
void display() {
if (top = = -1) {
printf("Stack is empty!\n");
} else { int i;
} printf("\n"); }}
}} }}
Data Structures using C- Module 4
#include <stdio.h>
#include <stdlib.h>
void pop() {
if (top == -1) {
printf("Stack Underflow!\n");
} else {
int value = stack[top--]; // Return the top element and
decrement top
printf("Popped element: %d\n", value); }}
void peek() {
if (top == -1) {
printf("Stack is empty!\n");
} else {
printf("Top element is: %d\n", stack[top]); }}
void display() {
if (top == -1) {
printf("Stack is empty!\n");
} else {
printf("Stack elements are:\n");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
printf("\n"); }}
Data Structures using C- Module 4
// Main function to test the stack implementation with a menu and while loop
Void main() {
int choice;
while (1) {
printf("\nStack Operations Menu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
push(); break;
case 2:
pop(); break;
case 3:
peek();break;
case 4:
display();break;
case 5:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
} }}
Data Structures using C- Module 4
multiply A and B,
A*B+C/D AB*CD/+ +*AB/CD divide C by D,
add the results
add B and C,
A * (B + C) / D ABC+*D/ /*A+BCD multiply by A,
divide by D
divide C by D,
A * (B + C / D) ABCD/+* *A+B/CD add B,
multiply by A
Data Structures using C- Module 4
#include <stdio.h> }
#include <ctype.h> else if (ch == '+' || ch == '-' || ch == '*' ||
#define MAXSTACK 100 ch == '/') {
#define POSTFIXSIZE 100 A = pop();
int stack[MAXSTACK]; B = pop();
switch (ch)
int top = -1; {
case '*':
void push(int item) val = B * A; break;
{ case '/':
if (top >= MAXSTACK - 1) { val = B / A; break;
printf("stack over flow"); case '+':
return; val = B + A; break;
}
else { case '-':
top = top + 1; val = B - A; break;
stack[top] = item; }
}} push(val);
int pop() }
{ }
int item; printf(" Result of expression evaluation :
if (top < 0) { %d \n", pop());
printf("stack under flow"); }
}
else { int main()
item = stack[top]; {
top = top - 1; int i;
return item; char postfix[POSTFIXSIZE];
}} for (i = 0; i <= POSTFIXSIZE - 1; i++) {
scanf("%c", &postfix[i]);
void EvalPostfix(char postfix[])
{ if (postfix[i] == ')')
int i; {
char ch; break;
int val; }
int A, B,num; }
4.3 QUEUE
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at
both its ends. One end is always used to insert data (enqueue) and the other is used to remove data
(dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be
accessed first.
A real-world example of queue can be a single-lane one-way road, where the vehicle enters first,
exits first. More real-world examples can be seen as queues at the ticket windows and bus-stops.
Queue Representation
As we now understand that in queue, we access both ends for different reasons. The following
diagram given below tries to explain queue representation as data structure −
As in stacks, a queue can also be implemented using Arrays, Linked-lists, Pointers and Structures.
For the sake of simplicity, we shall implement queues using one-dimensional array.
Basic Operations
Queue operations may involve initializing or defining the queue, utilizing it, and then completely
erasing it from the memory. Here we shall try to understand the basic operations associated with
queues −
enqueue() − add (store) an item to the queue.
dequeue() − remove (access) an item from the queue.
peek() − Gets the element at the front of the queue without removing it.
isfull() − Checks if the queue is full.
isempty() − Checks if the queue is empty.
In queue, we always dequeue (or access) data, pointed by front pointer and while
enqueing (or storing) data in the queue we take help of rear pointer.
Data Structures using C- Module 4
Enqueue Operation
Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively
difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
Step 1 − Check if the queue is full.
Step 2 − If the queue is full, produce overflow error and exit.
Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
Step 4 − Add data element to the queue location, where the rear is pointing.
void enqueue() {
if (rear = = MAX - 1) {
printf("Queue Overflow!\n");
} else {
int value;
scanf("%d", &value);
if (front == -1) {
front = 0;}
queue[++rear] = value;
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 −
void dequeue() {
if (front = = -1) {
printf("Queue Underflow!\n");
} else {
} else { } else {
}} }}
void display() {
if (front = = -1) {
printf("Queue is empty!\n");
} else {
} printf("\n"); }}
}} }}
Data Structures using C- Module 4
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
int queue[MAX];
int front = -1;
int rear = -1;
void enqueue() {
if (rear == MAX - 1) {
printf("Queue Overflow!\n");
} else {
int value;
printf("Enter the value to enqueue: ");
scanf("%d", &value);
if (front == -1) front = 0;
queue[++rear] = value;
printf("Enqueued %d to queue\n", value);
}
}
void dequeue() {
if (front == -1 || front > rear) {
printf("Queue Underflow!\n");
} else {
int value = queue[front++];
printf("Dequeued element: %d\n", value);
if (front > rear) {
front = rear = -1; // Reset to initial state
}
}
}
void peek() {
if (front == -1 || front > rear) {
printf("Queue is empty!\n");
} else {
printf("Peek: %d\n", queue[front]);
}
}
void frontElement() {
if (front == -1 || front > rear) {
printf("Queue is empty!\n");
} else {
printf("Front element is: %d\n", queue[front]);
}
}
Data Structures using C- Module 4
void rearElement() {
if (front == -1 || front > rear) {
printf("Queue is empty!\n");
} else {
printf("Rear element is: %d\n", queue[rear]);
}
}
void display() {
if (front == -1 || front > rear) {
printf("Queue is empty!\n");
} else {
printf("Queue elements: ");
for (int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
printf("\n");
}
}
int main() {
int choice;
while (1) {
printf("\nQueue Operations Menu:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Peek (Front Element)\n");
printf("4. Display\n");
printf("5. Front\n");
printf("6. Rear\n");
printf("7. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1: enqueue(); break;
case 2: dequeue(); break;
case 3: peek(); break;
case 4: display(); break;
case 5: frontElement(); break;
case 6: rearElement(); break;
case 7: printf("Exiting...\n"); exit(0);
default: printf("Invalid choice. Try again.\n");
}
}
return 0;}
MODULE -5
Searching and
Sorting
MODULE 5: