0% found this document useful (0 votes)
5 views

DSA-unit-1

Uploaded by

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

DSA-unit-1

Uploaded by

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

Introduction Data Structure

1. What is Data structure ?


2. Why we need to study Data structure
3. Classification of data structures
Definition :
• In computer science, a data structure is
defined to be a well structured format that
organizes, manages, and stores data in a
memory at the processing.
Basic Need of Data Structure
– As applications are becoming more complex and the amount of data is
increasing day by day, which may cause problems with processing
speed, searching data, handling multiple requests etc.
– Data structure provides a way of organizing, managing, and storing data
efficiently. With the help of data structure, the data items can be
traversed easily.
– Data structure provides efficiency, reusability and abstraction. It plays
an important role in enhancing the performance of a program because
the main function of the program is to store and retrieve the user’s data
as fast as possible.
– Data structure and algorithms are two of the most important aspects of
computer science. Data structures allow us to organize and store data,
while algorithms allow us to process that data in a meaningful way.
Learning data structure and algorithms will help you become a better
programmer. You will be able to write code that is more efficient and
more reliable. You will also be able to solve problems more quickly and
more effectivel
Basic Need for Data Structure
• Any computer program serves some kind
of data processing.
• Even those programs that do not compute
anything (for instance, a program that
copying a file from one location to another
one) operate with some data.
• To access these data and to collect the
resulting data, it is necessary to organize
them in some reasonable structures.
• Knowing data structures, it is easier to
learn different programming languages.
Three major components that define Data
Structure
• Relationships: In a data structure, elements are related or
connected in some way. They follow a sequence, or are arranged in
a certain format. This contrasts with an assortment of different but
unrelated variables. For example, three stand-alone integers do not
necessarily share any relationship.
• Operations: Each data structure is associated with a collection of
functions that can implement and manipulate it. These integrated
algorithms are used to interact with the actual data. Most data
structures support operations such as adding or deleting an item.
However, other operations are only meaningful in certain situations.
For instance, it might make sense to sort an array, but not a hash
table.
• Data Values and Type: The definition of a data structure also
includes the values it contains and the type of data it allows. In some
data structures, all values must have the same type, while others do
not enforce any restrictions.
Classification of data Structure
• Primitive Data Structure –
– Primitive Data Structures directly operate according to the
machine instructions.
– Data types like int, char, float, double, and pointer are
primitive data structures that can hold a single value.
• Non – Primitive Data Structure –
– Non-primitive data structures are complex data structures that
are derived from primitive data structures.
– Non – Primitive data types are further divided into two
categories.
• Linear Data Structure - Examples are List, Queue, Stack,
Array etc.
• Non – Linear Data Structure - Examples are Tree, BST,
Graphs etc.
Uses of Data structures in computing
• Searching: Many data structures support efficient algorithms to find a
specific entry from within a longer list.
• Storage/Scaling: Using data structures, large amounts of data can be
effectively structured, organized, and stored. Several data structures are
designed to interact with relational database management systems.
• Indexing: Hash tables and some tree structures can index a long list of
entries.
• Sorting: A classic data structure called a binary search tree is often used to
sort a list of unordered data into alphabetical order or some other
arrangement.
• Listing: Simple data structures such as arrays can retrieve any data items
matching a set of criteria.
• Data Transfer: Data structures are a good choice to share information
through an interface or API because both client and server have a common
understanding of the data. The transfer might occur between classes or
functions, or between a client an
UNIT-1. Pointers and Structures

Topics to be covered :
1. Pointers, Structures : Introduction to pointers,
pointers and Arrays, Pointers to pointers, pointers
to functions
2. Introductions to Structures : Declarations,
initializations, Accessing Structures, Internal
implementations of structures
3. Files in C : Text input output with respect to
files in C, Basic file handling functions in C

9
Pointers
Objectives
❏ To understand the concept and use of pointers
❏ To be able to declare, define, and initialize pointers
❏ To write programs that access data through pointers
❏ To use pointers as parameters and return types
❏ To understand pointer compatibility, especially regarding pointers to
pointers
❏ To understand the role of quality in software engineering

1. Introduction to pointers
2. Pointers and Arrays
3. Pointers to pointers
4. Pointers to functions
1. Introduction to Pointers
A pointer is a variable that contains an address of
other variable that holds access data.
Advantages :
•Pointers can be used to return multiple values from a
function via function arguments (output parameters).
•Pointers allow C to support dynamic memory
management.
•Use of pointers increases the execution speed and
thus reduces the program execution time.
Example - Returning MULTIPLE values from a functions
12
Example - Returning MULTIPLE values from a functions
13
Understanding Pointers
0
• Computer’s memory is a
1
sequential collection of storage
2
location.
3
• Each location, commonly known 4
as a byte, is identified by an 5
address associated with it. .
• These addresses are numbered .
consecutively, starting from zero. .
• The last address depends on the .
memory size.
– A computer system having 64K
memory has its last address as
65535. 6553
5
• int quantity = 250;

quantit variabl
y e
250 valu
e
500 addres
0 s
• A variable that can hold address of another
variable is called a pointer variable.
• int quantity = 250;
• int *p = &quantity;

variabl valu address


e e
quantit 250 500
y 0

p 5000 501
2
• Since the value of the variable p is the address of the
variable quantity, we may access the value of quantity by
using the variable p, and therefore we say that the
variable p points to the variable quantity. Thus p is the
name of the pointer.
Example on Accessing the Address
of a Variable
• We can access the address of a variable with
the & operator in C.
– We have already used & operator in scanf
function.
• The operator & immediately preceding the
variable returns the address of the variable
associated with it.
– p = &quantity; //assigns the address 5000 (value
decided at run time) to p.
• The & operator can be used only with a simple
variable or an array element.
main()
{
int a;
float p, q;
char choice;
a = 15;
p = 10.25f;
q = 5.46f;
choice = 'Y';
printf("%d is stored at address %u\n", a, &a);
printf("%f is stored at address %u\n", p, &p);
printf("%f is stored at address %u\n", q, &q);
printf("%c is stored at address %u\n", choice, &choice);
}

Output:
15 is stored at address 6356748
10.250000 is stored at address 6356744
5.460000 is stored at address 6356740
Y is stored at address 6356739
Declaring Pointer Variables
• Declaration Syantax : data_type *ptr_name;
– The asterix (*) tells that the variable ptr_name is a pointer variable.
– ptr_name needs a memory location.
– ptr_name points to a variable of type data_type.
• Examples - 1. int *p; // declares the variable p as a pointer variable
that can point to a memory location holding an integer data type.
2. float *q; // declares the variable q as a pointer variable
that can point to a memory location holding float data type.
• Since the memory locations corresponding to p and q have not been
assigned any values, these contain garbage value and therefore point
to unknown locations.
– Example: int *p;

p ? ?
contains points to unknown
garbage location
Initialization of Pointer Variable
• The process of assigning the address of a
variable to a pointer variable is known as
initialization.
– Uninitialized pointers will have unknown
values.
– It is important to initialize pointer variables
before they are used in the program.
• int quantity;
• int *p;
int *p = &quantity;
• p = &quantity;
Initialization of Pointer Variable
• We must ensure that the pointer variables always point to the
corresponding type of data.
– float a, b;
– int sum, *p;
– p = &a; // Wrong
• It is possible to declare combine declaration of simple variable,
declaration and initialization pointer variable in one statement.
– int a, *p = &a;
– Declares a as an integer variable and p as a pointer variable and
then initializes p hold the address of a.
• We can also define a pointer variable with an initial value of
NULL or zero.
– int *p = NULL; // same as int *p = 0;
Accessing a Variable Through its
Pointer
• To access value of a variable using the
pointer, we use the asterisk (*) operator, also
known as the indirection operator or
dereferencing operator.
– int quantity, *p, n;
– quantity = 250;
– p = &quantity;
– n = *p; // equivalent to n = *&quantity; which in
turn // is equivalent to n = quantity;
– Here *p returns the value of the variable quantity.
main()
{
int a, b;
int *p;
a = 15;
p = &a;
b = *p;
printf("Value of a is %d and address is %u\n", a, &a);
printf("Value of a is %d and address is %u\n", *&a, &a);
printf("Value of a is %d and address is %u\n", *p, p);
printf("%d is the address pointed to by %u\n", p, &p);
printf("Value of b is %d and address is %u\n", b, &b);
*p = 25;
printf("Now the value of a is %d", a);
}
Value of a is 15 and address is 6356748
Value of a is 15 and address is 6356748
Value of a is 15 and address is 6356748
6356748 is the address pointed to by 6356740
Value of b is 15 and address is 6356744
Now the value of a is 25
Stag Values stored in locations and their
e a
addresses b p

Declaratio
n
635674 635674 635674
8 a 4 b 0
p

a= 10
10
635674 635674 635674
8 a 4 b 0 p

p= 10 6356748
&a
635674 635674 635674
8 a 4 b 0 p

b= 10 10 6356748
*p
635674 635674 635674
8 a 4 b 0 p

b= 10 10 6356748
*p
635674 635674 635674
• ADD few more Examples
Pointers and Arrays
• When an array is declared, the compiler allocates a base
address and memory to hold the array elements in
contiguous memory locations.
– The base address is the location of the first element (index 0) of
the array.
– The compiler also defines the array name as a pointer to the first
element.
– int a[5] = {4, 10, 8, 5, 20};
– The name a is the base address (pointer) that points to the first
element, a[0] and therefore value of a is 1000.

Element a[0] a[1] a[2] a[3] a[4]


s
Valu 4 10 8 5 20
e
Addres 1000 1004 1008 1012 1016
s
base
• int *p;
• p = a; // equivalent to p = &a[0];
– p is an integer pointer that points to array a.
– We can access elements of a using p.
– p = &a[0] (=1000)
– p+1 = &a[1] (=1004)
– p+2 = &a[2] (=1008)
– p+3 = &a[3] (=1012)
– p+4 = &a[4] (=1016)
• Address of a[3] = base address + (3 * sizeof(int))
= 1000 + (3 * 4) = 1012
Program to add array elements
using Pointers
main()
{
int a[] = {3, 4, 8, 2, 7, 5};
int *p, i, sum;
p = a;
sum = 0;
for(i=0; i<6; i++)
{
sum = sum + *p;
p++;
}
printf("Sum is %d", sum);
}
Pointers to pointers
• So far, all our pointers have been pointing
directly to data.
• It is possible—and with advanced data
structures often necessary—to use
pointers that point to other pointers.
• For example, we can have a pointer
pointing to a pointer to an integer
FIGURE 9-20 Pointers to
Pointers Computer Science: A Structured 30
Programming Approach Using C
FIGURE 9-21 Using Pointers to
Pointers Computer Science: A Structured 31
Programming Approach Using C
PROGRAM 9-6 Using pointers to
pointers

Computer Science: A Structured 32


Programming Approach Using C
PROGRAM 9-6 Using pointers to
pointers

Computer Science: A Structured 33


Programming Approach Using C
PROGRAM 9-6 Using pointers to
pointers

Computer Science: A Structured 34


Programming Approach Using C
Pointers to functions
Pointer to Function
• Functions in our program occupy memory.
The name of the function is a pointer
constant to its first byte of memory.
• To declare a pointer to function, we code
it as if it was a prototype definition, with
the function pointer in parentheses.

36
37
Example: function larger
• This generic function will return a larger
value of two values to be compared
• To use a larger function as a generic one,
we will need to write a compare function
for each particular data type. A compare
function will return either a positive or
negative flag value depending on which
value in a compared pair is larger: the first
one or the second one.

38
39
40
41
42
43
44
45
2. Structures :
1. Introduction
2. Declarations, initializations,
2. Accessing Structures,
3.Internal implementations of structures
2. Structures - Introduction
• Arrays can be used to represent a group of data
elements of same type.
• However, we cannot use an array to represent a
collection of data elements of different types using
a single name.
• C supports a constructed (or programmer-defined)
data type called structures, a mechanism for
grouping data of different types.
– A structure can be used to group logically related data
items.
Arrays Vs. Structures
• An array is a collection of related data
elements of same type.
– Structure can have elements of different types.
• An array is a derived data type whereas a
structure is a programmer-defined type.
• An array behaves like a built-in type. We just
declare an array and use it.
– In case of structure, we need to define the format
of the structure before the variables of that type
are declared and used.
Structures help us to organize complex
data in a meaningful way…
• Examples on related data items
– book
• author, title, price, year
– student
• name, roll-no, marks
– address
• name, door_number, street, city, pin
– customer
• name, phone_no, city
– inventory
• item, stock, price
Defining a Structure
• Syntax • Example
struct structure_name struct Book
{ {
data_type member1; char title[20];
data_type member2; char author[15];
… int pages;
data_type member; float price;
}; };
• The keyword struct defines a structure with a name Book to hold
four data fields viz., title, author, pages and price.
– These fields are called structure elements or members.
– Each member may belong to a different data type.
– Book is the name of the structure and is called the structure tag.
– The tag name can be used subsequently to declare variables.
Defining a Structure
• The keyword struct defines a structure to
hold four data fields viz., title, author,
pages and price.
– These fields are called structure elements or
members.
– Each member may belong to a different data
type.
– Book is the name of the structure and is called
the structure tag.
– The tag name can be used subsequently to
declare variables.
Defining a Structure
title array of 20 characters

array of 15
author characters

pages integer

price float

• Note that the definition does not declare any


variables. It simply describes a format called
template to represent the information as shown
above.
Declaring Structure Variables
– Syntax:
• struct <tag_name> variable_list;
– Example:
• struct Book C-Book, DS-book[5], Maths-books[10];
– Remember that the members of a structure
themselves are not variables.
– They do not occupy any memory until they are
associated with the structure variables such as
C-book.
• The following declaration is also valid.
struct Book
{ Boo
chark title[20];
char author[15]
int pages;
float price;
} C-book, DS-book[5], Maths-books[10];

• The use of tag_name is optional here.


–However, this is not recommended, as we cannot use it
for future declarations.
Accessing Structure Members
• Structure members have no meaning
individually without the structure.
• In order to assign a value to any structure
member, the member name must be linked
with the structure variable using a
dot ● operator also called period or member
access operator.
– strcpy(C-book ● title, “Programming in C”);
– strcpy(C-book ● author, “Balaguruswamy”);
– C-book ● pages = 250
– C-book ● price = 175.50;
We can also use scanf to assign values to the
members.
struct Book
{
char title[25];
char author[10];
int pages;
float price;
};
main()
{
struct Book c-book;
printf("Enter title. Author, pages and price of a C book :");
scanf("%s%s%d%f", c-book.title, c-book.author);
scanf(“%d%f”, c.book.pages, c.book.price);
printf(“ C Book details are...\n");
printf(“ Title of the book :%s\n”, c-book.title);
printf(“ Author of the book : %s\n ”,c-book.author
printf(“ Pages in the book : %d\n ”,c-book.pages:
printf(“ Price of the book : %f “, c-book.price);
}
Structure Initialization
• C does not permit the initialization of individual
structure members within the template.
• The initialization must be done only in the
declaration of the actual variables.
• Like any other data type, a structure variable can
be initialized at compile time.
• Syntax:
– struct <tag_name> structure-var = {initialization_list};
• Example:
– struct Book C-book= {“C-Programming”,“Ritche", 225, 250.0 };
Rules for Initializing Structures
• We cannot initialize individual members
inside the structure template.
• The order of values enclosed in
initialization_list must match the order of
members in the structure definition.
• It is possible to have partial initialization.
– The uninitialized members should be at the end of
the list.
• The uninitialized members will be assigned
with default values.
– Zero for integer and floating point numbers,
– ‘\0’ for characters and strings.
Copying and Comparing Structure
Variables
• Two variables of the same structure type
can be copied the same way as ordinary
variables.
– book2 = book1; //Permitted
• However, C does not permit the use of
logical operators (== and !=) on structure
variables.
– In such case, we need to compare them by
comparing members individually.
Comparing Two Structure
Variables
struct Student s1 = {"Ramesh", 25, "Civil"};
struct Student s2 = s1; //We can assign one to another
struct Student s3 = {"RAMESH", 25, "Civil"};
struct Student s4 = {"Ramesh", 25, "Civil"};
int res;
res = ((strcmp(s1.name,s2.name)==0) && (s1.rollno == s2.rollno)
&& (strcmp(s1.branch,s2.branch)==0)) ? 1 : 0;
printf("s1 and s2 are same:%d\n", res); //Prints 1
res = ((strcmp(s1.name,s3.name)==0) && (s1.rollno == s3.rollno)
&& (strcmp(s1.branch,s3.branch)==0)) ? 1 : 0;
printf("s1 and s3 are same:%d\n", res); //Prints 0
res = ((strcmp(s1.name,s4.name)==0) && (s1.rollno == s4.rollno)
&& (strcmp(s1.branch,s4.branch)==0)) ? 1 : 0;
printf("s1 and s4 are same:%d\n", res); //Prints 1
Operations on Individual
Members
• Individual members of a structure are
accessed using the dot operator.
• A member of a structure can be treated like
any other variable name and therefore can be
manipulated using expressions and
operators.
– if(s1.rollno == 111)
• s1.marks = s1.marks + 5;
– float sum = s1.marks + s2.marks;
– s2.marks = s2.marks + 4;
– s1.marks++;
3. File Management in C
• So far, we have used scanf and printf to read and
write data from/to console.
• A file is a place on the disk(secondary disk) where a
group of related data is stored. i.e. Discrete storage
unit for data in the form of a stream of bytes
• C supports a number of functions to perform basic file
operations such as,
– Naming a file (while creating a new file),
– Opening a file,
– Reading data from a file,
– Writing data to a file, and
– Closing a file.
Defining and opening a file
• If we want to create a file and store data into it, we must
specify
– Filename
• A string of characters that make a valid filename for the operating
system.
– Purpose of opening (whether to read or write)
• FILE is a data type.
• The general form for declaring and opening a file is:
– FILE *fp;
– fp = fopen(“Filename”, “mode”);
– fp is a pointer to data type FILE.
– mode can be
• r – open the file for reading only
• w – open the file for writing only
• a – open the file for appending (or adding) data to existing file.
• When trying to open a file, one of the
following things may happen:
– When the mode is “w”, a file with the specified
name is created if it does not exist. The current
contents are deleted if the file already exists.
– When the mode is “a”, the file is opened with
the current contents safe. A file with the
specified name is created if it does not exist.
– When the mode is “r”, and if it exists, the file is
opened with the current contents safe.
Otherwise an error occurs.
Sample Example
main()
{
FILE *fp;
char ch;
fp = fopen("input.txt", "w");
while((ch=getchar())!=EOF)
putc(ch, fp);
fclose(fp);
fp = fopen("input.txt", "r");
while(!feof(fp))
{
printf("%c", getc(fp));
}
fclose(fp);
}
Closing a file
• A file must be closed as soon as all
operations on it have been completed.
– This prevents accidental misuse of the file.
• The function to close a file is:
– fclose(fp);
– This will close the file associated with the
FILE pointer fp.
• fclose(fp);
Input/Output Operations on
Files
• The getc and putc functions
– Analogous to getchar and putchar functions and
handle one character at a time.
– putc(ch, fp)
• writes the character contained in variable ch to the file
associated with fp.
– ch = getc(fp)
• reads a character from the file whose file pointer is fp.
– The file pointer moves by one character for every
operation of getc or putc.
• The getc will return an end-of-file marker EOF, when
the end of the file has been reached.
main()
{
FILE *fp;
char ch;
fp = fopen("input.txt", "w");
while((ch=getchar())!=EOF)
putc(ch, fp);
fclose(fp);
fp = fopen("input.txt", "r");
while(!feof(fp))
{
printf("%c", getc(fp));
}
fclose(fp);
}
The fprintf and fscanf Functions
• fprintf and fscanf can handle a group of
mixed data simultaneously.
– fscanf(fp, “control string”, list);
• Reads the items in the list from the file specified by
fp, according to the input specifications contained
in the control string.
• When the end of file is reached, it returns the value
EOF.
– fprintf(fp, “control string”, list);
• fp is the file pointer associated with a file that has
been opened for writing.
• The control string contains output specifications for
the items in the list.
main()
{
FILE *fp;
int rollno, marks, i, n;
char name[20];
fp = fopen("student.txt", "w");
printf("Enter number of students:");
scanf("%d", &n);
printf("Enter student data:\n");
printf("Roll Number Name Marks\n");
for(i=1; i<=n; i++)
{
scanf("%d %s %d", &rollno, name, &marks);
fprintf(fp,"%d %s %d\n", rollno, name, marks);
}
fclose(fp);
fp = fopen("student.txt", "r");
printf("Roll No Name Marks\n");
for(i=1; i<=n; i++)
{
fscanf(fp, "%d %s %d", &rollno, name, &marks);
printf("%d\t%s\t%d\n", rollno, name, marks);
}
fclose(fp);
}
• Write a C program that creates a file
reading contents that the user types from
the keyboard till EOF. The text in this file
must be in lowercase. There could be
multiple blanks in between some words.
Create another file in which the same
content is copied in UPPERCASE and
with only one blank in between the words
that contained multiple blanks.
int main()
{
FILE *f1, *f2;
char ch, ch1, line[80];
f1=fopen("input.txt","w");
printf(“Enter text (Type END to terminate):\n”);
do
{
gets(line);
if(strcmp(line, "END") == 0)
break;
fputs(line,f1);
fputs("\n", f1);
}while(1);
fclose(f1);
Continued…
f1=fopen("input.txt","r");
f2=fopen("output.txt","w");
while((ch=getc(f1))!=EOF)
{
if(ch==' ' && ch==ch1)
continue;
putc(toupper(ch),f2);
ch1=ch;
}
fclose(f1);
fclose(f2);
printf("\n Copied to output file. \n\n");
return 0;
}
End of Unit

You might also like