Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 127

Oromia State University

Department of IT

Fundamental of Programming

Chapter 5
ARRAYS AND STRINGS
Lecture note

IT Dep't Fundamental of
programming
Introduction to Arrays
Consider an organization that need to store the age
of 2000 employees in their DB. For the organization
it would not be feasible to define 2000 variable,
each with a different name. because a variable is
capable to storing only one value at a time.

The solution is to create one array variable, of the


integer data type because you need to store ages,
containing 2000 values.
What Is An Array?

• An array Definition: – is a collection of values that have


the same data type.
o Is a group of variables of the same data type, collectively
represented by a single name.
o e.g. A collection of integer data values or A collection
of character data values etc…
• An array is used to process a collection of data of the
same type
Examples:
o A list of names (i.e. employees,books,student…)
o A list of temperatures
• Every variable or an item in an array is known as an
element of that array. IT Dep't Fundamental of
programming
Con’t
• The data type of the array element defines the data type
of the array. This data type can be:
• char, int, long, float or double.
• An array irrespective of its data type has a finite size. All
the elements of an array are known by the same name.
Each element of an array has its own subscript (index
value).
• A subscript is a unique number assigned to every
element of an array and this subscript or index is used to
access an array element.

IT Dep't Fundamental of
programming
Why do we need Array?
• It is the method of implementing all variables of the same
data type by a single name.
• Special way of processing individuals /each of the variable.
What is the benefit or advantage of using Array?
 Compare the number of instruction need to handle
individual elements
 Performance of a computer is not reduced when
Fetch, decode, and execute phase
 Reusability of programs-how much needs to be changed if
the number of data items changed.

IT Dep't Fundamental of
programming
Con’t
• Consider the following that displays an array score of
five elements. int Score[5]
• Score [0] Score [3]
• Score [1] Score [4]
• Score [2]
• In the above statements score is assumed to an array of
five elements. These five elements are distinguished
from one another using the subscripts 0,1,2,3 and 4.
• As a result, the first element score [0], the second
element score [1], the third element score [2], the fourth
element score [3], and the fifth element score [4].

IT Dep't Fundamental of
programming
How to Declare Arrays?
• To declare an array in C++, you should specify the
following things
– The data type of the values which will be stored in the
array
– The name of the array (i.e. a C++ identifier that will be
used to access and update the array values)
– The dimensionality of the array:
• One dimensional (i.e. list of values ),
• Two-dimension array (a matrix or a table), etc.
– The size of each dimension
syntax: type ArrayName[ArraySize];
IT Dep't Fundamental of
programming
Con’t
• Examples
– int x[10]; // An integer array named x with size 10

– float GPA[30]; // An array to store the GPA for 30


//students

– int studentScores[30][5]; // A two-dimensional


array to store the scores of 5 exams for 30 students

IT Dep't Fundamental of
programming
Declaring an Array
• An array, named score, containing five
variables of type int can be declared as
int score[ 5 ];
• This is like declaring 5 variables of type int:
score[0], score[1], … , score[4]
• The value in brackets is called
– A subscript or
– An index
IT Dep't Fundamental of
programming
Declaring arrays Con’t…
Arrays are declared like other variables, except that
the identifier is followed by brackets containing a
value specifying the size of the array.
Form/syntx:
type ArrayName[ArraySize];
Type- any data type
ArrayName – any valid identifier
ArrayValue or (ArraySize) – a constant variable,
expression,
or literal
Examples: const int N = 30;
int A[N], B[2*N], C;
The Array Variables
• The variables making up the array are referred to as:
– Indexed variables
– Subscripted variables
– Elements of the array
• The number of indexed variables in an array is the
declared size, or size, of the array
– The largest index is one less than the size
– The first index value is zero

IT Dep't Fundamental of
programming
Array Name Vs Element Name
• In array we have two types of identifiers:
– The name of the array and
– The name of each individual element
• The name of the array- is the name of the whole
structure, while ;
• The name of an element-allows us to refer to that
element.
• Example, score[5]
– where, score-is the name of the array and
– Name of each element is the name followed by the index.
• Example, score[0],score[1] and so on.
IT Dep't Fundamental of
programming
Using [ ] With Arrays
• In an array declaration, [ ]'s enclose the size
of the array such as this array of 5 integers:
int score [5];
• When referring to one of the indexed variables, the [ ]'s
enclose a number identifying one of the indexed
variables
– score[3] is one of the indexed variables
– The value in the [ ]'s can be any expression that
evaluates to one of the integers 0 to (size -1)

IT Dep't Fundamental of
programming
Indexed Variable Assignment

• To assign a value to an indexed variable, use


the assignment operator:

int n = 2;
score[n + 1] = 99;
– In this example, variable score[3] is
assigned 99

IT Dep't Fundamental of
programming
Loops And Arrays
• We can use loops to read and write the elements in an
array.
• We can also use loops to process elements.
• Now it does not matter if there are 100,1000 or 10,000
elements to be processed-loops make it easy to handle
them all.
• We can use an integer variable to control the loop and
remain in the loop as long as the value of this variable
is less than the total number of elements in the array.

IT Dep't Fundamental of
programming
Con’t
• for-loops are commonly used to step through arrays
• Example: for (i = 0; i < 5; i++)
{
cout << score[i] << " off by "
<< (max – score[i]) << endl;
}
could display the difference between each score and
the maximum score stored in an array

IT Dep't Fundamental of
programming
Constants and Arrays
• Use constants to declare the size of an array
– Using a constant allows your code to be easily
altered for use on a smaller or larger set of data
• Example:
const int NUMBER_OF_STUDENTS = 50;
int score[NUMBER_OF_STUDENTS];

for (int i = 0; i < NUMBER_OF_STUDENTS; i++)
cout << score[i] << " off by "
<< (max – score[i]) << endl;
• Only the value of the constant must be changed to
make this code work for any number of students
IT Dep't Fundamental of
programming
Computer Memory

• Computer memory consists of numbered locations


called bytes.
– A byte's number is its address.

• A simple variable is stored in consecutive bytes


– The number of bytes depends on the variable's type

• A variable's address is the address of its first byte

IT Dep't Fundamental of
programming
Arrays and Memory

• Declaring the array int a[6]


– Reserves memory for six variables of type int
– The variables are stored one after another
– The address of a[0] is remembered
• The addresses of the other indexed variables is
not remembered
– To determine the address of a[3]
• Start at a[0];
• Count past enough memory for three integers
to find a[3]
IT Dep't Fundamental of
programming
Accessing an Array elements
• If we would like to access a particular value stored in an
array, we specify its index (i.e. its position relative to the
first array value)
– The first array index is always 0
– The second value is stored in index 1
– Etc.

IT Dep't Fundamental of
programming
Con’t
• Note: The array subscript numbering starts at zero.
Thus, the highest subscript for an array of N elements
would be N-1.
• Types of arrays
– You can classify arrays by name, types, and size.
– This is known as dimensioning the array.
Array can be of two types:
– Single/One-dimensional
– Multi-dimensions

IT Dep't Fundamental of
programming
Con’t
A single-dimensional array is an array with
a single row of elements.

A single-dimensional array of five elements


with integrating data is presented as shown
below.

IT Dep't Fundamental of
programming
Con’t
• A multi-dimensional array is an array with more than
one-dimension.
For example, a two-dimensional array has multiple rows
and multiple columns of elements.
• The following is a two-dimensional array with three
rows and five columns that store integer values.
Score[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}

IT Dep't Fundamental of
programming
• The Subscripts of the two dimensional array
are shown below

• In the above reading from left to right the first cell


denotes the first column of the row.

IT Dep't Fundamental of
programming
Con’t

• Declaring an array is quite similar to declaring variable


first you specify the data type and the name. Then,
since an array is a collection of variables, you specify the
size of the array using a number enclose within square
brackets.

IT Dep't Fundamental of
programming
Con’t
• Note: - in a multi-dimensional array, each dimension is
represented by a separates square bracket. The product
of the entire dimension determines the size of such array
syntax.
• <Data_Type><variable_Name>[dimention1_size]
[dimension2_size ];
• Where: dimension1_size and dimension2_size are the
sizes of the two dimensions of the array.

IT Dep't Fundamental of
programming
One-dimensional Arrays
• We use one-dimensional (1Dim) arrays to store
and access list of data values in an easy way by
giving these values a common name,
e.g. int x[4]; // all values are named x

x[0] = 10; // the 1st value is 10 x[0] 10


x[1] 5
x[1] = 5; // the 2 value is 5
nd

x[2] 20
x[2] = 20; // the 3rd value is 20
x[3] = 30; // the 4th value is 30 x[3] 30

IT Dep't Fundamental of
programming
Declaring one-dimensional Array
• Consider the following statement
• int singarray[10];
• This statement declares a single-dimensional array,
singarray of integer type.
• The number 10 in the square bracket indicates the
size of singarray. There are 10 elements in singarray.

IT Dep't Fundamental of
programming
Con’t
• Every array element is distinguished from every other
element by means of a subscript. The first element of
an array is denoted by the subscript zero, the second
by the subscript 1 and so on. The last element of an
array is denoted by a subscript which is one less than
the size of the array. So the last element of singarray
is singarray [10-1], i.e. singarray [9].
• The 10 elements of singarray can be denoted by
singarray [0], singarray [1], singarray [2], up to
singarray [9].

IT Dep't Fundamental of
programming
Con’t
• The C++ compiler allocates memory to a variable based on
its data types. Similarly, after the declaration of the array,
the compiler allocates memory to every element of that
array based on the array’s data type.
• Therefore, the declaration of singarray causes the
compiler to set aside 20 contiguous bytes of memory to
singarray (assuming that every element, an integer
variable occupies 2 bytes in memory.)

IT Dep't Fundamental of
programming
Con’t
• Following the declaration, every element of
singarray stores a garbage value in its memory
location.
• To store meaningful value in the elements of
singarray, the array can be initialized at a time of
declaration or its elements can be assigned values
later.

IT Dep't Fundamental of
programming
Accessing 1Dim Array Components

• General syntax:

where indexExp, called an index, is any expression


whose value is a nonnegative integer
• Index value specifies the position of the component in
the array
• [] is the array subscripting operator
• The array index always starts at 0

IT Dep't Fundamental of
programming
Array Index Out of Bounds

• If we have the statements:


double num[10];
int i;

• The component num[i] is valid if i = 0, 1, 2, 3, 4, 5, 6, 7, 8, or


9
• The index of an array is in bounds if the index >=0 and the
index <= ARRAY_SIZE-1
– Otherwise, we say the index is out of bounds
• In C++, there is no guard against indices that are out of
bounds
IT Dep't Fundamental of
programming
Initializing (1Dim) arrays
Elements in array may be initialized in two ways:
1) Explicitly (using an assignment statement for each
element)
2) Using a list: A list is denoted using braces { }, with
element in the list separated by a comma.
Example, float Cgpa[5]={3.7,2.5,2.0,1.7,4.0};
1) Initializing arrays explicitly Easily accomplished using a
for loop.

Example: Explicitly initialize all elements in an array to 5.0


const int Asize = 100;
int A[Asize];
for (int i = 0; i < Asize; i++) A[i] = 5.0;
IT Dep't Fundamental of
programming
2) Initializing arrays using a list

Elements in array may be initialized using a list of values in


braces.

• If the number of values listed is less than the size of the


array, the remaining elements are initialized to zero
(treated as null characters ‘\0’ in char arrays).
• If the array size is omitted when using a list, then the
array size is set to the number of elements in the list.
Example:
double X[4] = {1.1, 2.2, 3.3, 4.4}; // initialize array X
// with a list
Using the list above is equivalent to:
double X[4];
X[0] = 1.1;
X[1] = 2.2;
X[2] = 3.3; IT Dep't Fundamental of
programming
Example:-Initializing arrays using a list
int A[5] = {11,22}; // initializes array values to 11,22,0,0,0
double Sum[7] = {0.0}; // initializes all 7 sums to 0.0
int B[ ] = {2,4,6,8}; // array B is assigned an array size of 4
char Vowels[8] = “aeiou”; // Vowels[0] = ‘a’, Vowels[1] = ‘e’, etc.

Array Sum Array Vowels


Array A Array B
0 a
11 2
0 e
22 4
0 i
0 6
0 o
0 8
0 u
0
0 \0
0 \0
\0
\0 is the “null character”
Copying Arrays
• The Assignment operator can’t be applied to array
variables:
 Const int size=10
 Int x[size];
 Int y[size];
 X=y; //illegal
• Only individual elements can be assigned to using the
index operator, eg.,x[1]=y[2];
• To make all elements in ‘x’ the same as those in
‘y’(equivalent to assignment), a loop has to be used.
• //loop to do copying one elements at a time.
 For(int i=0;i<size;i++)
 X[i]=y[i]
IT Dep't Fundamental of
programming
Exercise

• Write a program using array that will


calculate the sum of 5 numbers accepted.
• First try it by for loop and
• By array

IT Dep't Fundamental of
programming
Two-dimensional Arrays
• Two-dimensional array: collection of a fixed number
of components (of the same type) arranged in two
dimensions
– Sometimes called matrices or tables
• Declaration syntax:

where intexp1 and intexp2 are expressions yielding


positive integer values, and specify the number of
rows and the number of columns, respectively, in
the array IT Dep't Fundamental of
programming
Two-dimensional Arrays (cont'd.)

IT Dep't Fundamental of programmin


g
Two-Dimensional Arrays (continued)

IT Dep't Fundamental of
programming
Accessing 2D Array Components
• The syntax to access a component of a two-
dimensional array is:
arrayName[index_1][index_2]
where indexexp1 and indexexp2 are
expressions yielding nonnegative integer
values.
• Index_1 specifies the row position and
index_2 specifies the column position

IT Dep't Fundamental of
programming
Accessing 2D Array Components (cont'd.)

IT Dep't Fundamental of programmin


g
Processing Two-Dimensional Arrays

• A two-dimensional array can be processed in three


different ways:
1. Process the entire array
2. Process a particular row of the array, called row
processing
3. Process a particular column of the array, called
column processing

IT Dep't Fundamental of
programming
Processing Two-Dimensional Arrays (continued)

• Each row and each column of a two-


dimensional array is a one-dimensional array

• When processing a particular row or column


of a two-dimensional array

– we use algorithms similar to processing


one-dimensional arrays

IT Dep't Fundamental of
programming
Two-Dimensional Array Initialization
During Declaration
• Two-dimensional arrays can be initialized when they are
declared:
int mark[4][3]={{2,3,1},{15,25,13},{20,4,7},{11,18,14}
– Elements of each row are enclosed within braces and
separated by commas
– All rows are enclosed within braces
– For number arrays, if all components of a row aren’t
specified, unspecified ones are set to 0.

IT Dep't Fundamental of
programming
2D Array cont…
• Two-dimensional arrays are stored in row order
– The first row is stored first, followed by the
second row, followed by the third row and so
on
• When declaring a two-dimensional array as a
formal parameter
– can omit size of first dimension, but not the
second
• Number of columns must be specified

IT Dep't Fundamental of
programming
Initialization

• To initialize row number 4 (i.e., fifth row) to 0:

• To initialize the entire matrix to 0:

IT Dep't Fundamental of
programming
Print/display
• To output the Elements of matrix:

IT Dep't Fundamental of
programming
Input
• To input data into each component of matrix:

• Exercise 3:
• Write a program that can do matrix addition of two 3x3
matrix.
IT Dep't Fundamental of
programming
Omitting the Array Size
• If one-dimentional array is initialized, the size
can be omitted as it can be found from the
number of initializing elements:
 Int []={1,2,3,4};
• This initialization creates an array of four
elements.
• Note how ever:
 Int x[][]={{1,2},{3,4}}; // error is not allowed.
• And must be written
 Int [2][2]={{1,2},{3,4}};
IT Dep't Fundamental of
programming
Functions and Arrays
Arrays may be passed as arguments of functions, but some
important
notes should be made:
• Function declaration - include the data type and empty
brackets
• Function call – include the array name with no brackets
• Function header – include the data type, name, and empty
brackets
String Representation and Manipulation

• String in C++ is nothing but a sequence of


character in which the last character is the null
character ‘\0’.The null character indicates the
end of the string. Any array of character can be
converted into string type in C++ by appending
this special character at the end of the array
sequence. IT Dep't Fundamental of
programming
Continued…
• In C++ strings of characters are held as an array of
characters, one character held in each array
elements. In addition special null character,
represented by ‘\0’ is appended to the end of the
string to indicate the end of the string. Hence if a
string has N characters then it requires an N+1
element array (at least) to store it. Thus the
character ‘a’ is stored in a single byte whereas the
single-character string “a” is stored in two
consecutive bytes holding the character ‘a’ and the
null character.
IT Dep't Fundamental of
programming
Character Strings
• A sequence of characters is often referred to
as a character “string”.
• A string is stored in an array of type char
ending with the null character '\0 '.

IT Dep't Fundamental of
programming
Character Strings cont…
A string containing a single character takes up 2
bytes of storage.

IT Dep't Fundamental of programmin


g
Character vs. String
• A string constant is a sequence of characters
enclosed in double quotes.
– For example, the character string:
char s1[2]="a"; //Takes two bytes of storage.
s1:
a \0
– On the other hand, the character, in single
quotes:
char s2 [1] =`a` //Takes only one byte of storage.

s2:
a
IT Dep't Fundamental of
programming
Reading and Writing Strings
• Most rules that apply to arrays apply to C-
strings as well
• Aggregate operations, such as assignment
and comparison, are not allowed on arrays
• Even the input/output of arrays is done
component-wise
• The one place where C++ allows aggregate
operations on arrays is the input and
output of C-strings (that is, character
arrays) IT Dep't Fundamental of
programming
Input/Output with Strings
• A common problem with reading strings from user input is that it could
contain white spaces.
• cin uses white space (e.g. space, tab, newline) as a delimiter between
inputs;
cin >> fullName;
> getName2.exe
Enter your full name: Groucho Marx
Your name is: Groucho
//Consider the following example
#include<iostream>
using name space std;
int main ( ) {
char name [16];
cout<<”enter your fulname”;
cin>>name; IT Dep't Fundamental of
programming
String Output
• cout << name; outputs the content of name
on the screen
– << continues to write the contents of name
until it finds the null character
– If name does not contain the null character,
then we will see strange/out of the ordinary
output
• << continues to output data from
memory adjacent to name until '\0' is
found
IT Dep't Fundamental of
programming
String Input

• cin >> name; stores the next input C-string


into name
• To read strings with blanks, use get:
cin.get(str, m+1);
– Stores the next m characters into str but
the newline character is not stored in str
– If the input string has fewer than m
characters, the reading stops at the
newline character
IT Dep't Fundamental of
programming
//Exercise to read text containing blanks we use another
function, get().
//Example,
#include <iostream>
using namespace std;
int main ()
{
const int max=80;
char str[max];
cout<<“\n enter a string”;
cin.get(str,max); //max avoid buffer overflow
cout<<”\n you entered :”<<str;
return 0;
} IT Dep't Fundamental of
programming
Reading multiple lines
• We have solved the problem of reading strings with
embedded blanks, but what about strings with multiple
lines?
• It turns out that the cin::get() function can take a third
argument to help out in this situation.
• This argument specified the character that tells the
function to stop reading. The default value of this
argument is the newline (‘\n’) character, but if you call
the function with some other character for this
argument, the default will be overridden by the specified
character.
• In the next example, we call the function with a dollar
sign (‘$’) as the third argument IT Dep't Fundamental of
programming
//reads multiple lines, terminates on ‘$’character

#include<iostream>
using namespace std;
int main (){
const int max=80;
char str[max];
cout<<”\n enter a sting:\n”;
cin.get(str,max,’$’); //terminates with $
cout<<”\n you entered \n”<<str;
Return 0;
}

IT Dep't Fundamental of
programming
Avoiding buffer over flow

• The string in the program invites the user to type in a


string. What happens if the user enters a string that is
longer than the array used to hold it? There is no built-
in mechanism in C++ to keep a program from inserting
array elements outside an array.
• However, it is possible to tell the >>operator to limit
the number of characters it places in an array.

IT Dep't Fundamental of
programming
//avoids buffer overflow with cin.width
#include<iostream.h>
usingname space std;
#include<iomanip.h> //for setw
int main()
{
const int max=20;
char str[max];
cout<<“\nenter a string:”;
cin>>setw(max)>>str;
cout<<“\n you entered:”<<str; }

IT Dep't Fundamental of
programming
Get( ) and getline( ) functions
• Use the get() and/or getline () functions to read
spaces and multiple lines in a string.
• There are situations when a user may want to store
many words in a variable.
• Consider the following codes:
//Example,Codes to enter the name of the user
#include<iostream>
using name space std
int main ( ) {
char name [16]
cout<<”enter your fulname”;
cin>>name; IT Dep't Fundamental of
programming
continued
• As seen in the output of the code the variable name,
stores only the first word. To overcome this problem
c++ provide the follow two functions.
• get () and
• getline () functions
• These are built-in functions in C++ that accept user
input at run time.
• String .h Header file
• C++ provides the string.h header file, which contains
a number of functions to manipulate strings. This
header file contains the prototypes of the string-
based functions.
IT Dep't Fundamental of
programming
The functions defined in string .h are divided in
to three categories
• str Functions: Function names that begin with str
and operate on strings that terminate with a null
character.
• Strn Functions: Function names that begin with
strn and operate on strings of specified length.
• Mem Function: Function names that begin with
mem and operate on character arrays of
specified length.

IT Dep't Fundamental of
programming
Some examples of str functions that are applied on
strings are
• Strlen( ): Returns the length of the string. The function has
only one argument, a string specified in double quotes or a
string variable. The value returned by the function does not
include the length of the null character.
//exercise on the strlen() function
# include < iostream>
using name space std
void main () {
char name [20]
int len =0;
cout << “enter your name”
cin getline (name, 20)
len= strlen (name) << name << end; IT Dep't Fundamental of
programming
• Strcat: concatenates or append a source string
to a destination string. This function takes two
arguments. The first argument is the
destination string and the second argument is
the source string. The source can be specified
in the double quotes or as a string variable.
• The value returned by the function includes the
null character.

IT Dep't Fundamental of
programming
//Example in the strcat ( ) function

# include < iostream>


# include <string .h>
using namespace std
int main ( ) {
char name [40];
char name [20];
cout<< “enter your first name “<<end;
cin.getline (name, 40)
cout<<”enter your last name”<< end;
cin.getline (name, 20)
strcat (name, “ “)
strcat (name, lname0 << end
cout<< ” name=”<< name }
IT Dep't Fundamental of
programming
• Strcpy ( ): copies or overwrites a destination
string with the source string. The function
takes two arguments.
• The first argument is the source string. This
source string can be specified in double
quotes or as string variable. The value
returned by the function includes the null
character.

IT Dep't Fundamental of
programming
//Example in the strcpy ( ) function
#include <iostream>
#include<string.h>
using namespace std
int main () {
char name [40];
char copy [40];
cout<<“ enter your name << endl;
cin.getline (name,40) ;
cout<<”name =”<< name <<endl;
strcpy (copy,name);
cout<<”copied name =”<<copy;
}

IT Dep't Fundamental of
programming
• Strcmp ( ): compares the source string with the
destination string. The function takes two arguments,
both of whichc may be strings specified in double
quotes or string variables.
• The function returns the following value based on the
results of the comparisons.
• A negative value: if the length of the first is less them
the second string
• Zero (0): it the strings are exactly the same
• A positive value: if the length of the first string is grate
than the second

IT Dep't Fundamental of
programming
//exercise on strcmp( ) function
# include <iostrem>
#include <string.h>
using name space std
int main ( ) {
char str1[40]
char str2[40]
cout<<’’enter the 1st string”<< end;
cin.getline (str1,40)
cout<< “enter the 2nd string “<< endl;
cin.getline (str2,40);
if (strcmp(str1,str2)==0);
cout<< string are same’1’;
else
cout<<’’string are not same”; IT Dep't Fundamental of
programming
C Library <strings.h> for String Operations
• char *strcpy(char *dst, char *src);
– Copies the string src to string dest
• char *strncpy(char *dst, char *src, int n);
– Copies the first n characters of src to dest
• char * strcat(*dst, char *src);
– Concatenate src to the end of dst.
• char * strcat(*dst, char *src, int n);
– Concatenate first n chars of src to end of dst.

IT Dep't Fundamental of
programming
Continued..
• int strcmp(char *str1, char *str2);
– Returns 0 if str1=str2, negative if str1<str2, positive if
str1>str2
• int strncmp(char *str1, char *str2, int n);
– Same as strcmp except it considers the first n chars of
each string
• int strlen(char *str); // returns the length of str
• char * strchr(char *str, int c);
Note.
– in strcpy, strncpy, strcat, and strncat, make sure that
the dst string has enough space to accommodate the
string copied or cancatenated to it
– If the strings are arrays, also make sure that the array
dst is large enough to accommodate the string
copied or concatenated to it
IT Dep't Fundamental of
programming
C-Strings (Character Arrays) (cont'd.)

IT Dep't Fundamental of programmin


g
Arrays of Strings
• Array of a string means two dimensional array of
character.
• example, char str[5][8];
• The first dimension tells how many stings are in the
array. The second dimension tells the maximum length
of each string.
• In above declaration we can store 5 strings each can
store maximum 7 characters, last 8th space for null
character in each string

IT Dep't Fundamental of
programming
Initialization of Array of string
• The array of string initialized like follow
• Example1. char str[2][7]=(“Sunday”,”Monday)
• Or like the following.
• Example2. char str[2][7]={{‘s’,’u,’n’,’d’,’a’,’y’},
{‘m’,’o’,’n’,’d’,’a’,’y’}}

IT Dep't Fundamental of
programming
Oromia State University

Department of IT

Fundamental of Programming

Chapter 6
Pointers
Lecture note

IT Dep't Fundamental of
programming
Pointers and dynamic objects

Topics
Pointers
Memory addresses
Declaration
Dereferencing a pointer
Reference
Computer Memory

• Each variable is assigned a memory slot (the


size depends on the data type) and the
variable’s data is stored there

Memory address: 1020 1024 1032

… … a
100 … 1024 …
Variable a’s value, i.e., 100, is
stored at memory location 1024
int a = 100;

IT Dep't Fundamental of
programming
Pointers
• A pointer is a variable used to store the address of a
memory cell.
• We can use the pointer to reference this memory
cell. Is a powerful technique by which we can access
data by indirect reference.
• Pointer is a data type that stores address values.
Memory address: 1020 1024 1032

… … 100 … 1024 …
integer
pointer

IT Dep't Fundamental of
programming
Pointer Types
• Pointer
– C++ has pointer types for each type of object
• Pointers to int objects
• Pointers to char objects
• Pointers to user-defined objects
(e.g., RationalNumber)
– Even pointers to pointers
• Pointers to pointers to int objects

IT Dep't Fundamental of
programming
Why we need pointers?
• Pointers are used to:
– Access array elements
– Passing arguments to functions when the
function needs to modify the original
argument
– Passing arrays and strings to functions
– Obtaining memory from the system
– Creating data structures such as linked lists

IT Dep't Fundamental of
programming
Pointer Variables
• A pointer variable is a variable that holds address
values
• Each data type has its own pointer variable, pointer to
int, pointer to double, pointer to char, …
• C/C++ uses the address-of operator( ”&”) to get the
address of any variable
• C/C++ uses the indirection or contents-of operator(*)
to access the value of the variable pointed by.
int i=17;
int* ptr; // defines a pointer to an integer variable
ptr= &i; // assign the address of x to pointer
cout << *ptr << endl; // prints contentsprogramming
of variable i
IT Dep't Fundamental of
Pointer Variables
int i;
0x1054
17
f
int *ptr;
s so
re
a dd f
nts o
nte
co
ptr=&i;

cout << *ptr << endl;

IT Dep't Fundamental of
programming
Pointer Variables con’t
int v; // defines variable v of type int
int w; // defines variable w of type int
int *p; // defines variable p of type pointer to int
p=&v; // assigns address of v to pointer p
v=3; // assigns value 3 to v
*p=7; // assigns value 7 to v
p=&w; // assigns address of w to pointer p
*p=12; // assigns value 12 to w

• Using the indirection operator *p to access the


contents of a variable is called indirect addressing or
dereferencing the pointer
IT Dep't Fundamental of
programming
Pointer variable con’t
• Pointer variable is defined to “Point to” data of a
specific type.
Example, int *ptr; // point to an int
• The value of a pointer variable is the address to which
it points. Example, int num;
• int *ptr1;
• Ptr1=&num
• The symbol & is address operator; it takes a variable as
argument and returns the memory address of that
variable.
• In the above the address of num is assigned to
ptr1.therfore, we can say that ptr1 is points to num.
IT Dep't Fundamental of
programming
Continued…

• int *p;
• int x;
• P=&x;
• X=5;
• The statement p=&x; assign the address of x
to p.
• The & is a unary operator that returns the
memory address of its operand.

IT Dep't Fundamental of
programming
Declaring pointers
• The declaration of pointers follows this:
• syntax:
Data_type * Variable_name;

where type is the data type pointed to by the


pointer. This type is not the type of the pointer
itself, but the type of the data the pointer points to.
For example:
int * number;
char * character;
double * decimals;
IT Dep't Fundamental of
programming
Continued…
• These are three declarations of pointers. Each one is
intended to point to a different data type, but, in
fact, all of them are pointers and all of them are likely
going to occupy the same amount of space in
memory (the size in memory of a pointer depends on
the platform where the program runs).
• Nevertheless, the data to which they point to do not
occupy the same amount of space nor are of the
same type: the first one points to an int, the second
one to a char, and the last one to a double.

IT Dep't Fundamental of
programming
Continued…
• Therefore, although these three example variables
are all of them pointers, they actually have different
types: int*, char*, and double* respectively,
depending on the type they point to.

Note that the asterisk (*) used when declaring a


pointer only means that it is a pointer (it is part of its
type compound specifies), and should not be
confused with the dereference operator seen a bit
earlier, but which is also written with an asterisk (*).
They are simply two different things represented
with the same sign.
IT Dep't Fundamental of
programming
Address Operator &
• The "address of " operator (&) gives the memory
address of the variable
– Usage: &variable_name

Memory address: 1020 1024

… … 100 … … …
a
int a = 100;
//get the value,
cout << a; //prints 100
//get the memory address
cout << &a; //prints 1024

IT Dep't Fundamental of
programming
Address Operator &
Memory address: 1020 1024 1032

… 88 100 … … …
a b
#include <iostream>
using namespace std;
Result is:
void main(){
The address of a is: 1020
int a, b; The address of b is: 1024
a = 88;
b = 100;
cout << "The address of a is: " << &a << endl;
cout << "The address of b is: " << &b << endl;
}

IT Dep't Fundamental of
programming
The Address-of Operator
• The address-of operator converts a name into a
pointer.
int i; // location for final value
int *p; // pointer variable
p = & i; // set p to point to i

cout<<p; // scan number into i

• Address-of operator can be applied directly in


arguments.
int i; // location for final value
cout<<&i); // scan number into i as
above
IT Dep't Fundamental of
programming
Pointer Variables
Memory address: 1020 1024 1032

… 88 100 … 1024 …
a p
int a = 100; Result is:
int *p = &a; 100 1024
cout << a << " " << &a <<endl; 1024 1032
cout << p << " " << &p <<endl;

• The value of pointer p is the address of variable a


• A pointer is also a variable, so it has its own memory address

IT Dep't Fundamental of
programming
Dereferencing Operator *
• We can access to the value stored in the variable pointed
to by using the dereferencing operator (*),

Memory address: 1020 1024 1032

… 88 100 … 1024 …
a p
int a = 100;
int *p = &a; Result is:
cout << a << endl; 100
cout << &a << endl; 1024
cout << p << " " << *p << endl; 1024 100
cout << &p << endl; 1032

IT Dep't Fundamental of
programming

Don’t get confused
Declaring a pointer means only that it is a pointer: int *p;
• Don’t be confused with the dereferencing operator, which
is also written with an asterisk (*). They are simply two
different tasks represented with the same sign
int a = 100, b = 88, c = 8;
int *p1 = &a, *p2, *p3 = &c;
p2 = &b; // p2 points to b
p2 = p1; // p2 points to a
b = *p3; //assign c to b
*p2 = *p3; //assign c to a
cout << a << b << c; Result is:
888

IT Dep't Fundamental of
programming
A Pointer Example

Memory Layout
The code
Box diagram
void doubleIt(int x,
main
int * p)
{ p 8192
a 16
*p = 2 * x; (8200)
} doubleIt
int main(int argc, const x 9
char * argv[]) (8196)
{
int a = 16; a 16 main
doubleIt(9, &a); doubleIt (8192)
return 0;
} x 9

a gets 18 p
IT Dep't Fundamental of
programming
Another Pointer Example
#include <iostream> Let’s figure out:
using namespace std; value1==? / value2==?
int main (){ Also, p1=? p2=?
int value1 = 5, value2 = 15;
int *p1, *p2;
p1 = &value1; // p1 = address of value1
p2 = &value2; // p2 = address of value2
*p1 = 10; // value pointed to by p1=10
*p2 = *p1; // value pointed to by p2= value
// pointed to by p1
p1 = p2; // p1 = p2 (pointer value copied)
*p1 = 20; // value pointed to by p1 = 20
cout << "value1==" << value1 << "/ value2==" << value2;
return 0;
}

IT Dep't Fundamental of
programming
Pointers to Simple Values

• Two major operations when a pointer is referencing a


primitive
– To dereference the pointer value
int i = 7;
int j = 11;
int *p = & i; // set p to point to i
int *q = & j; // set q to point to j
*p = *p + 3; // i now has the value 10
– Change pointer value to another pointer value
p = q; // i now has the value 10
• Pointers should be compared only for equality.
if (p == q) … while (p !=q) …
IT Dep't Fundamental of
programming
Pointers and const
• Modifier const indicates whether it is the pointer
itself or the value it points to that is constant.
int i = 7;
const int * p = &i; // pointer to a constant int
int * const q = &i; // constant pointer

const int *const ptr; //combine the first two


statement
*p = 8; // not allowed, p points to a const int
*q = 8; // allowed, q is pointing to non const
int
p = q; // allowed, p itself is not constant
q = p; // not allowed q is constant
IT Dep't Fundamental of
programming
Pointers and Arrays
• There is a close association between pointers and arrays
• Arrays can be accessed using pointers
• The name of an array is also a constant pointer to the data
type of the elements stored in the array

int array[5] = { 23, 5, 12, 34, 17 }; // array of 5 ints


for (int i=0; i< 5; i++)
cout << array[i] << endl; //using index to access elements
for (int i=0; i< 5; i++)
cout << *(array+i) << endl; // using pointer to access
elements
// array is of type pointer to
IT Dep't Fundamental of
programming
Pointers to Functions
• A function pointer can be invoked without the
dereference operator.
double fdiv (int i, int j) { return i / (double) j; }

double (*fptr) (int, int); // declare variable fptr


fptr = & fdiv; // assign value

double x = fptr(7, 14); // call ftpr directly


double x = (*fptr) (7, 14); // dereference ftpr and call

IT Dep't Fundamental of
programming
Pointers as Function Arguments
void swap( double& x, double& y)
{
double tmp=x;
x=y; // access variable by its alias name
y=tmp; }
void swap( double* ptr1, double* ptr2)
{ double tmp=*ptr1;
*ptr1=*ptr2; // de-referencing pointer
*ptr2=tmp; }
double a=3.0;
double b=5.0
swap(a,b); // call by reference to variables a and b
swap(&a, &b); // call by pointer using the addresses of a and b
IT Dep't Fundamental of
programming
void * Pointers

• A void pointer can reference any type of value.


double d;
double * dp = & d;

void * p = dp;
A void * parameter must always be cast before
it can be used.
double * dp2;
dp2 = (double *) p; // convert p back into
pointer to double

IT Dep't Fundamental of
programming
Reference
• A reference is an alias, an alternative way to
name an existing object.
• Difference between reference and pointers
– A reference can never be null; it must
always refer to a legitimate object.
– Once established, a reference can never be
changed to make it point to a different
object.
– A reference does not require any explicit
mechanism to dereference the memory
address and access the actual data value.
– A pointer is a variable that can contain a
reference IT Dep't Fundamental of
programming
References
• A reference is declared by using the
ampersand.
int i = 7;
int & j = i; // j is an alias for i
j++; // i is now 8
i += 3; // i is now 11, as is j
• A reference can be target of an assignment.
Some functions will return a reference as a
result for precisely this reason.
int values[100];
int & index(int i) {
return values[i + 2]; }
index(27) = 12; // changes values[29];
IT Dep't Fundamental of
programming
Chapter Seven

Function
• Modular programming
– Breaking down the design of a program into individual
components (modules) that can be programmed and tested
independently
– A program divided into several smaller parts which can
interact
• Modules [functions]
– Can be written and tested separately
– Testing is easier (smaller)
– Doesn't need to be retested
– Reduces length of program
– Hides details (abstraction)
Functions in C++
 Modules in C++ are called functions
 Function - a subprogram that can act on data and return a value
 Every C++ program has at least one function, main(), where
program execution begins
 A C++ program might contain more than one function.
 Functions may interact using function call
 Functions in C++ come in two varieties:
– user-defined

– built-in
• E.g pow(), sqrt(), cin, etc
Declaration of Functions
 Functions must be declared before use
 The declaration tells the compiler
– Return type,
– Function name,
– Parameters of the function
… Declaration of Functions
 The declaration of a function is called function prototype
 Is a statement - it ends with a semicolon
 It consists of the function's
– return type,
– name,
– parameter list
• Syntax
– return_type function_name (type [parameterName1], type
[ParameterName2] ... );
• E.g. long Area(int, int);
Or
long Area(int length, int width);
Defining a Function
 The definition tells the compiler how the function
works.
 Consists of :
– the function header :
• like the function prototype except that the parameters must be named
• there is no terminating semicolon
– its body
• the task of the function
 Syntax
return_type function_name(parameter
declarations)
{
declarations;
statements;
}
Defining a Function

E.g.
long Area(int l, int w)
{
return l * w;
}
Calling Function
Syntax :
FunctionName (actual parameter lists);

E.g. Area(int l, int w);


// Creating and using a programmer-defined function.
#include <iostream.h>
Function prototype: specifies data types
int square( int ); // function prototype of arguments and return values.
square expects an int, and returns
int main() an int.
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call

cout << endl; Parentheses () cause function to be called.


When done, it returns the result.
return 0; // indicates successful termination

} // end main

// square function definition returns square of an integer


int square( int y ) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
Definition of square. y is a
copy of the argument passed.
} // end function square Returns y * y, or y squared.

1 4 9 16 25 36 49 64 81 100
#include<iostream.h>
Using namespace std; Example
float RectArea(float,float);
int main()
{
float l,w;
cout<<“Enter the Length of the rectangle"<<endl;
cin>>l;
cout<<“Enter the width of the rectangle"<<endl;
cin>>w;
cout<<"The area is "<<RectArea(l,w);
return 0;
}
float RectArea(float length,float width)
{
float area=length * width;
return area;
}
Scope of identifier
 Refers to where in the program an identifier is
accessible
 Determines how long it is available to your program
and where it can be accessed
 Two kind
– Local identifier - identifiers declared within a function (or
block)
– Global identifier – identifiers declared outside of every
function definition
Local scope
 You can declare variables within the body of the
function
– local variables
– When the function returns, the local variables are no longer
available
 Variables declared within a block are scoped to that
block – Local to that block
– they can be accessed only within that block and "go out of
existence" when that block ends
– E.g.
for(int i = 0;i<5; i++)
cout<<i;
i=+10; // compilation error i is inaccessible
Global Scope

 Variables defined outside of any function have


global scope
 Available from any function in the program,
including main()
 A local variable with the same name as a global
variable hides the global variable - when used
within the function
#include <iostream.h>
Output
void myFunction(); // prototype
int x = 5, y = 7; // global variables
int main() x from main: 5
y from main: 7
{
cout << "x from main: " << x << "\n"; x from myFunction: 5
cout << "y from main: " << y << "\n\n"; y from myFunction: 10
myFunction(); Back from myFunction!
cout << "Back from myFunction!\n\n"; x from main: 5
cout << "x from main: " << x << "\n"; y from main: 7
cout << "y from main: " << y << "\n";
return 0;
}
void myFunction()
{
int y = 10;
cout << "x from myFunction: " << x << "\n";
cout << "y from myFunction: " << y << "\n\n";
}
Parameter Passing

 Call by Value
– Value of the function argument passed to the
formal parameter of the function
– Copy of data passed to function
– Changes to copy do not change original
 Call by Reference
– Address of the function argument passed to the
formal parameter of the function

You might also like