Week2 - Array
Week2 - Array
1
Arrays in Data Structure
An array is a collection of more then one data items
or elements of same datatype in contiguous
memory (one after another) e.g. list of names, list of scores
Easier way to compare and use data than having
separate variables for data elements
data_type identifier[size]
int arr[3]
declares a one-dimensional array named arr with space
list[9]
Arrays
Arrays offer convenient means of grouping
together several related variables
One- dimensional arrays
type var_name[size]
int sample[10];
double d[30];
char ch[100];
Arrays in Data Structure
Examples:
double taxrate[3] = {0.15, 0.25, 0.3};
char word[] = “hello”;
char list[5] = {‘h’,’e’,’l’,’l’,’o’};
//list of characters, not a string
double vector[100] = {0.0}; //assigns zero to all 100 elements
Initializing Arrays
float f[5]={0.0, 1.0, 2.0, 3.0, 4.0};
// initializes f[0] to 0.0, f[1] to 1.0…f[4] to 4.0
Or
float f[5]; f[0]=0.0; f[1]=1.0; …
#include <iostream.h>
int main()
{
int t, sample[10]; // this reserves 10 integer
elements
return 0;
}
Initializing Arrays
int a[5];
Now an indexed variable like a[1] can be used anywhere that a variable of
type int can be used
int a[5];
cin >> a[4] >> a[2];
cout << a[2] << “ “ << a[4] << endl;
int student = 2;
a[student] = 99;
cout << a[student] << “ “ << a[2] << endl;
int main()
{
const int SIZE = 5;
int i, score[SIZE], max_score;
cout << “The highest score is: “ << max_score << endl
<< “Scores & their difference from highest: \n”;
• Total bytes =
number of bytes in type * number of elements
int size;
cin >> size;
int myarray[size];
// ...
a = b; // error -- illegal
/*So how do we make the contents of one array
same as the other?*/
Assigning One Array to
Another
int a[5], b[5];
// ...
a = b; // error – illegal
int main()
{
int b[ARRAY_SIZE];
return 0;
}
Assigning Values to an Array
•Example
int list[10];
int count;
return 1;
}
Two Dimensional Arrays
• C++ supports multi-dimensional array
– data_type array_name[ROW_SIZE][COLUMN_SIZE]
– int matrix[3][4];
row[0]
row[1]
row[2]
in memory
row1 row2 row3
Accessing Array Elements
• int matrix[3][4];
– matrix has 12 integer elements
– matrix[0][0] element in first row, first column
– matrix[2][3] element in last row, last column
Two Dimensional Arrays
int main()
{
const int ROWS = 3;
const int COLS = 4;
int i, j, num[ROWS][COLS];
int multidim[4][10][3];
entry
34 45 15 ---------- 36
0 1 2 ----------- 30
delete []ptr;
Array of Pointers
const int RSIZE = 4;
A two dimensional
const int CSIZE = 6; array of
int * iarray[RSIZE]; RSIZE*CSIZE