You are on page 1of 43

Unix Systems Programming

(CSE 3041)

Arrays
Chapter-7

SOA
Deemded to be University

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 1 / 43
Motivation

To solve many programming problems, it is more efficient to group data


items together in main memory than to allocate an individual memory
cell for each variable.
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.
composite data structure are made up of simpler data structures that
exist in the language.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 2 / 43
Defining Arrays

An array is a collection of two or more adjacent memory cells, called


array elements, that are associated with a particular symbolic name.
An array is a collective name given to a group of ‘similar quantities’.
One dimensional array may be defined abstractly as a finite ordered set
of homogeneous elements.
I “finite”: there is a specific number of elements in the array. This number
may be large or small, but it must exist.
I “ordered”: the elements of the array are arranged so that there is a
zeroth, first, second, third, and so forth.
I “homogeneous”: all the elements in the array must be of the same type.
An array is a collection of data items of the same type.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 3 / 43
Declaring Arrays

To set up an array in memory, we must declare both the name of the ar-
ray and the number of cells associated with it.
Array declaration
double x[8]
The number 8 tells how many elements of the type double will
be in our array.
and [8] tell complier that we are dealing with arrays.
instructs the compiler to associate eight memory cells with the
name x;
these memory cells will be adjacent to each other in memory.
Each element of array x may contain a single type double value,
a total of eight such numbers may be stored and referenced
using the array name x.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 4 / 43
Referencing arrays
How each individual elements in the array can be referenced ?
Done with subscript: the number in [ ] following the array name. It
specifies the element’s position in the array.
All the array elements are numbered, starting with 0.
Subscripted variable is a variable followed [subscript], designating an
array element.
Subscripted variable
x[0] use to reference 0th element of x
x[1] use to reference 1th element of x
x[7] use to reference the last element of x

Array subscript:
a value or expression enclosed in [] after the array name, specifying
which array element to access.
Range of its value :0 to (the number of memory cells in the array-1).
(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 5 / 43
Figure: Statements that manipulate array x
(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 6 / 43
Multiple array Declarations

Figure: Multiple array Declarations

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 7 / 43
Array subscript

Array subscript:
are used to differentiate between the individual array elements
are used to specify which array element is to be manipulated.
can be any expression of type int as an array subscript.
must lie between 0 and one less than the declared size of the array.

Figure: Array subscript

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 8 / 43
(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 9 / 43
A simple C program using array

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 10 / 43
Using for Loops for Sequential Access

For scanning data into array or printing its contents:


Process the elements of an array in sequence, starting with element
zero.
Accomplished using an indexed for loop,
I a counting loop whose loop control variable runs from 0 to one less than
the array size.
I Using the loop counter as an array index (subscript) gives access to each
array element in turn.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 11 / 43
Statistical Computations Using Arrays

Write a program to compute the mean and standard deviation of an array


of data and displays the difference between each value and the mean.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 12 / 43
Points to ponder

An array is a collection of similar elements.


The first element in the array is numbered 0, so the last element is 1
less than the size of the array.
An array is also known as a subscripted variable.
Before using an array its type and dimension must be declared.
However big an array its elements are always stored in contiguous mem-
ory locations.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 13 / 43
Array initialization

Till the array elements are not given any specific values, they are sup-
posed to contain garbage values.
If the array is initialised where it is declared, mentioning the dimension
of the array is optional.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 14 / 43
Array elements in memory

Figure: Memory map for int X[8]

16 bytes get immediately reserved in memory, 2 bytes each for the 8


integers
All eight values present in the array would be garbage values.
All the array elements would always be present in contiguous memory
locations.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 15 / 43
Bounds Checking

In C, there is no check to see if the subscript used for an array exceeds


the size of the array.
Data entered with a subscript exceeding the array size will simply be
placed in memory outside the array.
There will be no error message to warn you that you are going beyond
the array size.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 16 / 43
Using Array Elements as Function Arguments

Array elements can be passed to a function by


Calling the function by value: we pass values of array elements to the
function
Call by reference: we pass addresses of array elements to the function

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 17 / 43
Pointers and Arrays

Every time a pointer is incremented it points to the immediately next


location of its type.
Pointer arithmetic: following operations can be performed on a pointer

X Addition of a number to a pointer.


X Subtraction of a number from a pointer.
X Subtraction of one pointer from another
X Comparison of two pointer variables

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 18 / 43
Pointer Arithmetic: DO NOT ATTEMPT

X Addition of two pointers


X Multiplication of a pointer with a constant
X Division of a pointer with a constant

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 19 / 43
Important correlation

Correlation
Array elements are always stored in contiguous memory locations.
A pointer when incremented always points to an immediately next lo-
cation of its type.
Illustration
Write a program that prints out the memory locations in which the
elements of this array are stored.
Two programs to show ways in which we can access the elements of
an array.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 20 / 43
Which method is better?

Accessing array elements by pointers is always faster than accessing


them by subscripts.
Array elements should be accessed using pointers if the elements are
to be accessed in a fixed order, say
I from end to beginning, or
I every alternate element or
I any such definite logic.
Easier to access the elements using a subscript if there is no fixed logic
in accessing the elements.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 21 / 43
Passing an Entire Array to a Function

The address of the zero th element can also be passed by just passing
the name of the array.
This address is also called the base address of the array.
Practice problem
WAP to initialize all elements of an array with a specific value.

The second way:


int list[]
Notice that the parameter declaration does not indicate how many
elements are in list.
Because C does not allocate space in memory for a copy of the actual
array, the compiler does not need to know the size of the array param-
eter.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 22 / 43
The Real Thing

On mentioning the name of the array we get its base address.


*num we would be able to refer to the zeroth element of the array
num[i], the C compiler internally converts it to *( num + i )

Figure: All same. Can be used to get i th data item stored in the array num.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 23 / 43
Arrays as Input Arguments

ANSI C provides a qualifier (const ) that we can include in the declaration


of the array formal parameter
to notify the compiler that the array is only an input to the function &
that the function does not intend to modify the array.
const : attempt to change an array element within the function results in
compilation error.
Returning an Array Result Function’s return type can not be an array;
use o/p parameters instead.
Programming problems
Function to find the largest Element in an Array.
WAP to add two arrays.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 24 / 43
Partially filled arrays

Array can be used for processing shorter lists as well, provided that the
program keeps track of how many array elements are actually in use.
Use sentinel controlled loops to track the number of elements in use.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 25 / 43
Stacks

A stack is a data structure in which only the top element can be ac-
cessed.
Operations on Stack:
I Pop: Removing a value from a stack.
I Push: storing an item in a stack.
WAP to implement stack with functions for push and pop operations.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 26 / 43
Application: Linear Search algorithm

Searching an array is to determine the location of a particular value.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 27 / 43
Application : Selection sort

Sorting an array is to rearrange the array elements in numerical order.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 28 / 43
Parallel arrays

Parallel arrays : Two or more arrays with the same number of elements
used for storing related information about a collection of data objects.
If there are n-elements, these parallel arrays contain data for n-objects
of the same kind.
Further, all array elements at subscript i contain data for the ith object
in this group of n-objects.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 29 / 43
Enumerated Types

Good solutions to many programming problems require new data types.


Examples:
I Categories for expenses for a Budget problem: entertainment, rent, util-
ities, food, clothing, automobile, insurance, and miscellaneous.
I Possibilities for Marital status: Unmarried, Married, Divorced, and Wid-
owed.
I Days of a week : Monday, Tuesday,...,Sunday.
I Department in a payroll program: assembly, manufacturing, accounts
and stores.
Enumerated data types allow defining own data types and define what
values the variables of this type can take.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 30 / 43
Enumerated types

Syntax
enum marital status
{
unmarried, married, divorced, widowed
};
enum mar status person1,person2;

First part: declares the data type and specifies its possible values.
These values are called enumerators or Enumeration constants
Second part: declares variables of enumerated data type.
person1=married ; person2=widowed;

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 31 / 43
Enumeration types

Do not use values that aren’t in the original declaration.


Internally, Compiler treats the enumerators as integers. Each values
corresponds to an integer, starting with 0.
You may override the assigned numbers by initializing the enumerators
to different integer values.
Pros and Cons
Make the program listing more readable.
Reduce program errors.
Used to clarify the operation of a program.
Weakness : No way to use the enumerated values directly in I/O func-
tions.
Are Enums necessary ? Macros vs Enums.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 32 / 43
Renaming data types with typedef

To clarify source code use typedef declarations.


Use to redefine the name of an existing variable type.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 33 / 43
Figure: Declaration

Figure: Relational, assignment, and even arithmetic operators can be used with
enumerated types

Figure: Looping
Figure: Selection

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 34 / 43
Two Dimensional Arrays
Multidimensional arrays are arrays with two or more dimensions.
The two dimensional array is also called a matrix.

Figure: Conceptual array elements arrangement in 2-D.

Basic idea :)
A two-dimensional array is a collection of a number of 1-D arrays
placed one below the other.
(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 35 / 43
Initializing 2-D array

Initialization

Another way to Initialize

Valid declarations Invalid declarations

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 36 / 43
Array arrangement in memory

Figure: Conceptual array elements arrangement in 2-D.

Figure: Array elements are stored in one continuous chain.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 37 / 43
Pointers and 2-Dimensional Arrays

C can treat parts of arrays as arrays.


Each row of a 2-D array can be thought of as a 1-D array.
Important fact: to access array elements of a 2-D array using pointers.

s[0] → address of First 1-D array


s[1] → address of Second 1-D array
s[2] → address of Third 1-D array
s[3] → address of Fourth 1-D array

Figure: Example memory map for array s[4][2].

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 38 / 43
Pointer to an Array

We have seen :
int *ip;
float *fp;
char *cp;
A pointer to an array? How to build and use it.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 39 / 43
Passing 2-D Array to a Function

3-ways to pass a 2-D array to a function


1. Using formal parameter for 2-D: int *q
2. Using formal parameter for 2-D: int (*q)[4]
3. Using formal parameter for 2-D: int q[ ][4]

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 40 / 43
Array of Pointers
We have
an array of ints or
an array of floats or
an char of floats
Lets learn :
Similarly there can be an array of pointers.
As known a pointer variable always contains an address, therefore
An array of pointers would be nothing but a collection of addresses.

Figure: Write a program to implement the above memory map?


(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 41 / 43
Three dimensional arrays

Figure: Conceptual memory map for 3-D


array

Figure: Initialization of 3D array.


Figure: Sequential storage
(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 42 / 43
Summary
X An array is similar to an ordinary variable except that it can store
multiple elements of similar type.
X Compiler doesn’t perform bounds checking on an array.
X The array variable acts as a pointer to the zeroth element of the array.
In a 1-D array, zeroth element is a single value, whereas, in a 2-D array
this element is a 1-D array.
X On incrementing a pointer it points to the next location of its type.
X Array elements are stored in contiguous memory locations and so they
can be accessed using pointers.
X Only limited arithmetic can be done on pointers.
Suggested readings:
Cover chapter 7 from your prescribed text book including various
case studies. Solve/attempt all programming problems from chap-
ter 7.

(Ashish Kumar Gupta, Ph.D.) Chapter-7, Arrays, C programming November 30, 2021 43 / 43

You might also like