Fundamentals of Programming - Chapter#5
Fundamentals of Programming - Chapter#5
1
Composite Type
A data type is called simple if variables of that type can store only
one value at a time.
Composite type or aggregate type is types that we can use to
define collections of data such that we can manipulate an entire
collection as a unit, but can still refer to individual components of a
given datum by name.
Composite Types are derived from more than one primitive type.
Examples
Array, struct, unions
A data structure is a particular way of storing and organizing
composite data in a computer memory so that it can be used
efficiently
2
Array
3
Array
In general, only the array itself has a num[0]
int
symbolic name, not its elements.
num[1]
Each element is identified by an index
num[2]
which denotes the position of the element
in the array. num[3]
5
One-dimensional Array:
6
Declaration of One-dimensionalArray
An array must be declared before it is used. Definition and declaration
tell the compiler the name, type, and dimension of the array.
The general syntax for one-dimensional array is:
type variable_name[dimension/size];
The dimension of the array must be an integer constant or integral
constant expression and must have a value at compilation time.
Example
float score[20]; //score can store 20 float value
char letterGrade[50]; //letterGrade can store 50 char value
int next, score[5], max; // declare arrays and regular
variables together
const unsigned int SIZE=50;
double temp[2*SIZE]; //constant expression for dimension
int i=15, temp[i]; //invalid declaration
7
Declaration…
8
Array Initialization
Array can be initialized at the time of declaration. There are two option.
Syntax (Option 1):
type array_Name[dimension/size] = { value0, value1, ..,value2};
type array_Name[dimension/size] { value0, value1, ..,value2};
Where
– type specify that what kind of array you are declaring
– array name specify the name of the array
– dimension specifies the size of the array
– value0, value1,…,valueN specify the initial values for array_name[0],
array_name[1],…, array_name[N] respectively.
Dimension is optional. The compiler can determine the dimension from the
list of initial values.
If the number of initial values is less than the dimension specified, the extra
elements of the array will be initialized to 0 for numeric type array or null
character(‘\0’) for character type array. 9
Array…
Example:
int num[5]={3,7,12,24,15]; //equivalent int num[]={3,7,12,24,15];
double distance[5] = {44.14, 720.52, 96.08, 468.78, 6.28};
double distance[5] ={0}; //all elements initialised to zéro
double m[5] ={1.5, 2.3, 4.7}; //m[0], m[1], m[2], m[3], and m[4] are
initialized to 1.5, 2.3, 4.7, 0.0, and 0.0 respectively.
10
Referencing Elements of an Array
An array individual elements can be accessed using an index. For a
one-dimensional array, the first element has an index of 0, the
second element has an index of 1, and so on. Array index starts
from zero.
The general format for accessing an array element in one dimensional
array is:
array_name[index];
Where array_name is the name of the array and index is an integral
constant or any expression that evaluates to an integral value.
Example:
score[3] refers to the third element to the array score
11
Referencing…
• An element of an array can be used any where a variable
can be used.
Assuming the following declaration
int arr[20]={1}, i=1, y=3;
An element of array can be assigned:
arr[4] = 55; //The fifth element of the array arr assigned 55
It can be used in an expression(as lvalue and rvalue):
arr[2*i +1] = 3*y + arr[2*i]; //the 4th element is assigned 10
It can be used in an input-output statement:
cin >> arr[18]; //the 19th element will be an integer read from
keyboard
cout << arr[15]; //The 16th will be displayed on the screen
12
Referencing…
Consider the following declaration for the next proposition:
int lista[]={5, 7, 9, 6, 4}, listb[5];
• Attempting to access a nonexistent array element leads to a
serious runtime error (called ‘index out of bounds’ error). The
compiler won’t complain if you assign a value to the
nonexistent element. Your code will compile.
listb[5]=lista[0]; // index out of bounds error
cout << lista[-1] ; // index out of bounds error
• C++ does not allow aggregate operations on an array:
listb=lista; //illegal. Copy element by element
cin >> listb; //illegal! Read element by element
cout << listb; //illegal! Display element by element
Copy element by element
13
Array Processing
14
Initialization
15
Filling array from Keyboard
16
Outputting Data Stored in an Array
17
Finding The Smallest, Largest,
Range and Average Value
Write a program that collects the score of students and
determine the smallest, largest, range and average of the
scores
18
Range Based For Loop and Array
A range based style loop is designed to cycle through a collection of
objects, such as an array, vector in strictly sequential fashion, from start
to finish.
The general form of the for-each version of the for is shown here:
for(range_decleration : collection){
statements
}
There are two types of ranged based loops
1. Normal Iterators: an ordinary temporary variable is diclared as the
iterator, and the iterator gets a copy of the current loop item by value.
Any changes made to the temporary copy will not get reflected in the
original iterable.
Syntax
for (datatype iterator : collection) {
// operation are performed here
19
}
Range Based For Loop…
20
Range Based For Loop…
2. Reference Iterators: Reference iterators are declared as a
reference variable, and the iterator gets the value of the current item by
reference. So the changes made inside the loop are definitely get
affected in the original container itself.Syntax
for (datatype & iterator : collection) {
// operation are performed here
}
int arr[]={12, 20, 50,54, 72, 101};
for(auto & x:arr){
x=2*x;
}
21
Two-dimensional Array:
22
Two-dimensional Arrray
23
Logical View of Two Dimensional Array
The table below shows the sale amount of salesperson for the quarters of
the year. This sales data can be represented using a two dimensional array,
row number representing salesperson and column number representing
quarter. It is a 7 by 4 two dimensional array. This is the logical view of the
programmer, as seven rows of four doubles entries each.
Quarter
Q1 Q2 Q3 Q4
50000 35000 27000 45000 27000 42000 33000 22000 11000 25000 31000 20000
25
Two-dimensional Array Declaration
A two dimensional array has two indices: row index and
column index.
The general syntax for declaring two dimensional array is:
dataType arrayName[rowSize][columnSize];
Where dataType, arrayNname, rowSize, columnSize refer to
the data type, array name, row dimension and column
dimension of the array respectively.
The dimension of the array must be an integer constant or
integral constant expression and must have a value at
compilation time.
double sales[7][4]; //declaration for the previous sale table
This array consists of seven rows and four columns and is
called a 7-by-4 array 26
Initialization of Two-dimensional Array
As with one-dimensional arrays, two-dimensional arrays can
be initialized in their declaration statements by listing the
initial values inside braces and separating them with
commas. Additionally, braces can be used to separate rows.
Syntax:
dataType arrayName[n][m] ={{value00, value01,…,value0m},
{value10, value11,…,value1m},
{value20, value21,…,value2m},
.
.
{valuen0, valuen1,…,valuenm}} .
• Although the commas in initialization braces are always required,
the inner braces can be omitted.
27
Initialization…
• In two-dimensional array, if the array is completely initialized, it
is possible to omit the first dimension(the row size).
• For numerical arrays, if all components of a row aren’t
specified, unspecified ones are set to 0
Example
int table[5][4]={{0, 1, 2, 3}, {10,11,12,13}, {20, 21, 22, 23},
{30, 31, 32, 33}, {40, 41, 42, 43}};
Or
int table[5][4]={0, 1, 2, 3, 10,11,12,13, 20, 21, 22, 23,
30, 31, 32, 33, 40, 41, 42, 43};
Or
int table[][4]={{0, 1, 2, 3}, {10,11,12,13}, {20, 21, 22, 23},
{30, 31, 32, 33}, {40, 41, 42, 43}}; 28
Referencing Array Elements for Two-
dimensional Array
30
Processing Two-Dimensional
Arrays
Processing a two-dimensional array usually requires a nested
loop.
Initialization
• To initialize a particular row (i.e., fifth row) to 0
row=4;
for(i = 0; i < rowSize; i++)
table[row][i]=0;
• To initialize the whole array to some value v
for(i = 0; i < rowSize; i++)
for(j = 0; i < colSize; i++)
table[i][j]=v;
31
Processing…
Inputting
for(i = 0; i < rowSize; i++)
for(j = 0; i < colSize; i++)
cin >> table[i][j];
Outputting
for(i = 0; i < rowSize; i++){
for(j = 0; i < colSize; i++)
cout << setw(5) << table[i][j] << ‘\t’;
cout << endl;
}
32
Range Based For Loop For 2D array
int b[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
for (auto& outer : b) {
for (auto& inner : outer) {
std::cout << inner << std::endl;
}
}
On the outer loop the auto and the & are required so that the array
doesn't decay to a pointer.
33
Example
Write a program that calculates and displays the
sum for each individual row, column, and the two
diagonal of a square matrices of integer. The
dimension of the square matrix is known to be not
greater than 10. The actual dimension must be
accepted from the user. The matrix is populated by
accepting the data from the user.
34
Multi-Dimensional Array:
35
Multi-Dimensional Array
36
Using Multi-Dimensional Array
A multi-dimensional array is used in a similar fashion as two-
dimensional array.
Initialization
An n-dimensional array will be initialized during declaration
using n level nested braces for each dimension.
Example for three-dimensional array
int arr[2][3][4] = {{{1,2,3,4}, {5,6,7,8},{9,10,11,12}},
{{13,14,15,16}, {17,18,19,20},{21,22,23,24}}}
It is possible to omit size of first dimension but not other
dimensions
Note: A three-dimensional array is simply an array of two-
dimensional array.
37
Using Multi-Dimensional Array
Referencing
An n-dimensional array will be referenced using n indices for
each dimension. Example
arr[2][3][1]=55;
Processing
An n-dimensional array will be processed using n level nested
loops.
38
Limitation of an Array
39
Pointer
40
Pointer-Concept
The memory of your computer can be 000A1051 6
imagined as a succession of memory 000A1052
000A105
cells, each one of the minimal size that 3
000A1054
computers manage (one byte). 2
000A105
These single-byte memory cells are 5
000A105
numbered in consecutive way. This 6
000A105 7
number is called the address of that 7
000A105
byte. Hexadecimal number is used to 8
000A105
9
represent these addresses. 000A106 1
0
000A106 0
1
000A106
2
000A106 8
3
000A106
4
000A106
5 41
Pointer and Variable
A variable is implemented as a sequence of
adjacent memory locations. For example
float var1=27.34;
char var2=‘A’; short var3; 000A1051 A Char
var1 is implemented as 4 bytes of 000A1052 var2
000A105
consecutive memory. 3
000A1054 27.34
var2 is implemented as 1 bytes of memory. 000A105
Float
var3 is implemented as 2 bytes of 5
000A105
var1
5
000A105
consecutive memory 6
000A105
The memory address of the first byte 7
000A105
can be used as names for the variables. 8
000A105 short
10
9
Thus a pointer to the memory address 000A106 var3
0
000A106
of the first byte of the variable provides 1
b
000A106
an indirect way of accessing variable. 2
000A106
c
3
000A106
4 42
Pointer Type
43
Pointer Value
C++ allows you to obtain the memory
address of the first byte of a variable, i.e. 000A1051 A char
the pointer to the variable, through the 000A1052
address operator(&). 000A105
3
000A1054
The address operator(&) provides a pointer 27.34
000A105
constant to any named location in memory. 5
000A105 Float
5 var1
Syntax: 000A105
6
000A105
&var_name 7
000A105
Where var_name is a valid variable name. 8
000A105
10
short
Example: consider the previous slide and 9
000A106 var3
what will be printed 0
000A106 b
1
float var1=27.34; 000A106
2
c
000A106
char var2=‘A’; 3
000A106
cout << “Address of var1: “ << &var1 << ‘\n’; 4 44
45
Declaring a Pointer Variable
Like any other variable a pointer variable should be declared prior of
use.
Different types uses different numbers of bytes and different internal
formats for storing values. Therefore, a pointer declaration must
specify what type of data to which the pointer points.
Declaration syntax:
dataType * ptr1, * ptr2, …,* ptrLast;
The variable ptr1, ptr2,…ptrLast can hold pointers to variables of type
dataType only but it cannot normally contain a pointer to a variable
of some other type.
Example:
double * ptrSale; //ptrSale is a pointer variable that can point a
double variable
int *p1, *p2, v1, v2; //p1, p2 are pointers, v1,v2 are int
46
Pointer Initialization
You can use the address operator & to determine the address of a
variable, and you can then assign that address to a pointer variable.
A pointer can be initialized during declaration by assigning it the address
of an existing variable. Then it is said to be it points to that variable.
SYNTAX
dataType var1, var2,…, varLast;
dataType *pvar1=&var1, *pvar2=&var2, …, *pvarLast=&varLast;
EXAMPLE
float data = 50.8;
float *ptr = &data; //ptr points to data
ptr Data
A pointer can be initialized to a NULL(0) during declaration . Then it is
said to be it points to nothing.
int *ip = 0;// points to nothing
float *fp = NULL; // points to nothing 47
Pointer Initia…
Pointers can also be initialized or set a value after declaration.
Example:
int ival1; fptr1 fval1
49
Accessing…
EXAMPLE
double x=0; *ptr1, *ptr2;
ptr1=&x;
ptr2=ptr1;
cout << x;
cout << *ptr1;
cout << *ptr2; The three statements are equivalent,
*ptr1=6;
cout << x << “ “ << *ptr2; //What is the output?
Note:
• It is an error to dereference a pointer whose value is NULL. It is
recommended first to check for NULL before dereferencing
• your program may also crash with run time error if you try to
dereference uninitialized pointer variable. 50
Pointer Operation
• Assignment – the value of one pointer variable can be assigned to
another pointer variable of the same type. Example:
int *ptr1, *ptr2, ival=0;
float *ptr3,fval=5;
ptr1=&val; //valid?
ptr1=&fval; // valid?
ptr3=ptr1; // valid?
ptr2=&ptr1;// valid?
ptr3=fval; // valid?
ptr3=&fval; // valid?
ptr1= 0xB8000000; // valid?
ptr1= (int *) 0xB8000000; // valid?
• Some limited arithmetic operations
– integer values can be added to and subtracted from a pointer
variable
ptr2=ptr1 + 5; ptr2=ptr1 - 5
51
Pointer Operation
54
Pointer and…
56
Example
57
Void Pointer
The void type of pointer is a special type of pointer. In C++, void
represents the absence of type, so void pointers are pointers that
point to a value that has no type (and thus also an undetermined
length and undetermined dereference properties).
The void pointer, also known as the generic pointer, is a special
type of pointer that can be pointed at objects of any data type. A
void pointer is declared like a normal pointer, using the void
keyword.
Syntax:
void * voidPtr;
Example:
int val1=6; float val2=3.14;
void * voidPtr=&val1;
voidPtr=&val2;
58
Void Pointer
59
Void Pointer
#include <iostream.h>
#include <conio.h>
int main()
{
int inum[3] = {10,20,30},i;
float fnum[4] = {1.2, 2.4, 3.7,9.8};
void *pvoid = NULL;
pvoid = inum;
for ( i=0; i<3; i++ )
cout<<*((int *)pvoid + i );
// Same void pointer can be cast to float
cout<<"\n";
pvoid = fnum;
for( i=0; i < 4; i++ )
cout<< *((float *) pvoid + i));
getch();
60
}
Pointer to Pointer
C++ allows the use of pointers that point to pointers, that these, in
its turn, point to data (or even to other pointers). In order to do
that, we only need to add an asterisk (*) for each level of reference
in their declarations:
Example:
char a; // a is type char
char * b; //b is type a pointer to char
char ** c; //c is type a pointer to pointer to char
char ***d; //d is type a pointer to pointer to pointer to char
a = 'z';
b = &a; supposing the randomly chosen memory locations for each variable are
7230, 8092 and 9002, it could be represented as:
c = &b;
a b c d
d=&c;
z 7230 9002 10012
61
7230 9002 10012 30012
Pointer to…
#include <iostream.h>
int main()
{
int num = 26;
int *ptr;
int **ptrToPtr;
ptr = #
ptrToPtr = &ptr;
cout << " The value of num is: = " << num << "\n";
cout << " The value of num is: = “ << *ptr << "\n";
cout << " The value of numis: = “ << **ptrToPtr << "\n";
return 0;
}
62