Chapt. 3 Arrays and Strings
Chapt. 3 Arrays and Strings
1
Dept. of Computer & Electrical Eng.
TWENEBOAH-KODUAH S.
UENR
2
Chapter 3 –
Arrays, Strings &
Pointers
A COLLECTION OF DATA IN BANK
DIVIDED INTO CELLS
“All progress is born of inquiry. Doubt is often better than overconfidence, for
it leads to inquiry, and inquiry leads to invention” – Hudson Maxim
UENR
3
Learning Objectives
At end of this chapter, you will be able to
◦ understand what an array is
◦ learn about one-dimensional array, their declaration, initialization,
ways to access individual array elements, representation of array
elements in memory, and other possible operations
◦ learn about one-dimensional strings and the way they are
declared, initialized,
◦ manipulated, inputted, and displayed
◦ learn about two-dimensional arrays, initialization of sized and
unsized two-dimensional
◦ arrays, accessing elements in such arrays, and how this kind of an
array can be used
◦ know about array of strings, its declaration, initialization, other
operations, manipulations, and uses
◦ get a brief idea of three-dimensional arrays or even larger ones
UENR
4
Scalar variable & aggregate type
Single value variable
◦ char maryJ;
◦ int n;
◦ float price;
Aggregate type
◦ any type whose values can be decomposed and are
related by some defined structure.
◦ Data retrieval and updating can be perform on individual
values of data structure.
◦ Structured type
◦ Data structure
UENR
6
Arrays
Arrays enable the storing and manipulation of potentially huge quantities of
data.
An array stores an ordered sequence of homogeneous values.
◦ Homogeneous means that all the values are of the same data type.
The order of the values are also preserved, i.e., the integer array {1, 2,
3, 4} is different from {1, 4, 3, 2}.
An array is a collection of individual data elements that is
Ordered—one can count off the elements 0, 1, 2, 3, ...
◦ Fixed in size
◦ Homogeneous—all elements have to be of the same type, e.g., int, float,
char, etc
Properties
◦ Data type
◦ Size of the array
◦ Zero base index
UENR
7
Arrays
Data structure ARRAY
◦ All arrays consist of contiguous memory locations.
The lowest address corresponds to the first element
and the highest address to the last element.
Types of arrays
• One dimensional array
• Multidimensional array
UENR
1D array declaration
Syntax
dataType array_name [size];
All the array elements hold values of type <dataType>
The size of the array is indicated by <SIZE>, the
number of elements in the array. <SIZE> must be an
int constant or a constant expression.
Array size must be a constant integer > 0
Example
◦ int array[10]; // can hold 10 integers. Reserves
space for 10 integers
◦ int arr[100]; // what is the size?
UENR
9
1D array declaration
Accessing arrays
◦ <array name> [<index>]
◦ Index is an integer constant ranging from 0 to <SIZE> -
1.
UENR
10
1D array declaration
Accessing element 3
◦ number [3];
UENR
11
1D array declaration
Illegal array declaration
UENR
12
1D array declaration
Syntax dataType arrayName [arraySize];
Example
int age[5];
Initializing arrays
int age[5]={2,4,34,3,4}; //Or int age[ ]={2,4,34,3,4};
UENR
1D array – accessing elements
Output
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
UENR
Animated 1D
array
UENR
Example
A program for
printing
numbers that
are greater than
the average
18
UENR
Array in
Computer
Memory
19
UENR
Sorting array
Bubble sort
A bubble sort compares adjacent array elements and
exchanges their values if they are out of order.
Smaller values ‘bubble’ to the top of the array (towards
element 0), while the larger values sink
to the bottom of the array.
This sort continues until no exchanges are performed in a pass.
If no exchanges are made, then all pairs must be in order.
A flag named ‘sorted’ is used to determine the state of the
array
UENR
20
Sorting array
Bubble sort
A bubble sort compares adjacent array elements and
exchanges their values if they are out of order.
Smaller values ‘bubble’ to the top of the array (towards
element 0), while the larger values sink
to the bottom of the array.
This sort continues until no exchanges are performed in a pass.
If no exchanges are made, then all pairs must be in order.
A flag named ‘sorted’ is used to determine the state of the
array
UENR
21
Sorting array – another illustration
UENR
22
Sorting array
23
UENR
In this way, we can keep track of the unsorted portion of the list and repeat
steps a and b with the help of a for loop, as shown in the following
pseudocode:
for (index = 0; index < length - 1; index++)
{
a. Find the location, smallestIndex, of the
smallest element in
list[index]...list[length - 1].
b. Swap the smallest element with list[index].
That is, swap list[smallestIndex] with
list[index].
}
Sorting array
24
UENR
Sorting array 25
UENR
Example
Searching an element within an array
Sequential search
◦ Search for an item with a list or array
Binary search
◦ The drawbacks of sequential search can be eliminated
if it becomes possible to eliminate large portions of the
list from consideration in subsequent iterations.
UENR
26
Binary search
In binary search, the following procedure is implemented.
◦ Look at the middle element of the list.
◦ If it is the value being searched, then the job is done.
◦ If the value that is being searched is smaller than the middle
element, then continue with the bottom half of the list.
◦ If the value that is being searched is larger than the middle
element, then continue with the top half of the list.
In effect, binary search splits the array in half and then
repeats the algorithm on the half that must contain the
value that it is searching for, if it is there at all.
UENR
27
Binary search
UENR
28
Binary search
Algorithm
UENR
29
Arrays of arrays Multidimensional array
Syntax:
data_type array_name [size1] [size2] ... [sizeN];
Example: int threedim[5][10][4];
float a[2][6];
//Here, a is an array of two dimension, which is an example
of multidimensional array. It has 2 rows and 6 columns
UENR
Strings array of characters
Array of character are called strings.
String is terminated by a null character \0
Each character in a string occupies one location in an array
‘\0’ is used to tell the compiler the end of the string
Strings have double quote “ . ” whereas character has
single quote ‘ . ‘
Example char msg[] = {‘h’,’e’,’l’,’l’,o’,’\0’};
I l o v e E E E 2 C
p r o g r a m m i n g \0
UENR
Strings and characters
Strings have double quote “ . ” whereas
character has single quote ‘ . ‘
Character is of the type char and string can
have type “pointer to char” i.e. (char *) or
array of character i.e. char myString [ ]
#include <cstring>
is need to use any string manipulation
function in C. e.g. strcopy, strlen, strcmp(),
etc.
UENR
Strings and characters
#include <cstring>
is need to use any string manipulation
function in C. e.g. strcopy, strlen, strcmp(),
etc.
char studentName[26];
studentName = "Lisa L. Johnson"; //illegal
UENR
Strings and characters
#include <cstring>
is need to use any string manipulation
function in C. e.g. strcopy, strlen, strcmp(),
etc.
char studentName[26];
studentName = "Lisa L. Johnson"; //illegal
UENR
Strings and characters
#include <cstring>
is need to use any string manipulation
function in C. e.g. strcopy, strlen, strcmp(),
etc.
char studentName[26];
studentName = "Lisa L. Johnson"; //illegal
UENR
Strings and characters
String declaration
1. As array of characters
e.g. char str1[ ] = “I like”;
2. As pointer to char
e.g. char *str2 = “EEE2 C programming”
UENR
Using cin() & getline() to accept string
char str1[26];
cin.get(str1, 26); //stores 25 characters
char textLine[100];
cin.getline(textLine, 100); //reads or store 99
characters
UENR
Multidimensional array
Parallel Arrays
Two (or more) arrays are called parallel if their
corresponding components hold related
information.
◦ Suppose you need to keep track of students’ course
grades, together with their ID numbers, so that their
grades can be posted at the end of the semester.
◦ Example
• int studentId[50];
• char courseGrade[50];
UENR
38
2D strings
2D string
array
initialization
Syntax:
<data_type> <string_array_name>[<row_size>] [<columns_size>];
UENR
39
Manipulating string arrays
cstring is required in string manipulation using
the following
String copy strcopy()
String length strlen()
String compare strcmp()
etc
UENR
40
Animated 2D arrays
data_Type Array_name
[row size][column size];
UENR
xD array initialization
The syntax for declaring a two-dimensional array is:
dataType arrayName[intExp1][intExp2];
Example, double sales[10][5];
UENR
xD array initialization
int c[2][3] = {
{1,3,0}, {-1,5,9}
};
OR
int c[][3] = {
{1,3,0}, {-1,5,9}
};
OR
int c[2][3]={1,3,0,-1,5,9};
UENR
xD array initialization
UENR
Accessing 2D array elements
An element in 2-dimensional array is accessed by
using the subscripts, i.e.,0 row index and column
a[0][0]:
index of the array.a[0][1]:
i.e. where
0 i and j are the array
indexes a[1][0]: 1
For example: int val = a[2][3];
a[1][1]: 2 //
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
UENR
Matrix addition
Write a C program to find sum of two matrix of
order 2*2 using multidimensional arrays where,
elements of matrix are entered by the user.
Best choice is for loop(s)
UENR
Accessing 2D array elements
Best choice is for loop(s)
UENR
To find the transpose of a matrix
Transpose of a matrix is found by exchanging rows
for columns of a matrix
UENR
49
Transpose of a matrix
UENR
50
UENR
51
UENR
52
UENR
53
Matrix
multiplication
54
UENR
Largest element in each row
UENR
55
Passing arrays as function arguments
1D array can be pass as double getAverage(int arr[],
function argument. Function int size)
parameters must be formally {
declared first
int i;
void myFunc (int *param)
double avg;
{…}
double sum;
void myFunc (int param[10])
{…}
for (i = 0; i < size; ++i)
{
void myFunc (int param[ ])
{…} sum += arr[i];
}
Example
avg = sum / size;
return avg;
}
UENR
Example – passing array to function
UENR
57
typedef declaration of 2D arrays
If you know the size of the tables with which the program will
be working, then you can use typedef to first define a two-
dimensional array data type and then declare variables of
that type.
For example, consider the following:
◦ const int NUMBER_OF_ROWS = 20;
◦ const int NUMBER_OF_COLUMNS = 10;
◦ typedef int tableType[NUMBER_OF_ROWS]
[NUMBER_OF_COLUMNS];
So, we can declare a variable of the type defined already
(above)
◦ tableType matrix;
◦ declares a two-dimensional array matrix of 20 rows and 10 columns.
UENR
58
Enumeration
Type
UENR
59
User defined (simple) data type
Enumeration Type
To define an enumeration type, you need the
following items:
◦ A name for the data type
◦ A set of values for the data type
◦ A set of operations on the values
C++ lets you define a new simple data type
wherein you specify its name and values, but not
the operations.
UENR
60
User defined (simple) data type
Enumeration Type
The syntax for enumeration type is:
enum typeName {value1, value2, ...};
value1, value2, ... are identifier called enumerators.
The statement:
◦ enum colors {BROWN, BLUE, RED, GREEN, YELLOW};
◦ defines a new data type called colors, and the values
belonging to this data type are BROWN, BLUE, RED,
GREEN, and YELLOW.
UENR
61
User defined (simple) data type
Enumeration Type Assignment: popularSport = FOOTBALL;
Declaring variable
◦ dataType identifier, identifier,...;
The statement:
enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER,
VOLLEYBALL};
Defines an enumeration type called sports.
The statement:
◦ sports popularSport, mySport;
declares popularSport and mySport to be variables of type
sports. No arithmetic operations are allowed on the enumeration type
UENR
62
User defined (simple) data type
No arithmetic operations are allowed on enum type.
◦ Illegal operations; mySport = popularSport + 2; popularSport++;
enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER,
VOLLEYBALL};
Allowed operations on enum type:
◦ popularSport =
static_cast<sports>(popularSport + 1);
popularSport = FOOTBALL;
popularSport =
static_cast<sports>(popularSport + 1);
After the second statement, the value of popularSport is
HOCKEY.
UENR
63
Declaring Variables When Defining the Enumeration Type
You can declare variables of an enumeration type
when you define an enumeration type
enum grades {A, B, C, D, F}
courseGrade;
◦ defines an enumeration type, grades, and declares a
variable courseGrade of type grades.
enum coins {PENNY, NICKEL, DIME,
HALFDOLLAR, DOLLAR} change, usCoins;
◦ defines an enumeration type, coins, and declares two
variables, change and usCoins, of type coins.
UENR
64
Enum type as index of array
const int NUMBER_OF_ROWS = 6;
const int NUMBER_OF_COLUMNS = 5;
enum carType {GM, FORD, TOYOTA,
BMW, NISSAN, VOLVO};
enum colorType {RED, BROWN, BLACK,
WHITE, GRAY};
int inStock[NUMBER_OF_ROWS]
[NUMBER_OF_COLUMNS];
UENR
65
Statement:
inStock[FORD][WHITE] = 15;
UENR
67
Namespaces
Syntax
namespace namespace_name
{
members
}
where members is usually named constants,
variable declarations, functions, or another
namespace.
UENR
68
Namespaces
Accessing namespace
◦ namespace_name::identifier
To access the member RATEof the namespaceglobalType,
the following statement is required:
◦ globalType::RATE
UENR
69
Records
(structs)
C++ STRUCTURES
UENR
70
Array and structures
Arrays Structures (struct)
Takes basic data types It is user defined data type
such as int, char, float, Itdifferent
hold collection of elements of
basic data type
etc. It is basically a record
Data is organize into It is a collection of variables of
linear elements of the different data types under a single
name
same data type
It can hold arrays or pointers as
Array is compose of some of its members
the same type of It means of grouping variables
under a single name for easier
elements handling and identification.
UENR
71
Declaring structures & structure variables
The keyword struct is used to declare structures
follow by optional tag or the structure name followed
by the body of the structure
Variables or members are declared within the body of
the structure block.
General structure declaration format
struct <structure_tagName> {
<dataType memberName1>; //basic data
<dataType memberNameN>; // types
}<structure_Variable1>,
<structure_Variable2>, … ;
UENR
72
Declaring structures & structure variables
General structure declaration format
struct <structure_tagName> {
<dataType memberName1>; //basic data
<dataType memberNameN>; // types
}<structure_Variable1>,
<structure_Variable2>, … ;
structure_tagName is name of the structure.
structure_Variables are list of variables
separated by commas
◦ Also known as instance variables
UENR
73
Declaring structures & structure variables
Like all data types, structures must be declared
and defined
Ways to declare and/or define a structure
◦ Variable structure
◦ Tagged structure
◦ Type-defined structure
UENR
74
Declaration of variable structure
struct {
member_List;
} variable_Identifier;
Example
struct {
int x;
int y;
} a;
UENR
75
Declaration of tagged structure
struct tag_Name{
Defining structure variables
member_List; struct tag_Name
} variable_Identifier; variable1, variable2, …;
Example
struct coordinate{
int x;
Structure are most
int y;
often declared at the
} a;
global area of a
Variable a is of type coordinate.
It has separate instance of all
program before
members (x and y) in the main()
structure.
UENR
76
Declaration of type structure
struct tag_Name{
member_List;
};
Example
struct coordinate{
int x;
int y;
};
Variable a is omitted.
We can declare a variable that is of type coordinate
UENR
77
Example
Declare a structure to get (or set) the coordinate
of any point in pixels on a screen.
UENR
78
Example – structure to hold personal data
UENR
79
Example – structure to hold personal data
UENR
80
Memory allocation
Example
81
UENR
Example – structure to hold personal data
UENR
82
Operations on structures
Structures can take ‘ = ‘ (simple assignment) and
‘ & ‘ (take the address).
It is not possible to compare structures for
equality using ‘ == ‘.
It is also not possible to perform arithmetic
operations on structures.
Arithmetic operations can only be done on
members of the structure.
UENR
83
Accessing members of a structure
Members of a structure can be accessed with the
use of the dot ‘ . ‘ operator (member access
operator)
General form of statement for accessing members
of a structure is
structure_variable . member_name
UENR
84
Accessing members of a structure
newStudent.GPA = 0.0;
newStudent.firstName =
“John”;
Getting/printing data
◦ cin>>newStudent.firstName;
◦ cout<<newStudent.testScore;
Assignment
◦ Student = newStudent;
Relational operator
However, ◦ if (student.firstName ==
if (student == newStudent) { } //illegal newStudent.firstName &&
student.lastName ==
newStudent.lastName) { }
UENR
85
Initializing structures
UENR
86
Initializing structures – Example
UENR
87
Initializing structures – Example
UENR
88
Example – complete program
A railway ticket generation program that uses
named initialization in a structure using C++.
UENR
89
Typedef in structure declarations
The typedef keyword allows the programmer to create
a new data type name for an existing data type.
No new data type is produced but an alternate name is
given to a known data type.
The general form of the declaration statement
using the typedef keyword is given as follows
typedef <existing data type> <new data
type ,….>;
UENR
90
Typedef in structure declarations
The general form of the declaration statement using the
typedef keyword is given as follows
typedef <existing data type> <new data
type ,….>;
UENR
91
Typedef in structure declarations
The general form of the declaration statement using the
typedef keyword is given as follows
typedef <existing data type> <new data
type ,….>;
In structure declaration
UENR
92
The hot coffee
UENR
05/07/2024 CENG 201 93
Understanding memory addresses
Computers has primary memory (RAM)
◦ Example of size of RAM; 16, 32, … 512 MB
etc.
◦ RAM holds the programs that the computer
is currently running along with the data
they are currently manipulating (their
variables and data structures).
◦ All variable used in a program and the
program itself reside in the RAM
◦ It is a sequence of a large number of
memory locations (cells), each of which has
an address. Each memory location is Variables that are defined outside any
capable of storing a small number (0 to function (whether of global or file static
256), which is known as a byte. scope), and variables that are defined
inside a function as static variables,
Declaring variables first always allows the exist for the lifetime of the program’s
compiler to set aside a space in memory execution.
which can then be filled up with useful These variables are stored in the data
numbers. segment.
UENR
94
Stack
UENR
95
Memory stack before pointers
The memory cells (a, b, c, and
d) holds values of integer type
( …, -2, -1, 0, 1, 2, ….)
A memory cell must have a
location, which we reference
via its address
The symbol indicate the
memory cell current holds
garbage – i.e. meaningless
value until variables are
initialized
UENR
05/07/2024 CENG 201 96
Memory stack before pointers cont’d
After initialization at line 3, the
garbage is replaced with the
(current) value
UENR
05/07/2024 CENG 201 97
Processor Clock cycles –
simplified
Computers operate on a clock style.
◦ At the beginning of each clock cycle, input values are read
from memory;
◦ During the cycle, arithmetic occurs over the input values;
◦ At the end of the cycle, computed values are written to
memory.
(oh!, that’s massive over-simplification )
UENR
05/07/2024 CENG 201 98
Stack example
Fill in the data corresponding to final memory configuration
UENR
05/07/2024 CENG 201 99
Stack example – self check
Fill in the data corresponding to final memory configuration
Answers:
a = 4; b = 2; c = 3
UENR
05/07/2024 CENG 201 100
Pointers – What are Pointers?
Different from other normal variables which can store values.
Pointers are special variables that can hold the address of a variable.
Since they store memory address of a variable, pointers are very
commonly said to “point to variables”.
UENR
05/07/2024 CENG 201 101
Pointers declaration
pointer_dataType *pointer_variableName;
◦ Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable
(user) and not a normal variable.
pointer_dataType : It specifies the type of pointer. It can
be int, char, float etc. This type specifies the type of
variable whose address this pointer can store.
pointer_variableName : It can be any name specified by
the user. Professionally, there are some coding styles which
every code follows. The pointer names commonly start
with ‘p’ or end with ‘ptr’. char *chptr;
UENR
05/07/2024 CENG 201 102
Pointers declaration
o Key points to remember about pointers in C:
Normal variable stores the value whereas pointer
variable stores the address of the variable.
The content of the C/++ pointer is always a whole
number i.e. address.
Always C/C++ pointer is initialized wth a null, i.e.
int *p = null.
The value of null pointer is 0.
UENR
05/07/2024 CENG 201 103
Pointers declaration
& symbol (address of operator)is used to get the
address of the variable.
* symbol (dereferencing operator or indirection
operator) is used to get the value of the variable
that the pointer is pointing to.
If a pointer is assigned to NULL, it means it is
pointing to nothing.
Two pointers can be subtracted, to know how many
elements are available between these two pointers.
But, Pointer addition, multiplication, division are
not allowed.
The size of any pointer is 2 byte (for 16 bit compiler).
UENR
05/07/2024 CENG 201 104
Pointers declaration -- Example
SYNTAX: type *variable ;
EXAMPLE: float *p;
INTERPRETATION: The value of the pointer variable p is a
memory address. A data item whose address is stored in this
variable must be of the specified type.
Example
int m = 25;
int *itemp; /* a pointer to an integer */
itemp = &m; /* Store address of m in pointer itemp */
UENR
05/07/2024 CENG 201 105
Pointers declaration -- Example
Note:
*itemp can be used to reference the cell selected by pointer item
*itemp = 35; //stores 35 in the variable m that is pointed by itemp
printf("%d", *itemp); // displays the new value of m (35).
The statement
*itemp = 2 * (*itemp); //doubles the value currently stored in m
UENR
05/07/2024 CENG 201 106
Illustration
UENR
107
Memory stack after pointers
//Pointer to an integer
After line 6
After line 4
UENR
05/07/2024 CENG 201 108
Arrays and pointers
Consider the array
int arr[4];
UENR
Arrays and pointers
(a + 3)
UENR
Arrays and pointers
Pointers can be used to alter the data of the array
UENR
Pointers
Pointer makes codes more efficient
It makes code harder to understand
It introduces what is called ugly bugs
Pointer bugs can crash a programme randomly
hence difficult to debug
Pointers are used to access memory addresses
UENR
112
Pointers
Pointers in C/C++ provide an alternative means of
accessing information stored in arrays, which is
especially valuable when working with strings. There
is an intimate link between arrays and pointers in C.
C/C++ uses pointers to handle variable parameters
passed to functions.
They are used to create dynamic data structures, those
that are built up from blocks of memory allocated from
the heap at run-time. This is only visible through the
use of pointers.
UENR
113
The address operator (&)
Example of usage scanf(“%d”, &n);
The & sign indicates to the address in memory of
the integer n, which must be previously declared
using int n;
Printing the address of a variable
◦ printf(“\n Address of i = %u”, &i);
UENR
114
Declaring a pointer
dataType *pointer_Variable
Example char *ptr
Meaning of some pointer type variable
declarations
UENR
115
Storing address of variable
#include <stdio.h>
int main()
{
int i = 5;
int *ptr = &i;
printf(“\nThe address of i using
& sign is %p”, &i);
printf(“\nThe address of i using
Ptr is %p”, ptr);
return 0;
}
UENR
116