6_Arrays
6_Arrays
2
What is an Array?
Scalar data types use a single memory cell to store a single value.
For many problems you need to group data items together.
A program that processes exam scores for a class, for example, would be
easier to write if all the scores were stored in one area of memory and
were able to be accessed as a group.
C allows a programmer to group such related data items together into a
single composite data structure.
We now take a look at one such data structure: the Array.
An array is a collection of two or more adjacent memory cells that:
Store the same type of data values (e.g. int)
Are referenced by the same name (i.e using one variable)
These individual cells are called array elements
3
Introduction to 1-D Arrays
To declare an array, we must declare its name, type of data values it
will store and the number of cells associated with it. Example:
double x[8];
This instructs C to associate eight memory cells with the name x; these
memory cells will be adjacent to each other in memory.
You can declare arrays along with regular variables
double cactus[5], pins[7];
It is essential that we understand the distinction between an array
subscript value and an array element value.
int x[2]; int y = 1; x[y] = 5;
It is a good practice to define the array size as constant:
#define ARRAY_SIZE 12 4
int myArray[ARRAY_SIZE];
Declaring Arrays
Each element of the array x may contain a single value of type double,
so a total of eight such numbers may be stored and referenced using the
array name x.
The elements are numbered starting with 0
An array with 8 elements has elements at positions 0,1,2,3,4,5,6, and 7
The subscripted variable x[0] (read as x sub zero) refers to the initial or
0th element of the array x, x[1] is the next element in the array, and so
on.
The integer enclosed in brackets is the array subscript or index and its
value must be in the range from zero to one less than the array size.
5
Visual representation of an Array
int x[8]; x[2] =
20;
Memory Array
Address 342901 ? 0 Index/Subscrip
es 342905 ? 1 t
342909 20 2
342913 ? 3 Array Element
342917 ? 4
342921 ? 5
342925 ? 6
342929 ? 7
7
Array Initialization …
If there are values in the initialization block, but not enough to fill the
array, all the elements in the array without values are initialized to 0
in the case of double or int, and NULL in the case of char.
int scores[20]={0}; // all 20 elements are initialized to
0
int scores[20]={1, 2, 3}; // First 3 elements are
initialized to 1,2,3, and the rest are initialized to 0
If there are values in the initialization block, an explicit size for the
array does not need to be specified. Only an empty array element is
sufficient, C will count the size of the array for you.
int scores[]={20, 10, 25, 30, 40}; // size of the array
score is automatically calculated as 5
8
Accessing Array elements
You can access elements of an array using their indices.
The index represents the position of an element within the array,
starting from 0 for the first element. Here's how you can access
elements of an array in C
10
Accessing Array elements
Using while structure:
11
Example 1:
The following program allows the user to input five grades and stores
them in an array called grades. It then displays the grades along with
their respective indices using for loops
12
Example 2:
The following program reads data into two arrays and subtracts their
corresponding elements:
13
Example 3a (using for loop):
The following program computes the square roots of all elements in an
array :
14
Example 3b (using while loop):
The following program computes the square roots of all elements in an
array :
15
Example 4
The following program uses a function to count even and odd numbers
from an integer array:
16
Example 4 (Explanation):
int is_even(int n);: This is a function prototype for the function is_even. It declares that is_even is a
function that takes an integer n as an argument and returns an integer.
int a[SIZE]; This declares an integer array a with a size of SIZE.
int i, evens = 0, odds = 0; Here, we declare three integer variables i, evens, and odds. i will be used
as a loop counter, and evens and odds will be used to store the count of even and odd numbers in the
array, respectively. Both evens and odds are initialized to 0.
for (i = 0; i < SIZE; ++i) This is a for loop that runs from i = 0 to i = SIZE - 1, i.e., it iterates over the
elements of the array.
scanf("%d", &a[i]); This line reads an integer input from the user and stores it in the i-th element of
the array a.
int is_even(int n) { ... } This is the definition of the is_even function. It takes an integer n as input and
returns an integer (1 if n is even, 0 if n is odd).
if (n % 2 == 0) return 1; else return 0; In this function, it checks whether the input n is even or odd.
If n % 2 == 0, it returns 1 (indicating it is even), otherwise, it returns 0 (indicating it is odd).
Inside the main function, the program counts the number of even and odd elements in the array a using
a for loop.
if (is_even(a[i])) evens++; else odds++;: For each element of the array a, the is_even function is
17
called to check if the element is even or odd. Depending on the result, either evens or odds is
incremented.
After counting, the program prints the number of even and odd elements using printf.
Example 5:
The following program searches for an element in an array:
18
Example 5 (Explanation):
In the previous program, we declare a 1D array arr of size SIZE to
store the integers entered by the user. We also declare variables
searchElement, i, count, and foundIndex.
The program first reads SIZE integers from the user and stores
them in the array arr. Then, it prompts the user to enter the
element to be searched (searchElement).
The for loop iterates through the array, comparing each element
with the searchElement. If it finds a match, it increments the count
and updates the foundIndex variable to store the first occurrence of
the element.
Finally, the program prints the position of the element (if found)
and the count of occurrences of the element in 19 the array. If the
element is not found, it will print a message indicating that.
Example 6
The following program converts the elements appearing in the odd
positions int zeros:
20
Example 6 (Explanation):
In the previous program, we use a while loop to traverse the
elements of the 1D array.
The user is prompted to enter the elements of the array, and then
the original array is displayed.
After that, the elements that appear on odd positions (i.e.,
elements with odd indices) are converted to zeros.
Finally, the modified array with odd-position elements converted to
zeros is displayed..
21
Example 7:
The following program computes the average of odd numbers and
the average of even numbers stored in a 1D array.
22
Example 7 (Explanation):
In the previous program, we use a for loop to traverse the elements
of the 1D array.
The user is prompted to enter the elements of the array, and then
we compute the sum and count of odd and even numbers
separately.
Finally, we calculate the average of odd and even numbers and
display the results. Note that the average is computed as a
floating-point value to preserve fractional parts of the result.
23
Using arrays as function arguments (How to pass array to a function)
24
Using arrays as function arguments
The function needs to know the size of the actual array in order to process it
correctly. The solution is to add an extra parameter indicating the size or
actual number of elements in the array.
You can write the array with or without the size inside the square bracket.
void fun(int size, double array[]);
Or
void fun(int size, double array[size]);
The order in the first syntax is not necessary. But the the second one is
important.
Since functions that take array usually also need to know the size of the array
or at least the number of elements in the array, the complete call to the
print_array function might be:
25
fun(size, array);
Array as Actual Argument in Function Call
26
Example 8:
The following program and its functions double each element of an array.
27
Example 9
The following example shows the use of a function with a 1-D array as an
argument. The function receives the 1-D array and prints the sum of the
elements of the array.
Example 10
The following example shows the use of a function with a 1-D array as an
argument. The function receives the 1-D array and returns the sum of the
elements of the array.
Example 11:
The following program and its functions find the average of elements in
an array.
30
Example 12:
The following program and its functions find the maximum element in an
array:
31
Example 12 (Explanation):
double get_max(double a[], int size);: This declares the get_max function, which
will find and return the maximum value from an array of double numbers. The
function takes an array a and its size size as arguments and returns a double
value.
for loop: Reads SIZE double values from the user and stores them in the array x.
maximum = get_max(x, SIZE);: Calls the get_max function with the array x and
its size SIZE to find the maximum value and assigns it to the maximum
variable.
double get_max(double a[], int size): This is the definition of the get_max
function. It takes an array a and its size size as arguments and returns the
maximum value in the array.
double max = a[0];: Initializes the max variable with the first element of the
array. 32
for loop: Iterates through the array starting from the second element and
Example 13:
The following program and its functions add two arrays and return the
result in another array :
33
Returning an Array as a Result
In C, the return type of a function cannot be an array.
Thus, to return an array as result from a function, the only
option is to use output parameter.
We recall that output parameters for a function are declared as
pointer variables.
However, as mentioned earlier, an array variable is a pointer
variable. Therefore formal parameters of type array are already
output parameters.
34
Linear Search Algorithm
This involves searching through the array sequentially until the target item is found or the array is
exhausted.
If the target is found, its location is returned, otherwise a flag such as –1 is returned. Here is the
algorithm for Linear Search
1. Assume that the target has not been found
2. Start with the initial array element
3. Repeat while the target is not found and there are more array elements
4. If the current element matches the target
5. Set a flag to indicate that the target has been found
else
6. Advance to the next array element
7. If the target was found
8. Return the target index as the search result
35
else
9. Return -1 as the search result
Example 14 (Linear Search Implementation):
36
2-D Arrays
37
Introduction to 2-D Arrays
A 2-D array is a contiguous collection of variables of the same type, that
may be viewed as a table consisting of rows and columns.
The same reason that necessitated the use of 1-D arrays can be extended
to 2-D and other multi-D Arrays.
For example, to store the grades of 30 students, in 5 courses require
multiple 1-D arrays.
A 2-D array allows all these grades to be handled using a single variable.
This idea can be easily extended to other higher dimensions.
38
Thus, we shall focus only on 2-D arrays.
Declaration of 2-D Arrays
A 2-D array variable is declared by specifying the type of elements, the
name of the variable, followed by the number of rows and number of
columns – each is a separate bracket:
The following declares a 2-D array, table, having 3 rows and 4 columns.
int table[3][4];
Both rows and columns are indexed from zero. So the three rows have
indexes 0, 1 and 2 and four the columns have 0, 1, 2, 3.
As we saw in 1-D array, it is a good practice to declare the sizes as
constants. So a better declaration for the above is:
#define ROWS 3
#define COLS 4
Int main() {
39
int table[ROWS][COLS];
Accessing 2-D Array elements
A particular element of a 2-D array, table, is referenced by specifying its
row and column indexes. For example, given the declaration:
int table[3][4];
The following stores 64 in the cell with row index 1, column index 3.
table[1][3] = 64;
Like a 1-D array, if you provide fewer values than the declared size, the remaining cells
are set to zero.
However, unlike a 1-D array where you can skip the size, here you must give at least
the number of columns. 41
int table[][4] = { {1,2,2,1}, {3,4,4,3}, {5,6,6,5} } //OK
int table[][] = { {1,2,2,1}, {3,4,4,3}, {5,6,6,5} } //WRONG!
Processing 2-D Arrays
To process a 2-D array, we need to extend the loop we normally use with
a 1-D array to nested loops:
42
Example 15
The following program reads two matrices from the user and adds them:
43
Example 16
The following program reads two matrices from the user and adds them:
What is the difference
between this program
and the one in example
13?
44
2-D Arrays as parameters to functions
As with 1-D arrays, it is possible to declare functions that take 2-D array as a
parameter.
Inside the prototyping syntax, we may declare rows and columns as integers
along with the array itself as parameters:
DataType FunName(int rows, int cols, int arrayNamr[rows][cols]);
Example: int ComputeAverage(int studentsNo, int courses, int
grades[studentsNo][courses]
Order of the parameters is important. So the declaration of the rows and columns
must appear before the declaration of the array.
Inside your main function or any other functions, Calling functions that take a 2-D
array as an argument is the same as calling functions that take a 1-D array. Just
give the name of the array with no brackets along with its dimensions.
45
FunName(rows, cols, arrayName]);
Example: ComputeAverage(studentsNo, coursesNo, grades);
Example 17
The following program and its functions compute the summation of two
2D arrays and store the results into a third 2D array:
46
Example 18
The following example shows the use of a function with a 2-D array as an
argument. The function receives the 2-D array and prints the sum of the
elements of the array.
Example 19
The following example shows the use of a function with a 2-D array as an
argument. The function receives the 2-D array and returns the sum of the
elements of the array.
Example 20
The following example shows the use of a function with a 2-D and 1-D arrays as
arguments.
Example 20 (Explanation)
Inside the main function:
First, the array2D is declared, and sumOfRows array is also declared and
initialized with zeros.
Second the array2D, which is the 3x3 2D array, is read from the user. The
program uses nested loops to read the elements of the 2D array from the
user.
Third, the findSumOfRows function is called with the 2D array, the 1D array,
and the number of rows and columns.
Inside the findSumOfRows function:
The findSumOfRows receives a 2D array arr, an empty 1D array rowsSums, and the
number of rows and columns as arguments. Then, it calculates the sum of each row in
the 2D array and stores the results in the rowsSums.
Finally, the program, inside the main function, prints the sum of each row using
the sumOfRows array.