You are on page 1of 35

Chapter 3

Array and string

1
Introduction
Variables in a program have values associated with them.

During program execution these values are accessed by using the identifier
associated with the variable in expressions.

If there were 10000 values imagine the tedium of typing the program and
making up variable names and remembering which is which.

To get round this difficulty all high-level programming languages use the
concept of a data structure called an Array.

2
Arrays
An array is a variable that can store multiple values of the same type.

An array is a series of elements of the same type placed in contiguous


memory locations that can be individually referenced by adding an index
to a unique identifier.

Represented as a group of consecutive memory locations .

To refer to a particular location or element in the array, we specify the


name of the array and the position number of the particular element in
the array.

Each element of an array is accessed by its index. 3


 For example 1 , an array to contain 5 integer values of type int called foo could be represented like this

 where each blank panel represents an element of the array. These elements are numbered from 0 to 4, with 0

being the first while 4 being the last;

 In C++, the index of the first array element is always zero.

 For example 2: Suppose a class has 27 students, and we need to store the grades of all of them.

 Instead of creating 27 separate variables, we can simply create an array.

 Like a regular variable, an array must be declared before it is used.

 A typical declaration for an array in C++ is: Type array_Name [ size ];


 typical declaration for the above examples:
 example 1 => int foo[5];
 example 2 => double grade[27]; 4
Types of Array

One Dimensional Array


Multidimensional arrays

5
One Dimensional Array

• This type of array, stores elements in a single dimension. And, in this


array a single specification is required to describe elements of the
array.
0 1 2 3 4

• The diagram above shows that it arranged all the elements in row wise
in a single dimension, one after other

6
Declaration:
 Before using the array in the program it must be declared

Syntax: data_type array_name[size];

data_type represents the type of elements present in the array.

 array_name represents the name of the array.

Size represents the number of elements that can be stored in the array.
The Size must be an integer constant greater than zero.

7
Examples-
int A[10];
• An array of ten integers .

Char str[20];
• An array of twenty characters .

 int a[ 100 ], b[ 27 ] ;
• Defining multiple arrays of same type .

8
 Initialization:
 We can explicitly initialize arrays at the time of declaration.

Syntax: data_type array_name[size]={value1, value2,……..valueN};

Value1, value2, valueN are the constant values known as initializers, which
are assigned to the array elements one after another.
 Example: Define an array temperature of 5 elements contains float numbers , and

Initialize it with these numbers : 12.3 , 7.5 , 65 , 72.1, 87.5 .

9
 float temperature [5] = {12.3 , 7.5 , 65 , 72.1, 87.5 };

temperature [0] 12.3

temperature [1] 7.5

temperature [2] 65.0 Elements

temperature [3] 72.1

temperature [ 4 ] 87.5

Index 10
Initializing Arrays
 int N[ ] = { 1, 2, 3, 4, 5 };
• In 1-D arrays it is optional to specify the size of the array. If size is omitted during
initialization then the compiler assumes the size of array equal to the number of
initializers.
 int N[5] = { 0 } ;
 int B[20] = {2, 4, 8, 16, 32};
• Unspecified elements are guaranteed to be zero .
• If not enough initializers, rightmost elements become 0 .
 int C[4] = {2, 4, 8, 16, 32};

• Error — compiler detects too many initial values .


11
Accessing Array Elements
An individual element within array is accessed by use of a

subscript (index) that describes the position of an element

in the array , it must be an integer or integer expression .

• We can’t copy the elements of one array to another array

by simply assigning it. Example: int a[5]={9,8,7,6,5};

• int b[5]; b=a; //not valid

• we have to copy all the elements by using for loop


12

const int SIZE=10
 x=y; // Error - Illegal
 int x [SIZE] ;

 int y [SIZE] ;

 Only individual elements can be assigned to using the index operator,

 e.g., 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.
for (int i = 0 ; i < SIZE; i++) // Loop to do copying, one element at a time

x[i] = y[i];

 This code will copy the elements of array y into x, overwriting the original contents of x. A loop

like this has to be written whenever an array assignment is needed. 13


Q? Write a c++ program that display the maximum value from the array elements.

int abc[5] = {12,45,32,56,3};


int maxx=0;

Q? At what index is the maximum located


for(int i=0;i<5;i++)
{
if(abc[i]>maxx)
{
maxx=abc[i];
}
}
cout<<" the maximum is "<<maxx; 14
 Q?

 Write a c++ program that display the elements of the following array
 Double marks[20]={50,90,30,100,78,68};

 Write a c++ program that initialize elements for the following array from the user, and display
the values/elements.
 double scores[5];

 Write a c++ Program to Increment every Element of the Array by one & Print Incremented
Array for the following array.
 int array[4] = {100, 200, 300, 400};

 Write a c++ Program that display the sum of the following array elements
 int array[4] = {100, 200, 300, 400};
15
Multidimensional arrays
A two dimensional array also falls under the category of a
multidimensional array.

• MD array can have any number of dimensions.


• Data type array_name [size 1][size2]….[size n]

 Here size1, size2 up to sizeN describe the number of dimensions

• Int array[3][3] // two dimensional array

• int array [5][2][3] // three dimensional array


16
Two-Dimensional Arrays
• In this type of array two indexes describe each elements the first index
represent a row and the second index represent a column.
(0,0) (0,1) (0,2)

(1,0) (1,1) (1,2)

(2,0) (2,1) (2,2)

• The above figure is a two dimensional array, the elements are arranged in row-
wise and column-wise, in a two dimensional array there are N number of rows
and columns. The above figure is a representation of a 3X3 matrix, which
means there are three rows and three columns in the array. 17
Declaration:
 The syntax is same as for 1-D array but here 2 subscripts are used.

Syntax: data_type array_name[rowsize][columnsize];

 Rowsize specifies the number of rows and Columnsize specifies the number of
columns.

Example: int a[4][5];

 This is a 2-D array of 4 rows and 5 columns. Here the first element of the array
is a[0][0] and last element of the array is a[3][4] and total number of elements is
4*5=20.
18
• .
The first element
col 0 col 1 col 2 col 3 col 4

row 0 a[0][0] a[0][1] a[0][2] a[0][3] a[0][4]

row 1 a[1][0] a[1][1] a[1][2] a[1][3] a[1][4]

row 2 a[2][0] a[2][1] a[2][2] a[2][3] a[2][4]

row 3 a[3][0] a[3][1] a[3][2] a[3][3] a[3][4]

The last element

19
Initializing Two-dimensional array

 2-D arrays can be initialized in a way similar to 1-D arrays.

Example: int m[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};


The values are assigned as:
The initialization of group of elements as follows:
a[0][0] =11 a[0][1] =0 a[0][2] =0

int m[4][3]={{11},{12,13},{14,15,16},{17}}; a[1][0] =12 a[1][1] =13 a[1][2] =0

 In 2-D arrays it is optional to specify the first dimension a[2][0] =14 a[2][1] =15 a[2][2] =16

a[3][0] =17 a[3][1] =0 a[3][2] =0


but the second dimension should always be present

 For processing of 2-D arrays we need two nested for loops. The outer loop

indicates the rows and the inner loop indicates the columns.
20
• Example: int a[4][5];

 Reading values in a
for(int i=0;i<4;i++)
for(int j=0;j<5;j++)
cin>>a[i][j];

Displaying values of a
for(int i=0;i<4;i++)
for(int j=0;j<5;j++)
cout<<a[i][j];
21
 Write a c++ program that display the maximum value from the
following array elements. And show the position(index) where the
maximum value is located.

int arr[3][4]={12,10,23,56,27,18,10,23,45,60,23};

Write a c++ program that display the sum of two 2X2 matrices

int arr1[2][2]

int arr2[2][2]

3D
22
Arrays as parameters
• In C++ it is not possible to pass by value a complete block of memory
as a parameter, even if it is ordered as an array, to a function, but it is
allowed to pass its address.

• To pass arrays as parameters the only thing that we must do when


declaring the function is to specify in the argument the base type for the
array that it contains, an identifier and a pair of void brackets [].

23
Here you have a complete example: ouput

#include <iostream> 5 10 15
Using namespace std; 2 4 6 8 10
void printarray (int arg[], int length)
{
for (int n=0; n<length; n++)
cout << arg[n] << " "; cout << "\n";}
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0;
}

24
Example 1: Passing One-dimensional Array to a Function
// C++ Program to display marks of 5 students
#include <iostream>
using namespace std;
void display(int m[5])
{
cout << "Displaying marks: " << endl;
for (int i = 0; i < 5; ++i)
{
cout << "Student " << i + 1 << ": " << m[i] << endl;
}}
int main()
{
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}

Example 2: Passing Multidimensional Array to a Function


25
String

26
String in C++ is nothing but a sequence of character in which the last
character is the null character ‘\0’.

In C++ strings of characters are held as an array of characters, one


character held in each array element.

A special null character , is represented by ‘\0’, is appended to the end


of the string to indicate the end of the string.

27
There are two types of strings commonly used in C++ programming
language:
Strings that are objects of string class (The Standard C++ Library string class)

C-strings (C-style Strings)

C-strings

• The collection of characters are stored in the form of arrays. .

• C-strings are arrays of type char terminated with null character, that is, ’\0’.

28
 How to define a C-string?
char str[] = "C++";

In the above code, str is a string and it holds 4 characters.

Although, "C++" has 3 character,

The null character \0 is added to the end of the string automatically.


 Alternative ways
char of=defining
str[4] "C++"; a string
char str[] = {'C','+','+','\0'};
char str[4] = {'C','+','+','\0'};

char str[100] = "C++";


Like arrays, it is not necessary to use all the space allocated for the string.
For example:
29
To read the text containing blank space, cin.get() function can be
used. This function takes two arguments.

First argument is the name of the string and second argument is the
maximum size of the array.

Example

30
string Object
In C++, you can also create a string object for holding strings.
Unlike using char arrays, string objects has no fixed length, and can
be extended as per your requirement.
• Example : C++ string using string data type

31
• In this program, a string str is declared. Then the string is asked from
the user.

• Instead of using cin>> or cin.get() function, you can get the entered
line of text by using getline().

• Getline() function takes the input stream as the first parameter which is
cin and str as the location of the line to be stored.

32
Counting the number of characters in a string.
The length method returns the number of characters in a string, including
spaces and punctuation.

Like many of the string operations, length is a member function, and we


invoke member functions using dot notation.

The string that is the receiver is to the left of the dot, the member function
we are invoking is to the right, (e.g. str.length() ).

In such an expression, we are requesting the length from the variable str.

33
String Functions & Purpose
 strcpy(destination, source);

 Strcpy copies character's from the location specified by sources to the location specified by
destination. It stops copying character's after it copies the terminating null character.

 The return value is the value of the destination parameter.

 strcat(destination, source);
The first character of the source string is copied to the location of the terminating null character of
the destination string.

 Strcmp(str 1, str2) or strncmp() compares two strings.

 Returns 0 string 1 is equal to string 2, 1 if string 1 is greater than string 2, -1 if string 1 is less than
string 2
strncmp(str1, str2, int n);
34
35

You might also like