0% found this document useful (0 votes)
34 views

Chapter Five Array and Strings

The document discusses arrays and strings. It begins by defining an array as a collection of elements of the same data type stored in adjacent memory locations. Each element has a unique index. Arrays can be one-dimensional or multi-dimensional. It then covers declaring and initializing one-dimensional arrays, accessing array elements, and multidimensional arrays. Two-dimensional arrays are discussed as having rows and columns accessed by two indexes. Methods for initializing and omitting the size of two-dimensional arrays are provided. The document concludes by discussing machine storage of two-dimensional arrays and introducing strings representation and manipulation.

Uploaded by

wubie derebe
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)
34 views

Chapter Five Array and Strings

The document discusses arrays and strings. It begins by defining an array as a collection of elements of the same data type stored in adjacent memory locations. Each element has a unique index. Arrays can be one-dimensional or multi-dimensional. It then covers declaring and initializing one-dimensional arrays, accessing array elements, and multidimensional arrays. Two-dimensional arrays are discussed as having rows and columns accessed by two indexes. Methods for initializing and omitting the size of two-dimensional arrays are provided. The document concludes by discussing machine storage of two-dimensional arrays and introducing strings representation and manipulation.

Uploaded by

wubie derebe
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/ 14

Computer Programming

Chapter Five: Array and String

6/14/2023 1

4.1 What is an arrays?


An array is a data structure which allows a collective name to be given to a group of elements
which all have the same type.

A collection of individual values, all of the same data type, stored in adjacent memory
locations.

An individual element of an array is identified by its own unique index (or subscript).

The index must be an integer and indicates the position of the element in the array.

Thus the elements of an array are ordered by the index.

The standard array notation is data type followed by array name with square bracket [].

Types of array one dimensional and multi dimensional array.


6/14/2023 2

1
4.1.1 Declaring and Initialization arrays/1-D Array
1 D is a n array with a single variable index.

Using the array name together with an integral valued index in square brackets refers to the
individual values.

The first array element always has the subscript 0.

The second array element has the subscript 1, etc. The base address of an array is its beginning
address in memory.

An array declaration is very similar to a variable declaration.

Syntax : DataType ArrayName[ArraySize];

The number of elements or array size must be an integer.


6/14/2023 3

Continued..
• The example below shows the declaration of an integer array of size 10 with element 0 -9.

• const int MAXSIZE = 10;

• int array[MAXSIZE]; or

• int array_name[100];

• Arrays can be initialized during declaration by equating the array to a listing of the array's
members in brackets. For example

• int array[MAXSIZE] = {2 , 4, 6, 8, 10, 12, 14,16, 18, 20};

6/14/2023 4

2
4.1.2 Accessing/processing of array element
The first element in an array always has the index 0, and if the array has n elements the last element will
have the arraysize n-1.

An array element is accessed by writing the identifier of the array followed by the subscript in square
brackets.

Thus to set the 15th element of the array above to 1.5 the following assignment is used:

annual_temp[14] = 1.5; Note that since the first element is at index 0, then the ith element is at
index i-1.

Hence in the above the 15th element has index 14.

To access individual elements, index or subscript is used. The format is the following:

6/14/2023
name [ index ] ; 5

4.2. Multidimensional arrays


✓An array may have more than one dimension.

✓Each dimension is represented as a subscript in the array.

✓Therefore a two dimensional array has two subscripts, a three dimensional array has three
subscripts, and so on.

✓Arrays can have any number of dimensions, although most of the arrays that you create will
likely be of one or two dimensions.

✓A chess board is a good example of a two-dimensional array. One dimension represents the
eight rows, the other dimension represents the eight columns.
✓Syntax of Type
6/14/2023 6
Multi_arrayName [ ] [ ]; Multi_arrayName [ ] [ ][];

3
4.2.1 Two-dimensional array
• Two-dimensional arrays store a tabular arrangement of values accessed by two indexes, for
example matrix[i][j], where i is the row index and j is the column index.

• To declare and initialize a two-dimensional arrays, Use the following syntax below.

datatype ArrayName [row][column];

6/14/2023 7

4.2.2 Initializing 2-Ddimensional arrays


To initialize a multidimensional arrays , you must assign the list of values to array elements in
order, with last array subscript changing while the first subscript holds steady.

The program initializes this array by writing

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

for the sake of clarity, the program could group the initializations with braces, as shown below.

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

6/14/2023 8

4
Omitting the Array Size
If a one-dimensional array is initialized, the size can be omitted as it can be found from the
number of initializing elements:

int x[] = { 1, 2, 3, 4} ;

✓This initialization creates an array of four elements.

Note however:

int x[][] = { {1,2}, {3,4} } ; // error is not allowed.

✓and must be written atleast the size of column

int x[][2] = { {1,2}, {3,4} } ;

6/14/2023 9

Multi-dimensional arrays: We can create array of arrays. It can be 2, 3 or N-


dimensional array, where N is an integer.

// Two dimensional array.

char WeekDays[7][10] = {
{“ Monday”},
{ “Tuesday”},
{“Wednesday”},
{“Thursday”},
{“Friday”},
{“Saturday”}
{“Sunday”}
};
6/14/2023 10

5
Col 1 Col 3 Col 5 Col 7 Col 9
Col 0 Col 2 Col 4 Col 6 Col 8

Row 0 M O N D A Y \0
Row 1 T U E S D A Y \0
Row 2 W E D N E S D A Y \0
Row 3 T H U R S D A Y \0
Row 4 F R I D A Y \0
Row 5 S A T U R D A Y \0
Row 6 S U N D A Y \0

6/14/2023 WeekDays[4][3] or 44th element 11

2-D Array: Char A[4][3]


Col 0 Col 2
Col 1

Row 0
A[0][0] A[0][1] A[0][2]

A[1][0] A[1][1] A[1][2]


Row 1
A[2][0] A[2][1] A[2][2]
Row 2

A[3][0] A[3][1] A[3][2]


Row 3

6/14/2023 12

6
Machine storage of 2-D array

{
A[0][0]
char A[4][3]; A[0]
A[0][1]
A[0][2]
A[1][0]

{
A is an array of size 4. A[1]
A[1][1]
A[1][2]
Each element of A is an A[2][0]
array of 3 chars A[2][1]

{
A[2]
A[2][2]
A[3][0]
A[3][1]
A[3]

{
A[3][2]

6/14/2023 13

Strings Representation
and
Manipulation

6/14/2023 14

7
4.3 Strings representation
String 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.

Each character in the string occupies one location in the array

Any array of character can be converted into string type in C++ by appending this special
character at the end of the array sequence.

Syntax

char StringName[ ];

6/14/2023 15

Continued…
For example a string variable s1 could be declared as follows:

char s1[10];

The string variable s1 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 s1[] = "example";

char s2[20] = "another example"


6/14/2023 16

8
Continued…
✓would store the two strings as follows:

s1 |e|x|a|m|p|l|e|\0|

s2 |a|n|o|t|h|e|r| |e|x|a|m|p|l|e|\0|?|?|?|?|

✓Note that the length of a string does not include the terminating null character.

6/14/2023 17

4.3.1 String Input


✓To read a string with several words in it using cin we have to call cin once for
each word.

✓For example to read in a name in the form of a First_name followed by a


Last_name we might use code as follows:
char firstname [12], lastname[12];

cout << "Enter first name and last name ";

cin >> firstname ;

cin >> lastname;

6/14/2023 cout << "The name entered was “<< firstname << " "<< lastname; 18

9
Continued…
✓To read text containing blanks we use another function, cin.get( ).
#include<iostream.h>
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;
}
6/14/2023 19

Continued…
✓In this example, we call the function with a dollar sign ('$') as the third argument

//reads multiple lines, terminates on '$' character


#include<iostream.h>

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; }

6/14/2023 20

10
4.3.2 Strings Manipulation
String constants

You can initialize a string to a constant value when you define it. Here's an example'

#include<iostream.h>

int main(){

char str[] = "Welcome to C++ programming language";

cout<<str;

6/14/2023 21

Continued…
Copying string

✓You can copy strings using strcpy function.

✓We assign strings by using the string copy function strcpy.

✓The builtin strcpy function is in string.h and add a heard file to include for this file which is declared
in the standard library under string.h header file

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.


6/14/2023 22

11
Continued…
Strings Manipulation
Copying string

✓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). Example:
#include <iostream.h>
#include <string.h>
int main(){
char me[20] = "David";
cout << me << endl;
strcpy(me, "YouAreNotMe");
cout << me << endl ;
return;
6/14/2023 } 23

Continued…
Concatenating strings

✓Appends source string at the end of destination string.

✓You can use strcat()

✓The function strcat concatenates (appends) one string to the end of another string.

strcat(destination, source);

6/14/2023 24

12
Continued…
✓ Example:
#include <iostream.h>
#include <string.h>
void main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl;
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
}

6/14/2023 25

Continued…
Comparing strings

✓Strings can be compared using strcmp

✓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

6/14/2023 26

13
Continued…
Example:
#include <iostream.h>

#include <string.h>

int 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;

6/14/2023 27

14

You might also like