0% found this document useful (0 votes)
11 views56 pages

Chapter 5 Finall

Uploaded by

abraham worku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views56 pages

Chapter 5 Finall

Uploaded by

abraham worku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

The image part with relationship ID rId13 was not found in the file.

Chapter 5: Array, Strings & Pointers

By Bizuayehu T.(Msc)

April 17, 2024


Arrays
üAn array is a collection of similar items stored in contiguous memory locations. In
programming, sometimes a simple variable is not enough to hold all the data.

üAn array is a collection of a fixed number of components all of them have same
data type.

ü C++ provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type.

ü An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
4/17/24 2
Array declaration
datatype arayname[intexpr];

§ In which intExp is any constant expression that evaluates to a positive integer. Also, intExp
specifies the number of components in the array

§ Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by
an index.

§ Example
§ Int num[5];
4/17/24 3
Array Declaration…
§ The above statement declares an array num of five components. Each
component is of type int.
§ The components are num[0], num[1], num[2], num[3], and num[4]. The
following figure illustrates the array num.

4/17/24 4
Array Declaration…

4/17/24 5
Accessing array elements
§ An element is accessed by indexing the array name.
§ This is done by placing the index of the element within square brackets
after the name of the array
§ Array index starts with 0, which means the first array element is at index 0,
second is at index 1 and so on

4/17/24 6
Example

4/17/24 7
Multidimensional array
§ Previously we discussed about one dimensional array, that is,
single variables specify array.
§ C++ allows programmer to create array of an array known as
multidimensional arrays. Here is the general form of a
multidimensional array declaration:
§ General form
§ type name[size1] [size2] [size3]…….. [sizeN];
§ E.g. int twodim[5] [10];

4/17/24 8
Multidimensional array…
§ Multidimensional arrays are also known as array of arrays. The
data in multidimensional array is stored in a tabular form as
shown in the diagram below

4/17/24 9
Two-Dimensional Arrays
§ Declaring a two dimensional array

§ This array has total 2*3 = 6 elements.????

4/17/24 10
Initialization of two dimensional array

4/17/24 11
4/17/24 12
Strings
§ Strings are words that are made up of characters, hence they are known as
sequence of characters.
§ Strings are used to represent successive characters such as words,
sentences, names, and texts.
§ In C++, there is no specific elementary variable type to store strings of
characters.
§ Arrays of type char can be used to store strings of characters, as char is
used to store a single character.
§ Arrays of characters are generally used to create strings of single characters.
§ A string of characters can be stored in an array, such as char name[20],
which can store a string up to 20 characters long.

4/17/24 13
Cont..
§ The maximum size of the array does not have to be fully used; it can store shorter strings.
§ A convention is to end the valid content of a string with a null character ('\0').
§ The null character indicates the end of the string, and its constant is written as '\0'.
§ The representation of the array name storing the strings "Hello" and "Studying C++"
would be:

§ After the valid content, a null character is included to indicate the end of the
string.
§ In C++ we have two ways to create and use strings
1. By creating char arrays and treat them as string
2. By creating string object
4/17/24 14
Initialization of Strings
§ Strings of characters follow the same rules as any other array.
§ Strings can be initialized in a similar way to other arrays using curly
braces and character values: char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
§ The example above declares a string (array) of 6 elements of type
char, initialized with the characters that compose "Hello" plus a null
character ('\0').

4/17/24 15
Constant Strings for Initialization
§ Strings of characters can also be initialized using constant strings.
§ Constant strings are specified enclosed between double quotes ( " ): e.g., "the
result is: ".
§ Unlike single quotes (' '), which specify single character constants, double quotes
(" ") specify a succession of characters.
§ Constant strings enclosed between double quotes always have a null character
('\0') automatically appended at the end.
§ Therefore, the string mystring can be initialized in two ways:
§ char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
§ char mystring[] = "Hello";
§ In both cases, the array mystring is declared with a size of 6 characters: the 5
characters that compose "Hello" plus a final null character ('\0').

4/17/24 16
Assigning Values to Strings
§ Arrays, including arrays of characters, can store values using assignment
operators.
§ Assigning a string using the equal sign (=) is only allowed during initialization,
not afterwards.
§ Valid assignments to an array of char involve assigning values to individual
elements of the array:
§ mystring[0] = 'H';
§ mystring[1] = 'e';
§ mystring[2] = 'l';
§ mystring[3] = 'l';
§ mystring[4] = 'o';
§ mystring[5] = '\0';

4/17/24 17
Cont..
§ Method of Assigning Values to an Array:

§ Common method involves using functions like strcpy

§ strcpy (string copy) is defined in the string.h library

§ Syntax: strcpy(string1, string2)

§ Copies the content of string2 into string1

§ string2 can be an array, a pointer, or a constant string

§ Example: strcpy(mystring, "Hello") assigns the constant string "Hello" to


mystring

4/17/24 18
Example
For example:
#include <iostream.h>
#include <string.h>
int main ()
{
char szMyName [20];
strcpy (szMyName,"Abebe");
cout << szMyName;
return 0;
}

4/17/24 19
Array of Characters

4/17/24 20
Example 2: Getting user input as string

4/17/24 21
Method of Assigning Values to an Array using cin
• Another method is using the input stream (cin) directly

• Allows the user to assign a value to the array during program execution

• getline method with cin:

• Typically used with strings of characters

• Prototype: cin.getline(char buffer[], int length, char delimiter = '\n')

• buffer: Address where the input will be stored (e.g., an array)

• length: Maximum length of the buffer (size of the array)

• delimiter: Character used to determine the end of the user input (default: '\n')

4/17/24 22
Example cin with strings
#include <iostream.h>
#include<conio.h>
int main (){
char mybuffer [100];
cout << "What's your name? ";
cin.getline (mybuffer,100);
cout << "Hello " << mybuffer << ".\n";
cout << "Which is your favourite team? ";
cin.getline (mybuffer,100);
cout << "I like " << mybuffer << " too.\n";
getch();
return 0;
}
4/17/24 23
Limitations of cin with Strings
§ In the previous section, we used the extraction operator (>>) to receive data from
standard input
§ This method can be used with strings but has limitations compared to cin.getline
§ Limitations of cin method:
§ Can only receive single words, not complete sentences
§ Uses any occurrence of a blank character (spaces, tabulators, newlines, carriage returns) as a
delimiter
§ Does not allow specifying a size for the buffer
§ Can make the program unstable if the user input exceeds the size of the array
§ Recommendation to Use cin.getline:
§ It is recommended to use cin.getline instead of cin >> for receiving strings of characters from
cin
§ cin.getline provides advantages over cin:
§ Can handle complete sentences
§ Allows specifying a size for the buffer, ensuring program stability
4/17/24 24
Converting Strings to Other Types
§ Strings may contain representations of other data types like numbers
§ Translating the content of a string to a variable of a numeric type can be useful
§ The cstdlib (stdlib.h) library provides three functions for this purpose:
§ atoi: Converts a string to int type
§ atol: Converts a string to long type
§ atof: Converts a string to float type
§ All of these functions take a string parameter and return a value of the requested
type (int, long, or float)
§ Advantages of using these conversion functions with getline:
§ Combined with the getline method of cin, these conversion functions provide a
more reliable way to get user input when requesting a number
§ Using these functions is preferred over the classic cin >> method for number
input
4/17/24 25
Example
// cin and ato* functions
#include <iostream.h>
#include <stdlib.h>
#include<conio.h>
int main() {
char mybuffer[100];
float price;
int quantity;
cout << "Enter price: ";
cin.getline (mybuffer,100);
price = atof (mybuffer);
cout << "Enter quantity: ";
cin.getline (mybuffer,100);
quantity = atoi (mybuffer);
cout<<"\nafter conversion :\n";
cout<<"\nprice is : "<<price;
cout<<"\nquantity is : "<<quantity;
cout << "\nTotal price: " << price*quantity;
getch();
return 0;
4/17/24 } 26
Functions to Manipulate Strings
§ String Length:
§ Returns the length of a string, excluding the null character ('\0')
§ Prototype: strlen(const char* string)
§ String Concatenation:
§ Appends the source string at the end of the destination string
§ Returns the destination string
§ Two forms of concatenation:
§ Appending the whole content of the source
§ Prototype: strcat(char* dest, const char* src)
§ Appending part of the source
§ Prototype: strncat(char* dest, const char* src, int size)
§ 'size' is the number of characters to be appended
4/17/24 27
Cont..
§ String Copy:
§ Overwrites the content of the destination string with the source string
§ Returns the destination string
§ Two forms of copying:
§ Copying the whole content of the source:
§ Prototype: strcpy(char* dest, const char* src)
§ Copying part of the source:
§ Prototype: strncpy(char* dest, const char* src, int size)
§ 'size' is the number of characters to be copied
§ String Compare:
§ Compares two strings: string1 and string2
§ Two forms of comparison:
§ Comparing the whole content of the two strings:
§ Prototype: strcmp(const char* string1, const char* string2)
4/17/24 28
Cont..
§ Comparing part of the two strings:

§ Prototype: strncmp(const char* string1, const char* string2, int size)

§ 'size' is the number of characters to be compared

§ Both string comparison functions return three different values:

§ Returns 0 if the strings are equal

§ Returns a negative value if the first string is less than the second string

§ Returns a positive value if the first string is greater than the second string

4/17/24 29
Pointers
§ When a variable is declared, a specific block of memory within the computer is
allocated to hold the value of that variable.

§ The size of the allocated block depends on the data type.

§ In C++, every value is stored somewhere in memory and can therefore be identified
with that address. Such addresses are called pointers.

§ A pointer is a variable which stores the address of another variable.

§ They have data type just like variables, for example an integer type pointer can hold
the address of an integer variable and a character type pointer can hold the address of
char variable.
4/17/24 30
Pointers…
§ The only difference between pointer variable and regular variable is
the data they hold.

§ A pointer is simply the address of an object in memory. Generally,


objects can be accessed in two ways: directly by their symbolic name,
or indirectly through a pointer.

§ We will use terms r value and l value for the value and the address of
the variable, respectively.
4/17/24 31
Pointers…
üThe r value appears on the right side of the assignment statement while l value on the
left.
ü Therefore, writing 10 = k; is illegal. If we write,
§ int x, y;
§ x = 10;
§ y = x; then, we have two integer variables x and y.

ü The compiler reserves memory for the integer variable x and stores the rvalue 10 in
it.
ü When we say y = x, then x is interpreted as its rvalue since it is on the right hand side
of the assignment operator =.
4/17/24 32
Declaring Pointers
üLike all variables, pointers must be declared before they can be used to store an address.

ü When you declare a pointer variable, C++ requires also specifying the type of variable
that’s pointed to.

ü The general syntax of declaring pointer variables can be given as below.

Syntax: datatype * varname ;


§ Here, type is the pointer's base type; it must be a valid C++ type and varname is the
name of the pointer variable.
§ The asterisk you used to declare a pointer is the same asterisk that you use for
multiplication.
§ However, in this statement the asterisk is being used to designate a variable as a pointer.

4/17/24 33
Declaring Pointers
üHere, data_type is the data type of the value that the pointer will point to.
For example,

int *pnum;

char *pch;

float *pfnum;

§ In each of the above statements, a pointer variable is declared to point to a


variable of the specified data type.

4/17/24 34
Pointer Operators
üC++ includes two built-in operators for working with pointers:

v The address-of operator (&) is written before a variable name (or any
expression to which you could assign a value) and returns the address
of that variable. Thus, the expression &total gives the address of total
in memory.

v The dereference operator (*) is written before a pointer expression


and returns the actual value to which the pointer points.
4/17/24 35
Pointer Operators…
ü Suppose, for example, that you have declared and initialized the following variables:

double x = 2.5;

double *px = &x;

ü At this point, the variable px points to the variable x, and the expression *px is
synonymous with the variable x.

üN.B: the * appears before a pointer variable in only two places: when you declare a
pointer variable and when you dereference a pointer variable (to find the data it points
to).

4/17/24 36
Declaration of pointer

4/17/24 37
4/17/24 38
Example

4/17/24 39
Pointer to Void
§ Limitations of Assigning Addresses to Pointers of Different Types
§ It is not possible to assign the address of a float variable to an integer pointer
variable
§ Similarly, the address of an integer variable cannot be stored in a float or
character pointer
Example:
float y;
int x;
int *ip;
float *fp;
ip = &y; // Illegal statement
fp = &x; // Illegal statement
§ Address assignment is only allowed if the variable type and pointer type are
the same
4/17/24 40
Cont…
§ Using a Void Pointer
§ In C++, it is possible to assign the address of a variable to a pointer variable of the
void type
Syntax: void *p;
Example:
void *p;
int x;
float y;
p = &x; // Valid assignment
p = &y; // Valid assignment
§ Void pointers are designed to store addresses and can be assigned addresses of variables of different
types
§ Limitations of Void Pointers
§ Void pointers cannot be dereferenced
§ They are used only for storing addresses
§ The dereference operator (*) cannot be used with void pointers
4/17/24 41
Arrays of Pointers
§ Declaring an Array of Pointers

§ If you need to reserve multiple pointers for different values, you can declare an array
of pointers

§ Example: int *iptr[10]; // Reserves an array of 10 integer pointers

§ The above statement creates a structure in RAM to hold the array of pointers

§ Assigning Addresses to Array of Pointers

§ Each element of the array can be assigned the address of a variable

§ Example: iptr[4] = &age; // Makes iptr[4] point to the address of age

§ The element at index 4 of the iptr array is assigned the address of the variable age

4/17/24 42
Pointer and Arrays
§ Relationship between Arrays and Pointers
§ The identifier of an array is equivalent to the address of its first element
§ Similarly, a pointer is equivalent to the address of the first element it points to
§ Arrays and pointers are essentially the same thing in this context
§ Example:
int numbers[20];
int *p;
Valid allocation: p = numbers;
§ After the assignment, p and numbers are equivalent and have the same properties
§ However, p can be assigned another value, while numbers will always point to the
first element of the array

4/17/24 43
Cont…
§ Array as a Constant Pointer
§ Unlike p, which is an ordinary variable pointer, numbers is a constant pointer
(array)
§ Assignment numbers = p; is not valid because numbers is a constant identifier
§ No values can be assigned to constant identifiers
§ Array Name as a Pointer
§ An array name is just a pointer that always points to the first element stored in the
array
Example:
int ara[5] = {10,20,30,40,50};
cout << *(ara + 2); // Prints ara[2]
§ The expression *(ara + 2) is valid since ara is a pointer to the first element
§ It takes the address stored in ara, adds 2 to the address, and dereferences that location
4/17/24 44
Cont…
§ Character Array Example

§ Consider the character array: char name[] = "C++ Programming";

§ Outputs of the following cout statements:

cout << name[0]; // Output: C

cout << *name; // Output: C

cout << *(name + 3); // Output: P

cout << *(name + 0); // Output: C

4/17/24 45
Pointer Advantage
§ Inability to Change Array Names

§ Array names are constants, and their values cannot be changed

§ Assigning a new value to an array during program execution is invalid

§ Example: Cname = "Football"; // Invalid array assignment

§ Ability to Change Pointer Variables

§ Pointers, unlike arrays, can have their values changed

§ Pointers can be made to point to different values in memory

4/17/24 46
Cont…
Example:
void main(){
float v1 = 679.54;
float v2 = 900.18;
float *p_v;
p_v = &v1;
cout << "\nThe first value is " << *p_v;
p_v = &v2;
cout << "\nThe second value is " << *p_v;
getch();
}

4/17/24 47
Cont…
§ Using Pointers as Arrays
§ Pointer notation can be used interchangeably with array notation
§ Example program demonstrating arrays and pointer notation:
void main() {
int ctr;
int iara[5] = {10, 20, 30, 40, 50};
int *iptr;
iptr = iara; // Makes `iptr` point to the array's first element (or `iptr = &iara[0]`)
cout << "Using array subscripts:\n";
cout << "iara\tiptr\n";
for (ctr = 0; ctr < 5; ctr++)
{
cout << iara[ctr] << "\t" << iptr[ctr] << "\n";
}
cout << "\nUsing pointer notation\n";
for (ctr = 0; ctr < 5; ctr++)
{
cout << *(iara + ctr) << "\t" << *(iptr + ctr) << "\n";
}
getch();
4/17/24
} 48
Cont…
§ Storing and Printing a Person's Name using a Character Pointer
§ Instead of using arrays, a character pointer can be used to store and print a
person's name
§ Example:
void main()
{
clrscr();
char *c = "Meseret Belete";
cout << "Your name is: " << c;
}

4/17/24 49
Pointer Arithmetic
§ Arithmetical Operations on Pointers
§ Pointers support addition and subtraction operations
§ Other arithmetic operations have no meaning in the context of pointers
§ Behavior of Addition and Subtraction
§ Pointers behave differently in arithmetic operations based on the size of the data
type they point to
§ Different data types occupy different amounts of memory
§ Example: char occupies 1 byte, short occupies 2 bytes, and long occupies 4
bytes
Example Pointers:
Suppose we have the following pointers:
char *mychar;
short *myshort;
long *mylong;
• Assume these pointers point to memory locations 1000, 2000, and 3000 respectively

4/17/24 50
Cont…
§ Pointer Arithmetic with Addition

§ When we perform mychar++, it means adding 1 to mychar

§ mychar would then contain the value 1001

§ Similarly, myshort++ would result in myshort containing the value 2002

§ Likewise, mylong++ would result in mylong containing the value 3004

§ Adding 1 to a pointer makes it point to the following element of the same type,
taking into account the size in bytes of the type pointed to

4/17/24 51
Cont…

4/17/24 52
Cont…
§ Pointer Arithmetic with Subtraction

§ Subtraction works similarly to addition

§ Subtracting 1 from a pointer makes it point to the preceding element of the


same type, considering the size in bytes of the type pointed to

4/17/24 53
Cont…
§ Example:
void main()
{
int iara[] = {10,20,30,40,50};
int * ip = iara;
cout<<*ip<<endl;
ip++;
cout<<*ip<<endl;
ip++;
cout<<*ip<<endl;
ip++;
cout<<*ip<<endl;
}

4/17/24 54
Reading Assignment
§Pointer and array
§Pointer to pointer

4/17/24 55
Thank You!

4/17/24
? 56

You might also like