Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Arrays in ‘C’
ARRA
YS
Introducing Arrays
Declaring Array Variables, Creating
Arrays, and Initializing Arrays
Passing Arrays to Methods
Copying Arrays
Multidimensional Arrays
Search and Sorting Methods
2
INTRODUCING
ARRAYS
Array is a data structure that represents a collection of the
same types of data.
int num[10];
3
DECLARING ARRAY
VARIABLES
datatype arrayname[index];
Example:
int list[10];
char num[15];
float hat[20];
CREATING
ARRAYS
datatype array-name[size];
Example:
int num[10];
5
DECLARING AND CREATING
IN ONE STEP
datatype arrayname[arraySize]=
{values seperated by comma};
Example :
For example,
int arr[10];
You can not insert any number to arr[11]
location because it is not initialized.
7
INITIALIZING
ARRAYS
Declaring, creating, initializing in one step:
float hat[4] = {1.9, 2.9, 3.4, 3.5};
8
DECLARING, CREATING,
INITIALIZING USING
THE SHORTHAND
NOTATION
float list[4] = {1.9, 2.9, 3.4, 3.5};
9
CAUTIO
N
float list;
10
Example: Copying Arrays
The program simply creates two
arrays and attempts to copy one to the
other, using an assignment
statement.
11
COPYING
ARRAYS
Before the assignment After the assignment
list2 = list1; list2 = list1;
list1 list1
Contents Contents
of list1 of list1
12
COPYING
ARRAYS
With direct assignment:
array2 = array1;
13
MULTIDIMENSIONAL
ARRAYS
Declaring Variables of Multidimensional Arrays and
Creating Multidimensional Arrays
int matrix[10][10];
float mat[5][5]; 14
MULTIDIMENSIONAL ARRAY
ILLUSTRATION
0 1 2 3 4 0 1 2 3 4 0 1 2
0 0 0 1 2 3
4 5 6
1 1 1
2 2 7 2 7 8 9
10 11 12
3 3 3
4 4 int[][] array ={
{1, 2, 3},
int matrix[5][5]; matrix[2][1] = 7 {4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
15
You can also use a shorthand notation to declare, create and
SHORTHAND NOTATIONS
initialize a two-dimensional array. For example,
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
This is equivalent to the following statements:
array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
RAGGED
ARRAYS
Each row in a two-dimensional array is
itself an array. So, the rows can
have different lengths. Such an array
is known as a ragged array. For
example,
int[][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
17
17
EXERCISE :
BUBBLE SORT
int i[] = {2, 9, 5, 4, 8, 1, 6}; //
Unsorted
Pass 1: 2, 5, 4, 8, 1, 6, 9
Pass 2: 2, 4, 5, 1, 6, 8, 9
Pass 3: 2, 4, 1, 5, 6, 8, 9
Pass 4: 2, 1, 4, 5, 6, 8, 9
Pass 5: 1, 2, 4, 5, 6, 8, 9
Pass 6: 1, 2, 4, 5, 6, 8, 9
18