Você está na página 1de 37

A R R AY S &

STRINGS

Arrays
Definition:

An array is a group of related data items that share


a

common name.
The array elements are placed in a contiguous memory

locations.
A particular value in an array is indicated by writing an
integer number called index number or subscript in a
square brackets after the array name.
The least value that an index can take in array is 0..

Arrays
For example
We define an array named salary to represent a set
of salaries of a group of employees.
Now the values or the salaries of employees
can be stored as follows.
salary[0]=10000, salary[1]=15000,
salary[2]=20000, salary[4]=10000,..etc.
where salary[0], salary[1], salary[2] etc. respectively
represent the salaries of first, second, third employee.

7/13/2012

Department of CSE

Arrays
If an array salary contains 5 integer values
(salaries) of employees then it is represented as
follows.

The elements are numbered from 0 to 4 since in


arrays the first index is always 0, independent of its
length.
7/13/2012

Department of CSE

Arrays
ArrayDeclaration:

type name [size];


wheretype isavaliddatatype(likeint,float...)
name isavalididentifier&
sizespecifieshowmanyelementsthearrayhastocontain.
sizefield isalwaysenclosedinsquarebrackets[]andtakes
staticvalues.

Forexample
anarraysalary containing5elementsisdeclaredas
follows

int salary [5];


7/13/2012

Department of CSE

Arrays
One Dimensional Array
A linear list of fixed number of data items of same
type.
These items are accessed using the same name using
a single subscript. E.g. salary [1], salary [4]
A list of items can be given one variable name
using only one subscript and such a variable is
called a single-subscripted variable or a onedimensional array.

7/13/2012

Department of CSE

Arrays IDimensional
Rules for subscript:
A subscript can be integer constants, Integer variables like i,
or expressions that yield integers.

Subscript of subscript is not allowed.

The Maximum subscript value appearing in a program for


a subscripted variable should not exceed the declared one.
The subscript value ranges from 0 to one less than the
maximum size. For example, If the array size is 5 , then
the first subscript is 0, the second is 1 and so on the last
subscript is 4. In general ith element has subscript (i-1).
7/13/2012

Department of CSE

Arrays 1D
Totalsize:
TheTotalmemorythatcanbeallocatedto1Darrayis
computedas
Total size =size *(sizeof(data_type));
wheresize numberofelementsin1Darray
data_type basicdatatype.
sizeof() is an unary operator which returns the size
of expression or data type in bytes.

Forexample,ifwewanttorepresentasetof5
numbersbyanarrayvariablen,thenwemay
declarethevariablen asint n[5];
7/13/2012

Department of CSE

Arrays 1D
If the values of array n are 32, 27,64,18,95 then
these values are stored in n as follows.
32

27

64

n[0] n[1]

18

95

n[2] n[3] n[4]

& n[0]
n
7/13/2012

Department of CSE

Arrays 1D
int n[5];

n[0] = 32;

32

n[4] = 95;

32

95

n[5] = 100;

32

95

100

Logically Not correct ! Out of range


7/13/2012

Department of CSE

10

Initializingonedimensionalarray
At compile time
At run time [during program execution]
for (i=0; i<100; i++)
{
if (i < 50)
n[i] = 0;
else
n[i] = 1;
}
7/13/2012

Department of CSE

11

Initializing one-dimensional array


(compile time)
type arrayname [size]={list of values}
type basic data type
arrayname name of the array.
size maximum number of elements and may be omitted.
List of values values separated by commas.

E.g. int number[3] ={ 0,0,0} or {0}


will declare the variable number as an array of size 3
and will assign 0 to each element.
7/13/2012

Department of CSE

12

Arrays 1Dimensional
If the number of values in the list is less than
the number of elements, then only that many
elements will be initialized.
The statement
int age[ ] ={16, 25, 32, 48, 52, 65};
declares the age array to contain 6 elements
with initial values 16, 25, 32, 48,52, 65
respectively.

7/13/2012

Department of CSE

13

Arrays 1D
For example
int x[3] = {9,11,13};
cout << x[0] << endl;
cout << x[1] << endl;
cout << x[2] << endl;

Output:
9
11
13

int x[3] = {9,11,13};


for (int i = 0; i<3; i++)
cout << x[i] << endl;
7/13/2012

Department of CSE

14

Initializealltheelementsofan
integerarrayvaluestozero
int values[20];

Begin for loop


Initialize counter
Set limit for counter

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

Increment counter

values[i]=0;

Initialize element in array


values
7/13/2012

Department of CSE

15

Initializinganarraytothedaysof
eachmonthanddisplaysthosedays
const int NUM = 12;
int Days[NUM]={31,28,31,30,
31,30,31,31,
30,31,30,31 };
for (int i=0; i < NUM; i++)
{
cout << \nMonth << (i + 1)
<<<<Days[i]<<days;
}
7/13/2012

Department of CSE

16

Programtoreadnelementsintoan
arrayandprintit
cout<<"enter no of numbers";
cin>>n;
cout<<"\nenter n numbers\n";

Output:

for(i=0;i<n;i++)
cin>>a[i];
cout<<\nNumbers entered are:\n;
for(i=0;i<n;i++)
cout<<a[i]<<endl;

7/13/2012

Department of CSE

enter no of numbers
3
Numbers entered are:
9
11
13

17

Programtoaddtwoarrayelementsand
storethecorrespondingelementssumin
anotherarray
cout<<"enter no of no for the
first array\n";
cin>>n; \\first array
for(i=0;i<n;i++)
cin>>a[i];
cout<<"enter no of numbers for
the second array\n";
cin>>m; \\second array
for(i=0;i<m;i++)
cin>>b[i];
7/13/2012

if(m==n)
{
for(i=0;i<m;i++)
c[i]=a[i]+b[i];
for(i=0;i<n;i++)
cout<<c[i]<<endl;
}

else
cout<<"cannot add";
getch();
}

Department of CSE

18

Displayingelementsofanarrayin
reverseorder.
cout<<Enter values\n";
for(i=0;i<n;i++)
cin>>a[i];
cout<<\nReverse order printing of array\n;
for(j=i-1;j>=0;--j)// reverse loop
cout<<a[j]<<"\t;

7/13/2012

Department of CSE

Example:a[]={1,2,3,4,5}
Enter values
n=5
12345
Reverseprintingofarray
54321
Arraybefore
Arrayafter
a[0]=1
a[0]=1
a[1]=2
a[1]=2
a[2]=3
a[2]=3
a[3]=4
a[3]=4
a[4]=5
a[4]=5

19

Writeaprogramtoreverseanarray
usingonlyonearray
int a[20],i,j,n, temp;
cout<<"enter n \n";
cin>>n;
cout<<"\n Enter values for an array";
for(i=0;i<n;i++)
cin>>a[i];

7/13/2012

Department of CSE

Example:a[]={1,2,3,4,5}
Enter values
n=5
12345
Reversedarray
54321
Array
Reversedarray
a[0]=1
a[0]=5
a[1]=2
a[1]=4
a[2]=3
a[2]=3
a[3]=4
a[3]=2
a[4]=5
a[4]=1

20

Reversinganarray
Example:
a[]={1,2,3,4,5}

j=n;
for(i=0;i<n/2; i++,j--)}
temp=a[i];
a[i]=a[i]+a[n-1-i];
a[i]=a[j-1];
OR a[n-1-i]=a[i]-a[n-1-i];
a[j-1]=temp;
a[i]=a[i]-a[n-1-i];
}
cout<<"\n Reversed array\n";
Output:
for(i=0;i<n;i++)
Enter values for an array
n=5
cout<<a[i]<<"\t";
12345
}
Reversedarray
54321
7/13/2012

Department of CSE

21

WAPtoinsertanelementtoanarray
atgivenposition
Example:insert9at2 position
nd

a[]={1,2,3,4,5}
cin>>n; // number of elements
cout<<"\nEnter the elements of array:";
for(i=0;i<n;i++)
Newarrayafterinserting9 :
a[]={1,2,9,3,4,5}
cin>>a[i];
cout<<"\nEnter the element and position of insertion:";
cin>>ele>>pos;
for(i=n;i>=pos;i--)
a[i]=a[i-1];
a[pos-1] = ele; //ele is inserted at the specified pos.
cout<<"\nThe array after insertion is:";
for(i=0;i<=n; i++)
cout<<a[i]<<"\n;
7/13/2012

Department of CSE

22

WAPtodeleteanelementfroman
array
Example:deleteele at2 position
nd

a[]={1,2,3,4,5}
cout<<"enter no of numbers";
cin>>n;
Newarrayafterdeleting3:
cout<<"enter n numbers \n";
a[]={1,2,4,5}
for(i=0;i<n;i++)
cin>>a[i];
cout<<"enter the position at which the ele to be deleted";
cin>>pos;
for(i=pos; i<n; i++)
a[i] =a[i+1];

for(i=0;i<n-1;i++)
cout<<a[i]<<endl;
7/13/2012

Department of CSE

23

Overview
1DArray:

Syntax:type array_name[size];

MemoryRequirement:
Total size =size *(sizeof(data_type));

Initialization:
typearrayname[size]={list of values}

WriteandRead:
for(i=0;i<n;i++)
cin>>a[i];

7/13/2012

for(i=0;i<n;i++)
cout<<a[i];

Department of CSE

24

Searching&Sorting
SearchingTechniques
LinearSearch
BinarySearch

SortingTechniques
BubbleSort
SelectionSort

7/13/2012

Department of CSE

25

Linearsearch

7/13/2012

Department of CSE

26

Linearsearch Example-2

7/13/2012

Department of CSE

27

Linear search- Example-2

7/13/2012

Department of CSE

28

WAPtosearchanelementinan
array
int found=0;
cout<<"enter no of numbers";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"enter number\n";
cin>>a[i];
}
cout<<"enter the element to be
searched";
cin>>key;
7/13/2012

for(i=0; i<n; i++){


if(a[i]==key)
{found=1;
pos=i+1;
break;
}
}
if(found==1)
cout<<"ele found in "<<pos
<<"position"<<endl;
else
cout<<"no is not found;

Department of CSE

29

BubbleSortAlgorithm

7/13/2012

Department of CSE

30

BubbleSort Example

7/13/2012

Department of CSE

31

BubbleSort Example

7/13/2012

Department of CSE

32

BubbleSortprocedure
for(i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
7/13/2012

Example:
a[]={16,12,11,67}
Arrayaftersorting(ascending)
a[]={11,12,16,67}

Department of CSE

33

Tobesolved
WAP to
Insert an element into a sorted array (new array

should be sorted one; find the pos in the sorted


array and insert there).

Delete an element from an array (element


should be read; search it and delete it.)

7/13/2012

Department of CSE

34

Insertanelementintoasorted
array
Readarrayelements&elementeletoinsert
//finding position

for(i=0; i < n; i++)


if (ele>=a[i] && ele<=a[i+1]) Example:insert3intoitsposition
a[]={1,2,4,5,6}
pos = i+1;
else if ( ele>a[i] )
Newarrayafterinserting3:
pos = n;
a[]={1,2,3,4,5,6}
//reposition elements after pos &
//insert ele to pos
7/13/2012

Department of CSE

35

Tobesolved
WAP to
Find the even & odd numbers stored in a given integer array
num. Display the original array num. Replace the even number
with its square and odd number with its cube in the same
array num. Display the new array num.[HINT: 2 replaced with
4 & 3 replaced with 27]
Read two 1D arrays A & B. Merge A & B and store it in C. Array C
has to be sorted [use bubble sort] and displayed.
Now repeat the Merge process done for A & B (Q.2) by carrying
out the sort process (any sorting) while storing it in array A.
[HINT: Read each element from array B and insert in
appropriate (sorted) position in array A]
7/13/2012

Department of CSE

36

Summary

Arrays
1Dimensionalarrays(lists)
Problemson1Darrays
Searching
Sorting

7/13/2012

Department of CSE

37

Você também pode gostar