Arrays
Arrays
Arrays
● An array is a collection of similar data objects (homogeneous data items) or
collection of similar entity stored in contiguous memory location. E.g. A collection
of characters is a string array.
● An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
● Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables.
● Each data item of an array is called an element. A specific element in an array is
accessed by an index.
Characteristics of an Array
An array has the following characteristics;
● Array initialization at compile time means initializing the array’s elements with
known values at the time of writing the code, rather than during runtime.
○ int arr1[5] = {1, 2, 3, 4, 5}; // Initializing an array of integers
○ float arr2[] = {1.1, 2.2, 3.3, 4.4, 5.5}; // Initializing an array of floats
Run Time Initialization
● Runtime initialization refers to initializing an array during the execution of the
program, as opposed to at compile time. This typically involves assigning values to
the array elements using variables or expressions whose values are determined
during runtime. Here's an example in C:
Accessing Values of an Array
You can access elements of an array by indices.
● Suppose you declared an array int mark[5] .
● The first element is mark[0], the second element is mark[1] and so on.
Keynotes:
● Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
● If the size of an array is n, to access the last element, the n-1 index is used. In this example, mark[4]
● Suppose the starting address of mark[0] is 2120d. Then, the address of the mark[1] will be 2124d.
Similarly, the address of mark[2] will be 2128d and so on.
● This is because the size of a float is 4 bytes.
Change Value of Array elements
● Suppose we declare an array as follows: int mark[5] = {19,
10, 8, 17, 9}
● Make the value of the third element to -1
○ mark[2] = -1;
● make the value of the fifth element to 0
○ mark[4] = 0;
Example 1: Array Input/Output
Here, we have used a for loop to
take 5 inputs from the user and
store them in an array. Then, using
another for loop, these elements are
displayed on the screen.
Example 2: Calculate Average
● Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can
think the array as a table with 3 rows and each row has 4 columns.
C Multidimensional Arrays