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

Arrays

Data Structures

Uploaded by

devhamnah
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Arrays

Data Structures

Uploaded by

devhamnah
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Data Structure and

Algorithms

Lec # 02
Abstract Data Types
Abstract Data Type (ADT): refer to as a set of
values and a set of operations on that data
type.
Each ADT operation is defined by its inputs
and outputs.
Encapsulation: Hide implementation details.

2
Data Structure
 A data structure is the physical
implementation of an ADT.
 Each operation associated with the ADT is
implemented by one or more subroutines in the
implementation.
 In a OO language such as C++, an ADT and
its implementation together make up a class.

 Data structure usually refers to an


organization for data in main memory. 3
 File structure: an organization for data on
Arrays
 Elementary data structure that
exists as built-in in most
programming languages.

main( )
{
int x[6];
int j;
for(j=0; j < 6; j++)
x[j] = 2*j;
}
Arrays
 Array declaration: int x[6];
 An array is collection of cells of the same
type.
 The collection has the name ‘x’.
 The cells are numbered with consecutive
integers.
 To access a cell, use the array name and
an index:
x[0], x[1], x[2], x[3], x[4], x[5]
Array Layout
Array cells are x[0]
contiguous in
x[1]
computer memory
x[2]
The memory can be
thought of as an x[3]
array
x[4]

x[5]
What is Array Name?
 ‘x’ is an array name but there is no variable x. ‘x’ is not an lvalue.
 For example, if we have the code

int a, b;

then we can write

b = 2;
a = b;
a = 5;

But we cannot write


2 = a;
Array Name
 ‘x’ is not an lvalue
int x[6];
int n;
x[0] = 5;
x[1] = 2;
x = 3; // not allowed
x = a + b; // not allowed
x = &n; // not allowed
Array Declaration
O arrayType arrayName[numberOfElements ];
O For example : int age [ 10 ] ;

O More than one array can be declared on a line:


O int age [10] , height [10] , names [20] ;
O Mix declaration of variables with: declaration
of arrays
O int i , J , age [10] ;
9
Array Declaration
O arrayType arrayName[numberOfElements ];

age[0]
O For example : int age [ 10 ] ;
age[1]

age[2]
age[3]
age[4] .72
age[5] .94
age[6]

age[7]

age[8] 10

age[9]
Initializing Array
There are several ways to initialize an array:
O int age[3]; age[0]=32;age[1]=34;age[2]=40;
O int age [ 10 ] = { 0,0,0,0,0,0,0,0,0,0} ;
O int age [ 10 ] = { 0 } ;
O int age [ 5 ] = {10,15,30,20,34} ;

11
Initializing Array
Perhaps the most common way is the use of
loops for initialization:
int c[10];
for(int i=0;i<10;i++)
cin>>c[i];
for(int i=0;i<10;i++)
out<<c[i];
12
Example# 1
int main(){
int age[5];
for(int i=0;i<5;i++){
cout<<"Please enter your age:";
cin>>age[i]; }
for(int i=0;i<5;i++){
cout<<"You Entered:"<<age[i]<<endl;
}
getch();
return 0;
} 13
14
Problem

Write a code which finds out minimum


element from an array of 10 digits

15
#include<conio>
#include<iostream>
void minimum(int[]);
const int Size=10;
int main(){
int array[Size];
cout<<"Enter 10 elements:";
for(int i=0;i<Size;i++)
cin>>array[i];
minimum(array);
getch();
return 0; 16

}
void minimum(int a[Size]){
int min;
min=a[0];
for(int i=1;i<Size;i++){
if(a[2]<min)
min=a[i];
}
cout<<"\nMinimum Element :"<<min;
}

17
Copying Arrays
O To copy from array “ a ” to array “ b ” :
Ob [ 0 ] = a [ 0 ] ; for(int i=0;i<11;i++)
Ob [ 1 ] = a [ 1 ] ; {
Ob [ 2 ] = a [ 2 ] ; b[i] = a[i]; b[2] =
a[2]
Ob [ 3 ] = a [ 3 ] ; }
O… … … … … …
O b [ 10 ] = a [ 10 ] ;
18
int main(){
int age[]={56,23,45,57,98};
int c[5];
for(int i=0;i<5;i++){
c[i]=age[i];
}
cout<<"Elements of c are now:";
for(int i=0;i<5;i++){
cout<<c[i]<<" ";
}
getch();
return 0;
} 19
Problem
Initialize an array of ten integers. Input the
numbers of ten students. Calculate average of
these numbers. Output the average

20
int main(){
const int ArraySize=10;
int numbers[ArraySize];
int add=0;
for(int i=0;i<ArraySize;i++){
cout<<"Plz Enter ur Number:";
cin>>numbers[i];
add+=numbers[i];
//Exactly Equal to add=add+numbers[i]
}
cout<<"\nAverage is:"<<(add/10);
getch();
return 0;
21
}
Dynamic Arrays
 You would like to use an array data structure
but you do not know the size of the array at
compile time.
 You find out when the program executes that
you need an integer array of size n=20.
 Allocate an array using the new operator:

int* y = new int[20]; // or int* y = new int[n]


y[0] = 10;
y[1] = 15; // use is the same
Dynamic Arrays
 ‘y’ is a lvalue; it is a pointer that holds the
address of 20 consecutive cells in memory.
 It can be assigned a value. The new operator
returns as address that is stored in y.
 We can write:

y = &x[0];
y = x; // x can appear on the
right
// y gets the address of
the
Dynamic Arrays
 We must free the memory we got using the
new operator once we are done with the y
array.

delete[ ] y;

 We would not do this to the x array because we


did not use new to create it.
Character Arrays
O Character array can be initialized as:
char string[]=“first”;
O This string contains 5 character and a
special character
O This character is ‘\0’

25
Character Arrays
O This character is appended in the end of string by
compiler
O We can store character by character in this kind of
array like
O char string1[]={‘f’,’i’,’r’,’s’,’t’,’\0’};
O We can use cin for input
O For output of string cout work and display char
array up to Null character
26
int main(){
char c[100],d[]={'T','h','i','s',' ','i','s','\0'};
cout<<"Plz Enter c string:";
cin>>c;
cout<<"\nd is: "<<d;
cout<<"\nc is: "<<c;
cout<<"\nc from Loop: ";
for(int i=0;c[i]!='\0';i++){
cout<<c[i];
}
cout<<"\nd from Loop: ";
for(int i=0;d[i]!='\0';i++)
cout<<d[i];
getch();
27
return 0;
}
int main(){
char c[]="Two roads diverged\n in a yellow
wood,";
cout<<c;
int i=0;
while(c[i]!='\0'){
if(c[i]=='d')
c[i]='e';
i++;
}
getch();
return 0; 28

}
Problem

O Declare an array of characters. The size of the


array is 100.Input a string from the user and
return it with more spaces (add tab) on the
location where spaces already exists.

29
#include<stdio.h>
int main(){
char a[100];
cout<<"Plz Enter A String:";
gets(a);
cout<<"\nThe text with more spaces:\n";
for(int i=0;a[i]!='\0';i++){
if(a[i]==' ')
a[i]='\t';
}
cout<<a;
getch();
30
return 0;
}
31
Exercise

O Input your name and display it in reverse


order
O Count the element of any character array

32
#include<iostream>
#include<conio>
#include<stdio>
void main(){
char a[100];
gets(a);
int count=0;
for(int i=0;a[i]!='\0';i++,count++);
for(int i=count-1;i>=0;i--)
cout<<a[i];

getch(); 33

}
Operations on Arrays
O Traversal
O Search
O Sorting

34
Search
O Important area in computer science
O The process of finding particular element in an
array is called searching
O The technique we use for searching an element
from the array is called linear search
O The element to be searched is also sometimes
called key

35
Linear Search or Sequential
Search
0 1 2 3 4 0 1 2
3 4
5 3 17 60 2 5 3 17 60 2

Ke Ke
y y

0 1 2 3 4 5 3 17 060 1
2 2
35 3
4 17 60 2

Ke Ke
5 30 17 1
60 2
2 3 4
y
y

Ke
y
Linear Search or Sequential
Search
 For Example An Array is
int array[8] = {6 4 1 97 3 2 8}

 If we have to find the 3 how we find


using the Linear Search?
 Compare 3 with each element of the
array
 if it match with any element of the array
then it returns its index.
 Otherwise No is Not found in the array
Linear Search or Sequential
Search
Key List
3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8
Searching in an Array
#include<conio>
#include<iostream>
int main(){
const int arraySize=10;
int
Record[arraySize]={19,3,15,11,9,13,5,17,11,
5};
cout<<"Enter the element you want to
search:";
int i,n,found=0; 39

cin>>n;
for(i=0;i<arraySize;i++){
if(n==Record[i]){
found=1;
break;
}
}
if(found==1)
cout<<"Element is found at location
Record["<<i<<"]";
else
cout<<"Element not found in record";
getch(); 40
return 0;
}
Binary Search
O Quicker method to search an element
O It cannot be applied on an unsorted array

O It locates the middle element of array and compare with the


search number
O If the value is found, its index is returned
O An algorithm to solve this task looks at the middle of the
array
O If the value looked for is smaller than the value in the middle
of the array
O Then the second half of the array or array segment can be ignored
O This strategy is then applied to the first half of the array or array
segment
Binary Search
O If the value looked for is larger than the value in the
middle of the array or array segment
O Then the first half of the array or array segment
can be ignored
O This strategy is then applied to the second half of
the array or array segment
O If the value looked for is at the middle of the array or
array segment, then it has been found
O If the entire array (or array segment) has been
searched in this way without finding the value, then
it is not in the array
Binary Search
OGiven value and sorted array a[], find index i
such that a[i] = value, or report that no such index
exists.
OInvariant. Algorithm maintains a[start]  value  a[end].
O Ex. Binary search for 33.

6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

start end
Binary Search
O Invariant. Algorithm maintains a[lo]  value
 a[hi].

O Ex. Binary search for 33.

6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

start mid end


Binary Search
O Invariant. Algorithm maintains a[lo]  value 
a[hi].

O Ex. Binary search for 33.

6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

start end
Binary Search
O Invariant. Algorithm maintains a[lo]  value 
a[hi].

O Ex. Binary search for 33.

6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

start mid end


Binary Search

O Invariant. Algorithm maintains a[lo]  value  a[hi].

O Ex. Binary search for 33.

6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

lo hi
Binary Search

O Ex. Binary search for 33.

6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

lo mid hi
Binary Search

O Ex. Binary search for 33.

6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

lo
hi
Binary Search

O Ex. Binary search for 33.

6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

lo
hi
mid
Binary Search
O Invariant. Algorithm maintains a[lo]  value  a[hi].

O Ex. Binary search for 33.

6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

lo
hi
mid
Binary Search example
#inlcude<iostream>
using namespace std;
int main(){
int , i , arr[50] , search, first , last , middle, loc;
Loc = -1; first= 0; last = 14;
int arr [15] =
{6,13,14,25,33,43,51,53,64,72,64,93,95,96,97};
cout<<“Enter a numer to find”<<endl;
cin>>search;
Binary Search example
while(first <= last){
middle = (first + last)/2;
if(arr[middle] == search) {
loc = mid;
break; }
else if(search<arr[middle])
last = mid-1;
else
first = mid+1; }
If (loc== -1)
cout<<search<<“not Found ”<<endl;
else cout<<search<<“Found at location”<<loc;
}
}
Passing Arrays to Functions
O We should mention the size of the array when
pass to the function
O Arrays are passed by reference
O int MyArray[5]

MyArray

54
Passing Array To Function
#include<conio>
#include<iostream>
void f(int[],int,int);
int main(){
int number[10]={0},a=15;
f(number,10,a);
for(int i=0;i<10;i++)
cout<<number[i];
cout<<a;
getch();
return 0; 55

}
Passing Array To Function
void f(int x[],int arraySize,int a){
a=100;
int i;
for(i=0;i<arraySize;i++)
x[i]=i;
}

56
Passing Individual elements of an Array
To Function (By Value)
#include<conio>
#include<iostream>
void check(int);
int main(){
int a[5]={5,4,6,7,9};
cout<<"Third element is::"<<a[2];
check(a[2]);
cout<<"\nThird element after call:"<<a[2];
getch();
return 0;
}
void check(int x){ 57
x=35;
O}
Two Dimensional Array

O int x [ 4 ] [4 ] ;

0 1 2 3
0

1
2
3
58
Two Dimensional Array

O int x [ 2 ] [ 3 ] ;

[0]
[ 0 ] [0 ] [ 0] [ 2 ]
[1]

[1]
[1 ] [2 ] [1] [2 ]
[0]
59
int main(){
const int row=2;
const int col=3;
int a[row][col];
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
cout<<"\
nCell["<<i<<"]"<<"["<<j<<"]=";
cin>>a[i][j];
}
60
}
for(int i=0;i<row;i++){
cout<<"\n\n\t\t";
for(int j=0;j<col;j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}

getch();
return 0;
} 61
62
Example

1 2 3 7 8 9

4 5 6 4 5 6

7 8 9 1 2 3

63

You might also like