Array Teach
Array Teach
Array Teach
Unit 3:
Array
1
Suppose you have a long list of numbers, but you don’t want
to assign them to variables individually.
For example, you are writing a simple program for a restaurant
to keep a list of the amount each diner has, but you don’t want
to write a list like:
int my_array[3];
my_array[0] = 5;
my_array[1] =
17;
my_array[2] =
23;
In this example, 5, 17, and 23 are the array’s elements, and 0, 1, and 2 are
its corresponding indices.
The above example would result in an array like:
Index:
my_array:
Note that every element in an array must be of the same type, for
example, integer. It is not possible in C to have arrays that contain multiple
Array bounds
The code below defines an array with 9 elements (C arrays are zero-
based.) : char my_array[9];
The first and last positions in an array are called its bounds.
Remember that the bounds of an array are zero and the integer that
equals the number of elements it contains, minus one.
In C’s, the compiler does not complain if you try to write to elements of
an array that do not exist(i.e. if you exceed the bounds of an array), the
debugger can tell you at run-time.
Initializing Arrays
You can initialize an array in C either one by one or using a
single statement as follows −
The above statement assigns the 5th element in the array with a
value of 50.0. All arrays have 0 as the index of their first
element which is also called the base index and the last index
of an array will be total size of the array minus 1.
We can initialize each element of the array one by one using the
index.
Consider the following example.
int marks[5];
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Example
Example: Sorting an Array
Arrays and for loops
When you declare an array, the computer allocates a block of
memory for it, but the allocated block contains garbage
(random values).
So, before using an array, you should initialise it. The
easiest way to initialise an array is with a for loop.
It is usually a good idea to set all elements in the array to
zero.
my_array[index] = 0;
Output: my_array[0] = 0
my_array[1] = 0
my_array[2] = 0
my_array[3] = 0
my_array[4] = 0
Multidimensional arrays
These are Arrays with more than one dimension.
Suppose that you are writing a chess-playing program. A chessboard
is an 8-by-8 grid. What data structure would you use to represent it?
You could use an array that has a chessboard-like structure, that is, a
two-dimensional array, to store the positions of the chess pieces.
You can declare an array of two dimensions as follows:
variable_type array_name[size1][size2]
Example: int chessboard[8][8];
Where type can be any valid C data type and arrayName will
be a valid C identifier.
A two-dimensional array can be considered as a table which
will have x number of rows and y number of columns. A two-
dimensional array a, which contains three rows and four
columns can be shown as follows −