Program Chapt 5

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

Chapter -5

Arrays and Strings

2
Array
3
Introduction
 An array is a collection of variables of the same type that are

referred to by a common name.


 An array is a consecutive group of memory locations that all have

the same name and the same type.


 For referring to a particular location, we specify the name and then

the positive index into the array. The index is specified by square
brackets, [].
 Arrays offer a convenient means of grouping together several

related variables, in one dimension or more dimensions:

4  What is the concept dimension in array?


Dimension in Arrays
 Declaring the name and type of an array and
setting the number of elements in an array is
called dimensioning the array.
The array must be declared before one uses
in like other variables.
In the array declaration one must define:
1. The type of the array (i.e. integer, floating
point, char etc.)
2. Name of the array,
3. The total number of memory locations to
be allocated or the maximum value of each
subscript. i.e. the number of elements in the
5
array.
Cont…
So the general syntax for the declaration is:
DataType name arrayname [array size];
int Student_list[55];
The expression array size, which is the
number of elements, must be a
constant such as 10 or a symbolic
constant declared before the array
declaration, for which the values are
known at the time compilation takes
place.
const int N = 55;
6 float Student_result[N];
Cont...
Product part numbers:
int part_numbers[] = {123, 326, 178, 1209};

Student scores:
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4}

Characters:
char alphabet[5] = {’A’, ’B’, ’C’, ’D’, ’E’};

Names:

char names[][40] = {“Peter”, “Mary”, “Lisa”, “John”, “George-Simon”};

3D coordinates: vector coordinates[4][3] ={{0, 0, 0},

{1, 0, 1},

{1, 0, 5},

7 {4, 7, 9}};
Initializing Arrays
When declaring an array of local scope
(within a function), if we do not specify
the array variable will not be initialized,
so its content is undetermined until we
store some values in it.
If we declare a global array (outside any
function) its content will be initialized
with all its elements filled with zeros.
Thus, if in the global scope we declare:
int day [5];
every0 element
0 0of day0 will0 be set
8
initially to 0:
Cont…

But additionally, when we declare an Array,


we have the possibility to assign initial values
to each one of its elements using twisted
brackets {}.
For example:
int day [5] = { 16, 2, 77, 40,
12071 };
The above declaration would have created an
array like 16
the following
2 one:
77 40 12071
0 1 2
3 4
day
9
Cont…

C++ allows the possibility of leaving


empty the brackets [ ], where the number
of items in the initialization bracket will be
counted to set the size of the array.

int day [] = { 1, 2, 7, 4, 12,9 };

The compiler will count the number of


initialization items which is 6 and set the
size of the array day to 6 (i.e.: day[6])

10
Cont…

You can use the initialization form only when


defining the array.
You cannot use it later, and cannot assign
one array to another once. I.e.
int arr [] = {16, 2, 77, 40, 12071};
int ar [4];
ar[]={1,2,3,4};//not allowed
arr=ar;//not allowed
Note: when initializing an array, we can provide
fewer values than the array elements. E.g. int a
[10] = {10, 2, 3}; in this case the compiler sets
the remaining elements to zero.
11
Accessing and processing array elements
 In any point of the program in which the array is
visible we can access individually anyone of its
elements for reading or modifying it as if it was a
normal variable.
 To access individual elements, index or subscript is
used.
 The format is the following: name [ index ]
 In C++ the first element has an index of 0 and the
last element has an index, which is one less the
size of the array (i.e. arraysize-1).
 Thus, from the above declaration, day[0] is the first
element and day[4] is the last element.

12
Cont…
The previous examples where day had 5 elements
and each element is of type int, the name, which
we can use to refer to each element, is the
following one:
day(0) day(1) day(2) day(3) day(4)
day 16 22 77 40 12071
For example, to store the value 75 in the third element
of the array variable day a suitable sentence would
be:
day[2] = 75; //as the third element is found at
index 2
 And, for example, to pass the value of the third
element of the array variable day to the variable a ,
we could write:
a = day[2];
13
Cont…
#include<iostream>
int main()
{
int numbers[5] ={10,20,30,40,50}; //array declaration & initialization
int sum, average; //declaring variables that store sum and average of
array elements
sum = 0,average=0; //initializing sum & average to 0

cout<<numbers[3]<<endl;
for (int i = 0; i <5; i++)
{
sum += numbers[i];
average = sum / 5;
} //end of for loop
cout<<"The Sum of Array Elements="<<sum<<endl;
cout<<"The Average of Array Elements="<<average;
return 0;
14 }
One-Dimensional Arrays
A one-dimensional array is a list of related variables. The general
form of a one-dimensional array declaration is:
type variable_ name[size]
 type: base type of the array, determines the data type of each element in the

array
 variable_name: the name of the array

 size: how many elements the array will hold

Examples:
float float_numbers[];
char last_name[40];
int sample[10]; 0 1 2 3 4 5 6 7 8 9
15 0 1 4 9 16 25 36 49 64 81
Cont…
Example: Loading and accessing the array sample with the numbers 0 through 9
#include<iostream>
using namespace std;
int main() {
int sample[10]; // reserves for 10 integers
int t;
for(t=0; t<10; t++) // initialize the array
{
cout << t <<" "; // display the index
}
cout<<endl;
for(t=0; t<10; t++)
{
sample[t] = t*t;
// display the array
cout << sample[t] << ' ';
}
return 0;
}
16
Two-Dimensional Arrays
A two-dimensional array is a list of one-dimensional arrays.

To declare a two-dimensional integer array two_ dim of size 3, 4 we


would write:

int test[3][4];
This corresponds to a table with 3 rows and 4 columns(for example).

17
Cont…
We can generate the array above by using this program:

#include<iostream>
int main()
{

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

for(int i=0;i<3;i++) {
for(int j=0;j<4;j++)
{
cout<<"test["<<i<<"]["<<j<<"]="<<test[i][j]<<endl;
}
}
return 0;
}
18
Writing Format to Two -Dimensional Array Initialization

 The Writing format of two -dimensional array


initialization are the same way as one dimensional arrays.
 For example, the following code fragment initializes an array squares with the

numbers 1 through 10 and their squares:


int squares[10][2] ={ 1, 1,
2, 4,
3, 9,
4, 16,
5, 25,
6, 36,
7, 49,
8, 64
9, 81
10, 100};
19
Cont…
 For better readability, one can use sub aggregate grouping by

adding braces accordingly.


 The same declaration as above can also be written as:

int squares[10][2] = { {1, 1},{2, 4}, {3, 9}, {4, 16}, {5, 25}, {6, 36}, {7, 49},
{8, 64}, {9, 81}, {10, 100}};

20
Arrays of Strings in dimension

 An array of strings is a special form of a two-dimensional array.

 The size of the left index determines the number of strings.

 The size of the right index specifies the maximum length of each string.

 For example, the following declares an array of 30 strings, each having a

maximum length of 80 characters (with one extra character for the null
terminator):

char string_array[30][81];

21
Character Array Initialization
Character arrays that will hold strings allow a shorthand
initialization that takes this form:

char array-name[size] = “string”;

For example, the following code fragment initializes str to the


phrase “hello”:

char str[6] = “hello”;


This is the same as writing

char str[6] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

Remember that one has to make sure to make the array


22
long enough to include the null terminator.
Un sized Array
Initializations
 It is possible to let C++ automatically dimension the arrays through the

use of unsized arrays.


char error_1[] = “Divide by 0\n”

char error_2[] = “End-of-File\n”;

char error_3[] = “Access Denied\n”;

 C++ will automatically create arrays large enough to hold all the

initializers present.

 For a multi-dimensional array, all but the leftmost dimension have to be

specified. So we can write:


char errors[][20] = {“Divide by 0\n”, “End-of File\n”, “Access Denied\n” };
23
Multidimensional Arrays
 C++ allows arrays with more than two dimensions.

 The general form of an N-dimensional array declaration is:

type array_ name [size_1] [size_2] … [size_ N];


 For example, the following declaration creates a 4 x 10 x 20

character array, or a matrix of strings:

char string _ matrix[4][10][20];

This requires 4 * 10 * 20*1 = 800 bytes.


 If we scale the matrix by 10, i.e. to a 40 x 100 x 20 x 1 array, then 80,000 bytes

are needed.
24
Arrays as parameters
At some moment we may need to pass an
array to a function as a parameter.
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, which
has almost the same practical effect and is
a much faster and more efficient operation.
For example, the following function:
void procedure
(int arg [])
25
Cont…
In order to declare 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
[] .

In order to pass to this function an array declared as


is used:

int myarray [40]; // It would be enough with a call like


this:
procedure (myarray);

To pass an array by value, pass each element to the


function
26
#include <iostream.h> Cont…
void printarray (int arg[], int length)
{
for (int n=0; n<length; n++)
cout << arg[n] << " ";
cout << "\n";
}
void mult(int arg[], int length)
{
for (int n=0; n<length; n++)
arg[n]=2*arg[n];
}
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
mult(firstarray,3);
mult(secondarray,5);
cout<<"first array after being doubled\n\n";
printarray (firstarray,3);
cout<<"second array after being doubled\n\n";
printarray(secondarray,5);
27
}
Part II

String
28
Introduction
 String in C++ is 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/null character ‘\0’ at the

end of the array sequence.

 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

29 "a" is stored in two consecutive bytes holding the character


….CONTN’D

A string variable Str1 could be declared as follows:


char Str1[10];

 The string variable Str1 could hold strings of length up to nine

characters since space is needed for the final null character. Strings can

be initialized at the time of declaration just as other variables are

initialized.
For example: char str1 [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char str2[] = "Hello";
For example:
char Str1[] = "Hello!";
char Str2[18] = "C++ Programming";

Would store the above two strings as follows:


H e l l O ! \0

Str1
C + + P r o g r a m m i n g \0

Str2
30
String Output

A string is output by sending it to an


output stream, for example:
char str1=“Hello!”;
cout<< "The string s1 is " <<
Str1<<endl; //would print The string Str1 is
Hello!
The setw(width) I/O manipulator can be
used before outputting a string, the string
will then be output right-justified in the
field width.

31
String Input
When the input stream cin is used space characters, n
space, tab, newline etc. are used as separators and
terminators.

To read a string with several words in it using cin we have


to call cin.

To read in a name in the form of first name followed by a


last name
char firstname[12], lastname[12];
cout << "Enter First name and Last name: ";
cin >> firstname>> lastname;
cout << "The Name Entered was " << firstname << " " <<
lastname;
32
Cont…

#include<iostream>
int main() {
const int max=80;
char str[max];
cout<<"Enter a string.\n";
cin>>str;
cout<<"You entered : "<<str;
}

33
Cont…
The cin>> considers a space to be a terminating
character & read strings of a single word.

To read text containing blanks we use another


function, cin.get().
#include<iostream>
int main()
{
const int max=80;
char str[max];
cout<<"Enter a string.\n";
cin.get(str,max);
cout<<"You entered : "<<str;
34 }
Cont…
Reading strings with multiple lines.
//reads multiple lines, terminates on '$'
character
#include<iostream>
int main()
{
const int max=80;
char str[max];
cout<<"\n Enter a string:\n";
cin.get(str, max, '$'); //terminates with $
cout<<"\n You entered:\n"<<str;
}
Type as many lines of input & enter the terminated
character $ when you finish typing & press Enter.
35
String Constants
You can initialize a string to a constant value
when you define it. Here's an example'
#include<iostream>
void main()
{
char str[] = "Welcome to C++ programming
language";
cout<<str;
}

36
Copying String
The strings copy performed using strcpy or strncpy
function. We assign strings by using the string copy
function strcpy. The prototype for this function is in
string.h.
strcpy(destination, source);
strcpy copies characters from the location specified
by source to the location specified by destination.
It stops copying characters after it copies the
terminating null character.
 The return value is the value of the destination
parameter.
You must make sure that the destination string is large
enough to hold all of the characters in the source
string (including the terminating null character).
37
Cont…
Example:
#include <iostream>
#include <string.h>
int main() {
char me[20] = "David";
cout << me << endl;
strcpy(me, "Are You or Not?");
cout << me << endl ;
return 0;
}

There is also another function strncpy, is like


strcpy, except that it copies only a specified
number of characters.
strncpy(destination, source, int n);
 It may not copy the terminating null
38character.
Cont…
Example strncpy(one, str2, 2);
#include <iostream> cout << one << endl;
#include <string.h> strcpy(one, str2);
void main() { cout << one <<
char str1[] = "String endl;
test"; }
char str2[] = "Hello";
char one[10];
strncpy(one, str1, 9);
one[9] = '\0';

cout << one << endl;


39
Concatenating Strings
In C++ the + operator cannot normally be used to
concatenate string, as it can in some languages
such as BASIC; that is you can't say
Str3 = str1 + str2;
You can use strcat() or strncat
The function strcat concatenates (appends) one
string to the end of another string.
strcat(destination, source);
 The first character of the source string is copied to the
location of the terminating null character of the destination
string.
 The destination string must have enough space to hold
both strings and a terminating null character.
40
Cont…
Example: cout << str1 <<
#include <iostream> endl;
#include <string.h> char str2[] = "xyz";
void main() strcat(str1, str2);
{ cout << str1 <<
char str1[30]; endl;
strcpy(str1, "abc"); str1[4] = '\0';
cout << str1 << cout << str1 <<
endl; endl;
strcat(str1, "def"); }

41
Cont’d
The function strncat is like strcat except that it
copies only a specified number of characters.
strncat(destination, source, int n);
 It may not copy the terminating null character.
Example:
cout << str1 << endl;
#include <iostream>
char str2[] = "xyz";
#include <string.h> strcat(str1, str2);
int main() { cout << str1 << endl;
char str1[30]; str1[4] = '\0';
strcpy(str1, "abc"); cout << str1 << endl;
cout << str1 << endl; }
strncat(str1, "def", 2);
str1[5] = '\0';

42
Comparing Strings
Strings can be compared using strcmp or
strncmp functions.
The function strcmp compares two strings.
strcmp(str1, str2);

strcmp returns: <0 if str1 is less


than str2
=0 if str1 is equal to str2
>0 if str1 is greater than
str2

43
Cont’d
Example:
#include <iostream>
#include <string.h>
void main() {
cout << strcmp("abc", "def") << endl;
cout << strcmp("def", "abc") << endl;
cout << strcmp("abc", "abc") << endl;
cout << strcmp("abc", "abcdef") <<
endl;
cout << strcmp("abc", "ABC") << endl;
}
44
Cont
 The function strncmp is like strcmp except that it
compares only a specified number of characters.
strncmp(str1, str2, int n);
strncmp does not compare characters after a terminating
null character has been found in one of the strings.
 Example:
#include <iostream.h>
#include <string.h>
int main()
{
cout << strncmp("abc", "def", 2) << endl;
cout << strncmp("abc", "abcdef", 3) << endl;
cout << strncmp("abc", "abcdef", 2) << endl;
cout << strncmp("abc", "abcdef", 5) << endl;
cout << strncmp("abc", "abcdef", 20) << endl;
}
45
Thank You

46

You might also like