0% found this document useful (0 votes)
16 views38 pages

Chapter 4

Uploaded by

asnak
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)
16 views38 pages

Chapter 4

Uploaded by

asnak
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/ 38

CHAPTER FOUR

Array and String


Outline
⚫ Introduction
⚫ Declaration and Initialization of Arrays
⚫ Accessing Elements of Arrays
⚫ Multidimensional Arrays
⚫ Arrays as parameters
⚫ Pointers and Arrays
⚫ Strings
Introduction
• Array
– So far we have used variables to store values in memory for
later reuse .
– we now explore a means to store multiple values together as
one unit, the array.
– Array is a fixed number of elements of the same data type
stored in sequentially in memory.
– Therefore, an integer array holds some number of
integers, a character array holds some number of
characters, and son .
Array Declaration
• Like a regular variable, an array must be declared before it is used.
• /yntax: dataType arrayName [elements];
– Data type a type of elements (like int, float...),
– name is a valid identifier
– the elements field (which is always enclosed in square brackets []),
specifies how many of these elements the array has to contain.
• must be a constant value

• Example: int num[5];// an integer array with 5 elements


Initialization of Arrays
• use an “initializer List” enclosed in braces to quickly insert values in your array
• There are several ways to initialize the array. one way is to declare the array and then
initialize some or all elements .
• int arr[3];
arr[0]=6;
arr[1]=0;
arr[2]=9;
• Another way is to initialize some or all of the value at the time of declaration:
• int arry[4]={6,0,9,6};
• Sometimes it is more convenient to leave out the size of the array and let the compiler
determine the array size for us based on how many elements we give it: int
arry[]={6,0,9,6,2,0,1,1};
• The complier will create an integer array of dimension.
Accessing the values of an array.
• You access an array element by referring to the index number
inside square brackets []
• Arrays in C++ are zero-indexed, so the first element has an
index of 0:[0], the second element index1:[1],etc.
• Example int num[5]; in this example num [0] refers to the
first element and num[4] refers to the last element.
• To access the 3rd element in array , we write arr[2];the value
returned can then be used just like any other integer.
Example
#include <iostream>
using namespace std;
int main() {
// Declaring an array of integers with 5 elements
int numbers[5] = {10, 20, 30, 40, 50};//initialize with specific
value
// Accessing elements of the array using a loop
cout << numbers[4];
return 0;
Output 50
}
NB. array are fixed size in C++ ,you can’t change the size
once declared .
Modify an array element
• To change the value of a specific element, refer to the index
number:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
Exercise
· Which set of data would not be suitable for
storing in an array?
 the score for each Football match

 your name, date of birth, and score on your


physics test
 temperature readings taken every hour throughout
a day
 your expenses each month for an entire year
Two dimensional Arrays

⚫ Two dimensional arrays can be described as "arrays of arrays“


 Each element of the 2-D array is accessed by
providing two indexes:
 a row index and a column index

 called as a an array of arrays

0 1
0 8 4
1 9 7
2 3 6

• value at row index 2, column index 0 is 3


Cont’d …
• A 2-d array is an array in which each element is itself an array
• It have a number of rows and columns
 i.e: int num[4][3];

size of 2-D array

 Total bytes= no of rows*no of columns*size of(base type)


 We declare a 2D array two sets of square brackets:
double height[20] [55];

 This 2D array has 20 rows and 55 columns

27
Initialize Two Dimensional Array in C++
· The general form to initialize values to two dimensional array in C++

· Sintax:
data_type array_name[row_size][column_size]
= { {comma_separated_value_list} };

Example:- declaring and initializing values to two dimensional


array named arr of type int, containing 5 row and 2 column i.e.,
dimension of this array is 5*2

int arr[5][2] = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };

21
Cont’d …
Out put

22
C++ Multidimensional Arrays
 The multidimensional array is also
known as rectangular arrays in C++.

 It can be two dimensional or three


dimensional.
 The data is stored in tabular form (row ∗
column)
which is also known as matrix.

N.B: Read about multi dimensional array


Strings
• Strings are the combination of characters. In other words,
you can think strings as an array of characters.
• A string variable contains a collection of characters
surrounded by double quotes
• Examples: “hello”, “high school”, “H2O”.

· C++ has a <string> library


· To use strings, Include an additional header file in the
source code, the <string> library.
· In this library, a class string is defined and
implemented.
24
Cont.
· The + operator can be used between strings to add them together to
make a new string .This called Concatenation:
· “high”+“school”=“highschool”

• Comparison:“high”<“school”// alphabetical

• Finding/retrieving/modifying/deleting/inserting substrings in a given


string

25
Declaration of strings
· The following instructions are all equivalent.
· They declare x assign the string “high school” to it:
 string x= “high school”;
 string x;
x=“high school”;

26 CS_Dept @ DDIT
Operations on strings
Concatenation
· Let x and y be two strings
· To concatenate x and y, write: x+y;
· string x= “high”;
· string y= “school”; O utput
string z; z=highschool
· z=x+y; z= highschool was fun
· cout< < “z= “< <z<< endl;
· z =z+“ was fun”;
· cout< < “z= “< <z<< endl;

27
C++ String Example
#include <iostream>
#include<string>
using namespace std;
int main( ) {
string s1 = "H ello";
char ch[] = { 'C', '+', '+'};
string s2 = string(ch); Output:
Hello
cout<<s1<<endl;
} cout<<s2<<endl;

C++
C++ String Concatenation Example
#include <iostream>
#include <cstring> Output:
using namespace std;
Enter the key string:
int main()
Welcome to
{
Enter the buffer string:
char key[25], buffer[25];
C++ Programming.
cout < < "Enter the key string: ";
cin.getline(key, 25); Key = Welcome to C++
Programming.
cout < < "Enter the buffer string: ";
cin.getline(buffer, 25); Buffer = C++
Programming.
strcat(key, buffer);
cout < < "Key = " < < key < < endl;
cout << "Buffer = " << buffer<<endl;
return 0;
}
String comparison
• comparing strings is very simple using the built-in comparison
operators like ==, !=, <, >, <=, >=, and the compare() method.
• Example

Out put
str1 is lexicographically less than str2
C++ String Compare Example

O utput:
What is my favorite fruit?
Apple
What is my favorite fruit?
banana
What is my favorite fruit?
mango
Answer is correct!!
C++ String Copy Example
#include <iostream>
#include <cstring> Output:
using namespace std;
int main(){ Enter the key string:
C++ Program
char key[25], buffer[25]; Key = C++ Program
cout < < "Enter the key string: "; Buffer = C++ Program

cin.getline(key, 25); strcpy(buffer,


key);
cout << "Key = "<< key << endl;
cout < < "Buffer = "<< buffer<<endl;
return 0;
}
C++ String Length Example
#include <iostream>
#include <cstring> using
namespace std; int main(){
char ary[] = "Welcome to C++ Programming"; cout < <
"Length of String = " < <
strlen(ary)<<endl;
return 0;
}
Output:
Length of String = 26
C++ Pointers
· A pointer is a variable, it is also known as locator or indicator that
points to an address of a value.
· A pointer is a variable whose value is the address of another
variable with the same type.
· Like any variable or constant, you must declare a pointer before
you can work with it.
· The general form of a pointer variable declaration is type * var-
name;
Cont’d …

Example: int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; //pointer to a float
char *ch; // pointer to character

· A pointer is a variable that holds the memory address of


another variable of same type.
• This memory address is the location of another variable
where it has been stored in the memory.
· It supports dynamic memory allocation schedules.

3
Cont’d …
Advantage of pointer
· Reduces the code and improves the performance.
 It is used to retrieving strings, trees etc. and used with
arrays, structures and functions.

· We can return multiple values from function using


pointer.

· It makes you able to access any memory location in the


computer's memory.
Cont’d …

Symbols used in pointer


Symbol Name Description
 & • Determine the
• Address
(ampersand address of a
operator
sign) variable.
 ∗ (asterisk • Indirection • Access the value of
sign) operator an address.
Declaring a pointer
 The pointer in C++ language can be declared using ∗
(asterisk symbol).
Example: int ∗ a; //pointer to int
char ∗ c; //pointer to char
Cont’d …
 A pointer is a variable which holds the memory
address of another variable.
 used for sorting the address of a memory cell.

 We can use the pointer to reference this memory cell.

37
Cont’d …
Address of operator(&)
· It is a unary operator that returns the memory
address of its operand.
· Here the operand is a normal variable.
Eg. int x = 10;
int *ptr = &x;

· Now ptr will contain address where the variable


9 x is stored in memory.
Cont’d …
· The “address of ” operator (&) gives the memory
address of the variable.
· Usage: &variable name;

Example:
int a=100;
// to gets the value, use the variable name

cout<<a; //prints 100


//To get the memory address, add the address operator before
the variable name

cout<<&a; //prints 1024


10
Cont’d …

Example:
int a=100;
int
*p=&a;
cout<<a<<” ”<<&a<<endl;
//prints a=100 and &a=1024
cout<<p<<” ”<<&p<<endl;
//prints P=1024 and &P=1032
• The variable of pointer p is the address of variable a
• A pointer is also a variable, so it has its own memory address
Cont’d …
Dereference operator (*)
• It is a unary operator that returns the value stored at the
address pointed to by the pointer.
• Here the operand is a pointer variable.

· Example:
int x = 10;
int *ptr = &x;
cout<< ptr;
// address stored at ptr will be displayed
cout<<*ptr;
// value pointed to by ptr will be displayed
· Now ptr can also be used to change/display the value of x.
41
Cont’d …

· We can access to the value stored in the variable pointed


to by preceding the pointer with “star” reference operator (*)
• Example1: based on the above figure
• int a =100; int
*p=&a; // prints 100

• cout<<a<<endl; cout<<&a<<endl;
// prints 1024
cout<<p<<” “<<*p<<endl;
// prints 1024 and 100 respectively
cout<<&p<<endl;
// prints 1032
42
Cont’d

· Example:

43
Cont’d …

Output: value1=5 and value2 = 20


44
Explanation of the above example

• Before p1 = p2:
• p1 points to the address of value1 (p1 = &value1).
• p2 points to the address of value2 (p2 = &value2).
• After p1 = p2:
• p1 no longer points to value1. Instead, it now points to the
same address as p2 (the address of value2).
• From this point on, any operation on *p1 (the value pointed
to by p1) will affect value2, because both p1 and p2 refer to
value2.
NULL Pointer

· NULL pointer is a special value that indicates an


empty pointer

· Example:
int* ptr = nullptr;
if (ptr == nullptr) {
cout << "Pointer is null." << endl;
}

You might also like