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

Data Structure

Data Structure .
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Data Structure

Data Structure .
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Data Structure Udemy Course:

Topics of course:

 Arrays
 Matrices Physical data structure defines how the data is arranged in
memory.
 Linked List
 Stack
 Queue
 Trees Logical data structure it defines how the data is utilized.
 Graph
 Hashing
 Recursion
 Sorting

What is a program?

 Program: is set of instructions which performs operations on data.

What is data Structure?

 How the program will organize the data in main memory when dealing with it during
execution time.

Data
Memory

Program
Code

Depending in your requirements you can choose suitable data structure.


Level of Knowing Data Structure?

 Level 1: Know all data structures above and how they work.
 Level 2: Know how it works in detail, you can do analysis (time and space
complexity), and you know what operations that performed by them and how its
operations are performed.
 Level 3: You can develop your own data structure.

Do I need to develop the data structure above?

 No, because most programming languages have built in code for these data
structures.
Example of C++ code:

#include <iostream>

using namespace std;

class a {

int a1; // Member variable

public:

// Constructor to initialize the member 'a'

a(int a1);

// Getter function to access the value of 'a'

int getA();

};

int main() {

// Create an object of class 'a' using new

a* a1 = new a(10);

// Output the value of 'a'

int a2 = a1->getA();

cout << "Value of a: " << a2 << endl;

// Don't forget to free the dynamically allocated memory

delete a1;

return 0;

// Forward declaration of class 'a'

// Definition of constructor outside the class

a::a(int a1) {

this->a1 = a1;

// Definition of member function outside the class

int a:getA() {
return a1;

Why Start with recursion?

 You can implement data structure using recursion.


 Help us in problem solving.

Arrays: collection of similar elements with same name.

Int A [5];

Heap

A[5];
1
4
2
5
3 Stack

Void main() {

int a [5] = Code Section


{1,2,3,4,5};

int a [10] = {1,2};


The rest will be initialized by zeros.
The rest meaning in this context:
Elements from index [2 to 9].
cout<<"Enter a size:"<<endl;
int size;
cin>>size.
int A[size]; ----------------------we called this Variable-sized
object;
Variable-sized arrays can’t be initialized
Int A[size] = {1,23,4,5};
Garbage values are values that do not belong to you.

Structure: is a collection of data members that are related to data members under
one name and those data members may be of similar type, maybe of unsimilar
type.

Structure used to define user data type.

Struct Rectangle {
Breadth = Area /
double length; length
S double breadth;

Length = Area / Breadth


Size of structure = total amount of memory consumed by
its members.
Size of rectangular = length (8 byte) + breadth (8 byte).
= 16 bytes
Summary:
 struct: Default access modifier is public.
 class: Default access modifier is private.
Dot operator are used to modify the value like this
a.length = 10;

Rectangle struct
struct complexNumber{
double real /*8 bytes*/;
double img;/*8 bytes*/
/*total 16 bytes*/
};
struct students {
double age; /*4 bytes*/
char name[100] /*100 bytes*/;
char address[100] /*100 bytes*/;
char department[100] /*100 bytes*/;
/*total 304 bytes*/
};

struct card {
int color ; /*4 bytes*/
int face; /*4 bytes*/
int shape; /*4 bytes*/
/*total 12 bytes*/
};
Color  (0,red )or(1,black)
Face  (1,ace) ---- (12,king)
Shape (0,hearts) ----(3,clubs);

struct card {
int color;
int face;
int shape;
};

int main()
{
card myCards[100];
myCards[0] = {0,1,1};

return 0;
}
myCards take memory of (12 * 100) == 1200.

definition of structure does not consume any memory until you create a
struct meaning: struct rectangle r = {1,0};
struct Rectangle {
int length;
int breadth;
char x;
};

The key reason for the discrepancy—why x (a char) appears to take 4 bytes rather
than just 1 byte—relates to (padding and alignment rules in memory).

 Memory alignment means that variables of a particular type are stored in


memory at addresses that are aligned in such a way that the address is a
multiple of the size of the variable.

Why Does Alignment Matter?

 If data is not properly aligned, it may take additional processor instructions to


access that data.
 This is because some systems, especially older or simpler processors, cannot
directly read or write to unaligned memory addresses.
 Instead, the processor must do extra work to align the data before reading or
writing it.

Note: A number is considered a multiple of another number if it can be


evenly divided by that number (i.e., the remainder is zero).
Example of Alignment and Padding:
struct Rectangle {

int length;

int breadth;

char x;

};

int length;

 On most systems, it must be stored at a memory address that is a multiple


of 4. For example, it can be stored at memory addresses like 0x0, 0x4, 0x8,
etc.

int breadth;

 Same a length.

Char x;

 A char typically requires only 1 byte, so it can technically be stored at any


address. However, in the context of the structure, the compiler may add
some padding after x to ensure that the overall structure adheres to
alignment rules

Natural alignment boundary is the address where it is most efficiently accessed.


The natural alignment of a data type is usually related to its size.

In this example why no padding add for integers ?


struct MyStruct { double b; // 8 bytes double c; // 8 bytes int length; // 4 bytes int
breadth; // 4 bytes };

the reason
 is suppose b in address 0x00
 the c will be address 0x08
 the length will be in address 0x16 which multiple of 4 which alignment an
integer
 breadth will be in address 0x20 which also multiple of 4 (20 / 4 = 5 );

Is easy for a machine (CPU) to read 4 bytes at time .

Padding : means it will take extra memory, so it’s easy to our machine to read the
entire structure at the time later it will discard extra three bytes and just used 1
byte.

Pointer
Is an address variable which mean it stores
address of data.
Also, it’s a way to access data indirectly.
int x = 10; // take 4 bytes in memory

int *a = &x; /*On a 32-bit system, a pointer typically takes 4 bytes (32 bits).

On a 64-bit system, a pointer typically takes 8 bytes (64 bits). */

cout<<x<<endl;

cout<<"(x , address of x)"<<"("<< *a <<" ,"<<a<<")"<<endl;

Main memory divided into three parts

 Heap
 Stack
 Code section (our program resides)
Program can directly access just (Stack and Code section).

Program will not directly access heap.

So, program use pointer to access heap memory indirectly And using pointer
to access file that in hard disk or I/O resource or network.
Using of pointer :

 Accessing heap
 Accessing resources (like file or I/O resource)
 Passing parameters

Dereferencing meaning take a data using a pointer like this


int x = 10;

int *p = &x;

int c = *p; -------------------------- c will equal the value of x which 10.

Any declaration on your program will be created on stack frame.


Anything that is dynamically located on memory(heap) on the end of the
program must be released typing delete (C++ language) or free (C
language).

When the program ends it will automatically be deleting the heap memory.
All types of pointers take 8 byte of memory.
Reference: nickname given to a variable

Must declare and initialize the reference


int &r;
without initialize will cause a “error: 'r' declared as reference but not initialized”.

Reference does not consume memory; it uses the same memory of variable.

Example:

Int a = 10;

int &r = a;

“r” here does not take any memory it just uses memory of variable “a” not
create new memory

Example in java to understand the concept:

StringBuilder c = new StringBuilder(“hello”);

StringBuilder b = c;

“b” just reference to instance does not create new instance.


#include <iostream>

#include <stdio.h>

using namespace std;

struct Rectangle {

int length;

int breadth;

};

void changeInt(int &a)

a = a + 10;

int main() {

struct Rectangle *rec = new struct Rectangle;

rec -> length =10;

(*rec).breadth = 20;

cout<<(*rec).length<<endl; ------------- 10

cout<<(*rec).breadth<<endl; ------------ 20

int c =140;

return 0;

)*rec).length == rec ->length

“->” to make code more readability.


In C compiler this statement invalid :
Rectangle r;
Because of forget to write Struct keyword before Rectangle.

Function : Paice of code which perform specific task.


Other definition group of related instructions which perform specific task.
We call it a procedure if it returns a value.

Monolithic programming: refers to a design where the entire program is


written as a single, large block of code, usually within a single function,
typically the main function, without modularization into smaller, reusable
functions. This approach places all the logic in one place, which can make
the program harder to maintain, read, and debug as it grows.

Modular programming : is a software design technique that involves breaking


a program into smaller, self-contained units or modules, each responsible for
a specific piece of functionality. These modules can then be developed,
tested, and maintained independently, making the overall system easier to
manage and extend.

Class: we can say that is group of functions(Paice of code which perform


specific task) and group of structures (group of elements or fields).

 Function: Call a function when you need to calculate or process


data and receive a value in return.

 Method: Call a method when you're working within an object-


oriented context, and you want to invoke a behavior associated with
an object or class.

 Procedure: Call a procedure when you need to perform an action or


task, but you don't need any result or return value.
Formal parameters

int add (int a, int b) ----------------- “prototype of function” or “declaration of


function.”
{
int c = a + b; called

function

return c; body or definition of function.


}
int main ()
{
int a = 10;
int b = 20;
Actual parameters

add (a, b); --------------------- function called.


}
The prototype or declaration of a function refers to its signature that
informs the compiler or interpreter about the function's name, return type,
and parameters (if any), without providing the actual implementation or
body of the function.

Add B:5 int add (int a, int b) {


a:10
C:15 int c = a + b;
Stack return c;
X: 10 Z:15

}
Y:5
Main int main () {
int x = 10;

Main { int y = 5;

} int z = add(x, y);


return 0
Add { Code section }
}
Parameters passing:

 Value passing
 Reference passing
 Pointer passing

Calling by values

Calling by pointers:
One function can access other functions using pointer.

Calling by reference: here swap become of part of main function because of


its parameters is reference meaning in code section for main will contain a
machine code for swap function.

One function can access other functions indirectly using pointer.

Array as parameters:

For passing array for parameter must type “[]” or like this *a

void accessArray (int a [], int size) or (int * a, int size)

for (int i = 0; i< size; i++)

{
Cout<<a[i]<<endl;

Here a [] is pointer to “array in stack” which declare in main ().

Array pass by “address”.

“a” and “array” point to same array in heap.


In programming languages like C and C++, an array is often treated similarly to a pointer,
but it is not exactly the same.

Relationship Between Arrays and Pointers:

1. Array Declaration:

o When you declare an array, e.g., int arr[5];, arr is the name of the array, and it
refers to the first element of the array.

2. Pointer Behavior:

o In expressions, the name of the array (arr) can be used as a pointer to the first
element of the array. This means that arr can be used in a similar way as a
pointer.

o For example, arr can be used to access the first element (*arr), and the array
can be indexed with arr[i].

3. Pointer to an Array:

o An array name, like arr, decays into a pointer to the first element when passed
to functions, meaning that when you pass arr to a function, it's essentially
passing a pointer to the first element, not a copy of the entire array.

4. Differences Between Arrays and Pointers:

o Memory Location: An array has a fixed size determined at compile time, and
its name refers to the memory location where the entire array starts. In
contrast, a pointer is a variable that can be changed to point to different
memory locations.

o Size: The size of an array is fixed and known at compile time, whereas a
pointer can dynamically point to different memory locations, and you might
not know the size of the data it points to.

o Array vs. Pointer Arithmetic: Pointer arithmetic works directly with


pointers, but when using arrays, the array name behaves like a pointer, and
you can use pointer-like arithmetic (e.g., arr + i is equivalent to &arr[i]), but
array elements cannot be reassigned to point to other memory locations, as
pointers can.

Example in C/C++:

Copy code

int arr[5] = {1, 2, 3, 4, 5};

int *ptr = arr; // Pointer points to the first element of the array

printf("%d\n", *arr); // Outputs 1, same as *ptr

printf("%d\n", *(arr + 1)); // Outputs 2, same as ptr[1]

ptr = ptr + 1; // Pointer can be incremented to point to the next element

// arr++; // This would result in a compile-time error since arrays cannot be incremented

Key Points:

 Array Name as Pointer: In many contexts, the name of the array behaves like a
pointer to its first element.

 Array vs. Pointer: Arrays are not pointers, but they can be used like pointers in
many scenarios, especially when passing them to functions.

 Fixed vs. Variable Address: While the array's name points to the first element, a
pointer is a variable that can point to any memory location.

You might also like