Uploaded by Soumya Mishra

Array complete

advertisement
Arrays
(Unit -1)
@LPU CSE202 C++ Programming
Outline
• To declare an array
• To initialize an array
• Operations on array
@LPU CSE202 C++ Programming
• Arrays
Introduction
– Collection of related data items of same data
type.
– Static entity – i.e. they remain the same size
throughout program execution
@LPU CSE202 C++ Programming
Why do we need arrays?
We can use normal variables (v1, v2, v3, ..) when we have a small number
of objects, but if we want to store a large number of instances, it becomes
difficult to manage them with normal variables. The idea of an array is to
represent many instances in one variable.
Where we use array????
• Implement data structure: Arrays can be used to
implement stack and queue data structures.
• Various mathematical problems like matrices can be easily
and efficiently solved with the help of an array data structure.
• Multimedia Applications: Arrays are used in multimedia
applications such as video and audio processing, where they
are used to store the pixel or audio samples. For example, an
array can be used to store the RGB values of an image.
• Data Mining: Arrays are used in data mining applications to
represent large datasets. This allows for efficient data access
and processing, which is important in real-time applications.
• Robotics: Arrays are used in robotics to represent the position
and orientation of objects in 3D space. This can be used in
applications such as motion planning and object recognition.
1D-Array
The entire array
has a single name
Each value has a numeric index
c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9]
c
79 87 94 82 67 98 87 81 74 91
An array of size N is indexed from zero to N-1
This array holds 10 values that are indexed from 0 to 9
How to calculate memory address of array=
Address=base address+[index*sizeofdatatype]
Eg=100+[5*2]
@LPU CSE202 C++ Programming
Declaring and Defining Arrays
• When defining arrays, specify:
– Name
– Data Type of array
– Number of elements
datatype arrayName[numberOfElements];
– Examples:
int rollno[10];
char name[50];
• Defining multiple arrays of same data type
– Format is similar to regular variables
– Example:
int b[100], x[27];
@LPU CSE202 C++ Programming
Initializing an Arrays
•
•


•
You can initialize an array at run time and compile time.
At compile time:
int n[5] = { 1, 2, 3, 4, 5 };
At run time:
Array is same as the variable can prompt for value from the user at run
time.
Array is a group of elements so we use for loop to get the values of
every element instead of getting single value at a time.
Example: int array[5]; // array of size 5
for(int i=0;i<5;i++)
{// loop begins from 0 to 4
cin>>&array[i];
}
@LPU CSE202 C++ Programming
Accessing the array element
In C++, each element in an array is associated
with a number. The number is known as an
array index. We can access elements of an
array by using those indices.
// syntax to access array elements
array[index];
Few Things to Remember:
• The array indices start with 0. Meaning x[0] is the first
element stored at index 0.
• If the size of an array is n, the last element is stored at
index (n-1). In this example, x[5] is the last element.
• Elements of an array have consecutive addresses. For
example, suppose the starting address of x[0] is 2120.
Then, the address of the next element x[1] will be 2124, the
address of x[2] will be 2128, and so on.
Program
//Demonstration of 1D array
• #include <iostream>
• using namespace std;
• int main()
• {
•
int numbers[5];
•
cout << "Enter 5 numbers: " << endl;
•
// store input from user to array
•
for (int i = 0; i < 5; i++)
•
{
•
cin >> numbers[i];
• }
• cout << "The numbers are: ";
• for (int i = 0; i < 5; i++) // print 1D array elements
{
•
cout <<"numbers ["<<i<<" ]"<< numbers[i]<< endl;
•
}
• }
2D Array
Examples of 2D array declaration
Initializing 2D Array at Compile time:
Inputting values into 2D at Run time
Example
Program on 2D Array
•
•
•
•
// C++ Program to display all elements
// of an initialised two dimensional array
#include<iostream>
using namespace std;
•
•
•
•
•
int main() {
int test[3][2] = {{2, -5},{4, 0},{9, 1}};
// use of nested for loop
// access rows of the array
for (int i = 0; i < 3; ++i) {
•
•
•
•
// access columns of the array
for (int j = 0; j < 2; ++j)
{
cout <<"Test ["<<i<<" ][" <<j <<"]"<< test[i][j] ;
cout<<endl;
}
}
return 0;
•
•
•
Problem :Addition of two matrix using C++
Basics of Matrix:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
// Program to add two matrix using 2D Array
#include<iostream>
using namespace std;
int main()
{
int A[3][2],B[3][2],C[3][2];
cout<<" Enter first matrix :"<<endl;
for(int i=0;i<3;i++)
{ for(int j =0;j<2;j++)
{
cin>>A[i][j];
}
}
cout<<" Enter second matrix :"<<endl;
for(int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
{
cin>>B[i][j];
}
}
Program to
add Two
matrix
cout<<" Addition of two matrix is
:"<<endl;
for(int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
{
C[i][j]=A[i][j] + B[i][j];
cout<<C[i][j]<<" ";
}
cout<<endl;
}
}
Operations on arrays
•
•
•
•
Traverse an array element.
Insertion of element into an array
Deletion of element from an array
Search of element in an array.
@LPU CSE202 C++ Programming
Traversing
• To traverse an array means to access each
element (item) stored in the array so that the
data can be checked or used as part of a
process.
• Algorithm:
• Start a loop from 0 to N-1, where N is the size
of array. for(i = 0; i < N; i++)
• Access every element of array with help of
arr[index]
• Print the elements.
Code for traversing
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
#include <iostream>
using namespace std;
int main()
{
int numbers[5];
cout << "Enter 5 numbers: " << endl;
// store input from user to array
for (int i = 0; i < 5; i++)
{
cin >> numbers[i];
}
cout << "The numbers are: ";
for (int i = 0; i < 5; i++) // print 1D array elements
{
cout <<"numbers ["<<i<<" ]"<< numbers[i]<< endl;
}
}
• Insert an array element
Approach:
how to do it?
First get the element to be inserted, say x
Then get the position at which this element is to be inserted, say pos
Then shift the array elements from this position to one position forward, and do
this for all the other elements next to pos.
Insert the element x now at the position pos, as this is now empty.
@LPU CSE202 C++ Programming
Algorithm for insertion
• Inserting into a Linear array at given possition.
INSERT(LA,N,K,ITEM):
Here LA is a Linear Array with N elements and K is a positive
integer such that K<=N. This algorithm inserts an element
ITEM into the Kth position in LA.
 [Initialize counter.] Set i:=N.
 Repeat Steps 3 and 4 while i>=K.
 [Move ith element downward.] Set LA[i+1]:= LA[i].
 [Decrease counter.] Set i:= i-1. [End of Step 2 loop.]
 [Insert element.] Set LA[K]:=ITEM.
 [Reset N.] Set N:N+1.
 Exit.
#include<iostream>
Using namespace std;
int main()
{
int LA[100], i , n , k, item;
cout<<"how many no to store in array";
cin>>n;
cout<<"Enter the number";
for(i=0;i<=n-1;i++)
cin>>LA[i];
cout<<"Enter the no. and its position";
cin>>item;
cout<<endl;
cin>>k;
k=k-1;
for(i=n-1;i>=k;i--)
{
LA[i+1]=LA[i];
}
LA[k]=item;
//print the resultant array after insertion
cout<<"Contents of the array\n";
for(i=0;i<=n;i++)
{
cout<<LA[i];
}
}
• Program to
insert an
element
into an
array
Delete an array element
Deletion Operation
In this array operation, we
delete an element from the
particular index of an array.
This deletion operation
takes place as we assign
the value in the
consequent index to the
current index.
Algorithm
• Consider LA is a linear array with N elements and k is a positive integer
such that k<=n. Following is the algorithm to delete an element available
at the kth position of LA.
• 1. Start
• 2. Set i = k
• 3. Repeat steps 4 and 5 while i < n
• 4. Set LA[i] = LA[i+ 1]
• 5. Set i = i+1
• 6. Set n = n-1
• 7. Stop
#include<iostream>
Using namespace std;
int main()
{
int a[100],i,n,k;
cout<<"how many no to store in array"<<endl;
cin>>n;
cout<<"enter the number"<<endl;
for(i=0;i<n;i++)
cin>>a[i];
cout<<"enter the position";
cin>>k;
for(i=k-1;i<n;i++)
{
a[i]=a[i+1];
}
cout<<"contents of the array"<<endl;
for(i=0;i<n-1;i++)
{
cout<<a[i];
}
@LPU CSE202 C++ Programming
• Program to
delete an
element
from an
array
How many no to store in array: 4
Enter the number: 12
14
5
11
Enter the position: 3
Content of the array
12
14
11
@LPU CSE202 C++ Programming
Output
Search an array element
Examples:
Input: arr[] = {10, 20, 30, 50, 60,
80, 110, 130, 140, 170}, x = 110
Output: 6
Explanation: Element x is
present at index 6.
Input: arr[] = {10, 20, 30, 40, 60,
110, 120, 130, 170}, x = 175
Output: -1
Explanation: Element x is not
present in arr[].
Searching in Arrays
• The process of finding a particular element of
an array is called searching.
• Search an array for a key value.
• Two searching techniques:
– Linear search
– Binary search
@LPU CSE202 C++ Programming
Linear search
• Linear search
– Simple
– Compare each element of array with
key value
– Useful for small and unsorted arrays
• It simply examines each element
sequentially, starting with the first
element, until it finds the key element
or it reaches the end of the array.
Example: If you were looking for
someone on a moving passenger train,
you would use a sequential search.
@LPU CSE202 C++ Programming
Linear search algorithm
•
•
•
•
•
•
Step 1: start
2. Read an array(a) with n element
3. SET i=0;
4. Input searching element
5. Repeat step 6 & 7 while i<n
6. if a[i]=item then
print item found & location =i & exit
7. i= i+1
8. if i>=n then print item not found &exit
9. end.
#include<iostream.h>
#include<conio.h>
int main()
{
int a[20],key,i,n, c=0;
cout<<“Enter the number of elements:\t";
cin>>n;
cout<<"Enter the elements:\t";
for(i=0;i<n;i++)
cin>>a[i];
cout<<"Enter the element to be found \t";
cin>>key;
for(i=0;i<n;i++)
if(a[i]==key)
//comparison
{
cout<<“Key found at location \t"<<i;
c++;
break;
}
if (c==0)
cout<<"element not found in the list";
getch();
return 0;
}
@LPU CSE202 C++ Programming
• Program of
linear
search in an
array.
Enter the number of elements: 4
Enter the element: 12
14
5
11
Enter a number to be found: 14
Key found at location 2
@LPU CSE202 C++ Programming
Output
Binary search
• Binary search :
 It is the divide and conquer searching technique in which we have
to divide our array into two half and then apply searching
operation
 Applicable for sorted arrays
• The algorithm locates the middle element of the array and
compares it to the key value.
– Compares middle element with the key
• If equal, match found
• If key < middle, looks in left half of middle
• If key > middle, looks in right half of middle
• Repeat (the algorithm is repeated on one-quarter of the
original array.)
@LPU CSE202 C++ Programming
Algorithm
• Binarysearch( A, N,item,beg,end)
Here A is an array of n sorted elements . Item is a positive integer to be
searched , beg and end is the lower and higher index respectively.
Step 1.Set beg=0, end=1
Step 2.Repeat step 3 and 4 while (beg<=end)
Step 3.Set Mid=beg+end/2
Step 4.if (item==A[mid]
print item is found and go to step 6
elseif(item>A[mid])
Set beg =mid +1;
else
Set end =mid-1
[end if]
[end loop]
Step 5. if (beg>=end)
item not found.
Step 6. exit.
#include<iostream.h>
#include<conio.h>
int main()
{
int ar[100],beg,mid,end,i,n,search;
cout<<"How many numbers in the array: ";
cin>>n;
cout<<"Enter "<<n<<" numbers in ascending order --> ";
for(i=0;i<n;i++)
cin>>ar[i];
beg=0;end=n-1;
cout<<"Enter a number to search: ";
cin>>search;
while(beg<=end)
{
mid=(beg+end)/2;
if(ar[mid]==search)
cout<<"\nItem found at position"<<(mid+1);
break;
if(search>ar[mid])
beg=mid+1;
else
end=mid-1;
}
if(beg>=end)
cout<<"\nSorry! "<<search<<" doesnot found.";
}
@LPU CSE202 C++ Programming
• Program of
binary
search in an
array.
How many numbers in the array: 4
Enter 4 numbers in ascending order12
14
26
47
Enter a number to search:26
Item found at position 3
@LPU CSE202 C++ Programming
Output
Sorting Algorithm
• A Sorting Algorithm is used to rearrange a given array or list
of elements according to a comparison operator on the
elements.
• The comparison operator is used to decide the new order of
elements in the respective data structure.
Why sort ??????????
• One of the main advantages of sorting algorithms is that they
can help to organize and analyze data in a more efficient and
meaningful way. For example, sorting a large dataset can
make it easier to search for specific elements or to identify
patterns and trends.
Bubble sort
• Bubble Sort is the simplest of the sorting techniques.
• In the bubble sort technique, each of the elements in the list
is compared to its adjacent element. Thus if there are n
elements in list A, then A[0] is compared to A[1], A[1] is
compared to A[2] and so on.
• After comparing if the first element is greater than the
second, the two elements are swapped then.
How does bubble sort works?
• It is the simplest sort method which performs sorting by
repeatedly moving the largest element to the highest index of
the array. It comprises of comparing each element to its
adjacent element and replace them accordingly.
• Bubble sort works on the repeatedly swapping of adjacent
elements until they are not in the intended order.
• It is called bubble sort because the movement of array
elements is just like the movement of air bubbles in the
water. Bubbles in water rise up to the surface; similarly, the
array elements in bubble sort move to the end in each
iteration.
Algorithm:
• Bubble sort(n, arr)
Here n is number of array elements and arr is array name
• Step 1. initialize i = 0
• Step 2. repeat step 3 to step 5 while (i<n-1)
• Step3 j=0
• Step 4 repeat through step 5 while (j<n-i-1)
• Step 5 if arr[j]>arr[j+1]
•
temp = arr[j+1]
•
arr[j+1] = arr[j]
•
arr[j] = temp
• Step 6 exit.
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
#include<iostream>
using namespace std;
int main()
{
int n, i, arr[50]={12,14,17,20,30,35,40},
j, temp;
cout<<"\nSorting the Array using Bubble
Sort Technique..\n";
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
Implementation in
C++
cout<<"\nArray Sorted Successfully!\n";
cout<<"\nThe New Array is: \n";
for(i=0; i<n; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
Optimization of bubble sort
• In optimized bubble sort, we have a flag
variable that keeps track of whether the list is
completely sorted or not.
• In optimized bubble sort, whenever there is a
swapping in any iteration, it means that the
array/list is still not sorted & hence the flag is
set to FALSE.
• Whenever there is no swapping in a particular
iteration, the flag is set to TRUE
Next Class: Time complexity
and Asymptotic notation
@LPU CSE202 C++ Programming
Download