You are on page 1of 51

Course Title: Applied Computer

Programming II

Course Code: GEC 225


Omega Semester
2021/2022
Module 4
Arrays and Pointers
4.1.0 Arrays
An array in C language is a collection of
similar data items stored at contiguous
memory locations, with elements that
can be accessed randomly using the
indices.
They are variables that can store
multiple values of primitive data types
such as int, float, double, char, etc.

3
They can also stored derived data types
such as structures and pointers.
In an array, the lowest address
corresponds to the first element while the
highest address to the last element as
shown in Fig. 4.1.
arrName[n-
arrName[0] arrName[1] arrName[2] … 1]

First Element Last Element

Fig. 4.1: Structure of an 1-Dimensional Array


4
As illustrated in Fig. 4.1, array elements
are accessed by using an integer index.

The index starts with 0 and goes till size


of array minus 1 (i.e. n-1).

Note that the name of the array is a


pointer to the first element of array.

5
The generic syntax for 1-dimensional
array declaration in C Language is:
dataType arrayName[arraySize];
Based on this generic syntax, the various
ways to declare an array are as follows:
i)Array declaration by specifying size, e.g.
int arrSample1[10];
or
int n = 10;
int arrSample1[n];

6
ii)Array declaration by initializing
elements, e.g.

int arrSample2 [ ] = {10, 20, 30, 40,50};

Note that for this example, the compiler


creates an array of size 5 and initializes
the elements with the specified integer
values.

7
iii) Array declaration by specifying size
and initializing elements, e.g.

int arrSample3 [10] = {10, 20, 30, 40, 50};

Note that for the example above, the


compiler creates an array of size 10,
initializes the first 5 elements as
specified above while the remaining 5
elements are set to 0.
8 Monday, 30 August 21
4.1.1 Merits and Demerits of Arrays in C Language
a) Merits
i) It allows random and easy access to the elements
using array index.

ii) It helps to achieve less line of codes since a single

array of multiple elements can be created.

iii) It is easy to sort numbers with less line of codes.

iv) It is easy to traverse through an array with a single

loop.

9
b) Demerits
i) It is a static structure, which implies that it only allows
a fixed number of elements that is decided during
declaration.
ii) Insertion and deletion of elements involves storing them
in consecutive memory locations, which involves costly
shifting operation.
iii) Allocation of memory more that is required leads to
wastage of memory space, while allocation of less
memory also cause problem.

10
Example 4.1.1
Write a C program that accepts 10 numerical values
from the users into an array, calculates the sum of the
values and outputs both the values and the sum on the
console.

11
#include <stdio.h> Example4.1.1 Solution
int main()
{
float arrValues[10];
float valSum = 0;
printf("\n\nEnter the elements of the 10 element array\n");
//Use for loop to accept values from users
for (int i = 0; i < 10; ++i)
{
printf("\nEnter value for element %d\n",i+1);
scanf("%f", &arrValues[i]);
valSum = valSum + arrValues[i]; //Compute the sum of the elements
}
printf("\n\n The entered values in the array are: \n");
//Use For loop to print the entered values
for (int i = 0; i < 10; ++i)
{
printf("Value %d:\n",i+1);
printf("%f\n\n", arrValues[i]);
}
printf("\n The sum of the array elements is: %f\n\n",valSum);
return 0;
}

12
4.1.2 Passing Arrays to a Function in C Language
C programming language allows you to pass arrays
to functions.
Only the name of the array is passed as an argument
in order to pass an entire array to a function.
You can use the following syntax to call a function with
an array as the parameter:
//Array declaration
dataType arrayName[arraySize];
//Passing of an array to a function
fncResult = fncName(arrayName);

13
The syntax for the function that is called is:
//Function definition with array as argument
dataType fncName(dataType arrayName[ ])
{
Code Statement(s);
}
The use of [] in the function definition informs the
compiler that a one-dimensional array is being
passed to the function.

14
Example 4.1.2
Write a function to print the elements and another
function to compute the sum of the elements of the
array in Example 4.1.1
Note that the number of elements in the array should
be specified by the users and the two functions
should be called from the main program.

15
Example 4.1.2 Solution
#include <stdio.h>
int main()
{
float computeSum(float arrValues[],int intElement);
void printValues(float arrValues[],int intElement);
float sumResult;
int intElement; //Declare the number of elements in the array
printf("\nEnter the number of elements in the array: \n");
scanf("%d", &intElement);
//Declare the array of the specified number of elements
float arrValues[intElement];

printf("\n\nEnter the elements of the array\n");


//Use for loop to accept values from users
for (int i = 0; i < intElement; ++i)
{
printf("\nEnter value for element %d\n",i+1);
scanf("%f", &arrValues[i]);
}
16
Example 4.1.2 Solution Cont’d
printf("\n\n The entered values in the array are: \n");
//Call the function to print the elements of the array
printValues(arrValues, intElement);
//Call the function to compute the Sum of the elements
sumResult = computeSum(arrValues, intElement);
printf("\n The sum of the array elements is: %f\n\n",sumResult);
return 0;
}

//Function to calculate the sum of the array elements


float computeSum(float arrValues[],int intElement)
{
float valSum = 0;
for (int i = 0; i < intElement; ++i)
{
valSum = valSum + arrValues[i];
}
return valSum;
}
17
Example 4.1.2 Solution Cont’d
//Function to print the elements of the array
void printValues(float arrValues[],int intElement)
{
//Use for loop to print the elements of the array
for (int i = 0; i < intElement; ++i)
{
printf("Value %d:\n",i+1);
printf("%f\n\n", arrValues[i]);
}
return;
}

18
4.1.3 Multidimensional Arrays in C Language
Beyond the 1-dimesional array, which we have
considered so far, you can create an array of arrays
in C language, which is known as
multidimensional arrays.
The simplest of the multidimensional array is
2-dimensional array with the syntax:
dataType arrayName[n][m];
This can represent a matrix with n rows and m
columns as shown in Fig. 4.2.

19
Column Column … Column
1 2 m

Row
...
1 arrayName[0][0] arrayName[0][1] arrayName[0][m-1]

Row
arrayName[1][0] arrayName[1][1] ... arrayName[1][m-1]
2


... ... ... ...

Row
arrayName[n-1][0] arrayName[n-1][1] ... arrayName[n-1][m-1]
n

Fig. 4.2: Structure of an 2-Dimensional Array

20
Example 4.1.3
Write a C program to enter the elements of a 3x3
matrix and a function to print out the entered values.

21
Example 4.1.3 Solution
#include <stdio.h>
int main()
{
void dispArrayElements(float arrMatrix[3][3]);
float arrMatrix[3][3];
// Take input using nested for loop
printf("\nEnter the elements of the matrix\n");
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
printf("\nEnter arrMatrix %d %d: ", i + 1, j + 1);
scanf("%f", &arrMatrix[i][j]);
}
}
//Pass multi-dimensional(2-d) array to the display function similar to 1-d array
printf("\nDisplay the elements of the matrix\n");
dispArrayElements(arrMatrix);
return 0;
}

22
Example 4.1.3 Solution Contd’
void dispArrayElements(float arrMatrix[3][3])
{
printf("Displaying:\n");
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
printf("%.2f\t", arrMatrix[i][j]);
}
printf("\n");
}
return;
}

23
4.2.0 Pointers
As earlier defined, a Variable is a storage
and each variable is a memory location.
Every memory location has its defined
address, which can be accessed using
ampersand (&) operator.
The amount of memory the computer
allocates depends on the data type and the
compiler.

24
In a typical modern day compiler, an integer is
allocated 4 bytes memory, char variable is
allocated 1 byte, float is allocated 4 bytes and
so on.

The memory address can be operated upon


using the concept of pointers.

Pointers are variables that store address of


another variable i.e. direct address of the
memory location.
25
4.2.1 Pointers Declaration
Like any variable or constant, you must
declare a pointer before using it to store any
variable address.
The general syntax of a pointer variable
declaration is:
datatype *var-name;

26
Fig. 4.2: Illustration of Pointer

27
As shown in Fig. 4.2:
Block of 4bytes at address 204 stores
variable a.
p is storing address of a.
Using some operators on p, we can reach a.
p also takes some memory, thus, p is stored
at location 64, and it also takes 4 bytes.
You can also modify p to point to another
integer.

28 Monday, 30 August 21
The key operations for using pointers are:
i) Define a pointer variable.
ii) Assign the address of a variable to a
pointer.
iii) Access the value at the address
available in the pointer variable. This
is done by using unary operator *
that returns the value of the variable
located at the specified address.
29
The operations are illustrated with
the following codes:
int a;
int *p;
✧p is a pointer variable that points to
an integer.
To store the address of a in p, we
need to use the code statement:
30
p = &a;
✧where &a is the address of a.

This shows that p has the address of


a and points to a.

31
Example 4.2.1
//Illustration of how to use Pointer
#include <stdio.h>
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
32
Example 4.2.2
//Illustration of how to use Pointer
#include <stdio.h>
int main () {
int a=5;
int b = 10;
float c= 5.8;
printf("address of a is %u \n",&a);
printf("address of b is %u \n",&a);
printf("address of c is %u \n",&a);
printf("------------\n\n\n");
33
Example 4.2.2 cont’d
//Illustration of how to use Pointer
int*p1;
p1=&a;
int*p2=&b;
float*p3=&c;
printf("value of p1 is %u \n",p1);
printf ("value of a is %d \n \n",*p1);
printf("value of p2 is %u \n",p2);
printf ("value of b is %d \n \n",*p2);
printf("value of p3 is %u \n",p3);
printf ("value of c is %f \n \n",*p3);
return 0;
}

34
4.2.2 Null Pointers
It is always a good practice to assign a NULL
value to a pointer variable in case you do not
have an exact address to be assigned.

This is done at the time of variable


declaration. A pointer that is assigned NULL is
called a null pointer.

The NULL pointer is a constant with a value of


zero defined in several standard libraries.

35 Monday, 30 August 21
Example 4.2.3
//Illustration of how to NULL Pointer
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %p\n", ptr);
return 0;
}

36
In most of the operating systems, programs are
not permitted to access memory at address 0
because that memory is reserved by the operating
system.

However, the memory address 0 has special


significance in programming; it signals that the
pointer is not intended to point to an accessible
memory location.

By convention, if a pointer contains the null


(zero) value, it is assumed to point to nothing.

37
4.2.3 Pointer Arithmetic
A pointer in c is an address, which is a
numeric value. Therefore, you can
perform arithmetic operations on a
pointer just as you can on a numeric
value.
There are four arithmetic operators that
can be used on pointers:
They are: ++, --, +, and –.

38 Monday, 30 August 21
Assuming that ptr is an integer
pointer which points to the address
1000.

Assuming 32-bit integers, let us


perform the following arithmetic
operation on the pointer
ptr++

39 Monday, 30 August 21
After the above operation, the ptr
will point to the location 1004
because each time ptr is
incremented.

It will point to the next integer


location, which is 4 bytes next to the
current location.

40 Monday, 30 August 21
If ptr points to a character whose
address is 1000, then the above
operation will point to the location
1001 because the next character will
be available at 1001.

41
4.2.3.1 Incrementing a Pointer
A pointer is often preferred instead of an
array because the variable pointer can be
incremented, unlike the array name which
cannot be incremented.

The following program increments the


variable pointer to access each succeeding
element of the array.

42 Monday, 30 August 21
Example 4.2.4
//Illustration of how to
#include <stdio.h>
const int MAX = 10;
int main () {
int var[] = {100,200,300,400,500,600,700,800,900,1000};
int i, *ptr; /* let us have array address in pointer */
ptr = var;
printf("\n");
for ( i = 0; i < MAX; i++) {
printf("Address of var[%d] = %p\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the next location */
ptr++;
printf("\n");
}
return 0; }
43
4.2.3.2 Decrementing a Pointer
The same considerations for
incrementing a pointer also applies to
decrementing a pointer,
The value is decreased by the number of
bytes of its data type.

44
Example 4.2.5
//Illustration of how to
#include <stdio.h>
const int MAX = 10;
int main () {
int var[] =
{100,200,300,400,500,600,700,800,900,1000};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
printf("\n");

45
Example 4.2.5 Cont’d
for ( i = MAX; i > 0; i--)
{
printf("Address of var[%d] = %p\n", i-1, ptr);
printf("Value of var[%d] = %d\n", i-1, *ptr);
/* move to the previous location */
ptr--;
printf("\n");
}
return 0;
}

46
4.2.4 Array of Pointers
There may be a situation when we want
to maintain an array, which can store
pointers to an int or char or any other
data type available.

The following syntax is the declaration of


an array of pointers to an integer.

int *ptr [MAX]


47 Monday, 30 August 21
It declares ptr as an array of MAX
integer pointers.

Thus, each element in ptr, holds a


pointer to an int value.

This is illustrated with Example 4.2.6.

48 Monday, 30 August 21
Example 4.2.6
#include <stdio.h>
const int MAX = 5;
int main () {
int var[] = {10, 15, 20, 25, 30};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of the integers */
}
printf("\n");
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
49
Module 4 Assignment
Write a C program to enter the elements of two n x n
matrices. The main program should call the following
functions:
i)A function that computes the sum of the matrices.
ii)A function that computes the product of the matrices.
iii)A function that displays the resulting matrices from i)
and ii) above.

Note:
The codes and outputs of this assignment MUST
be submitted on moodle.cu.edu.ng before the
next class.
50
END OF MODULE 4

51

You might also like