[go: up one dir, main page]

0% found this document useful (0 votes)
23 views11 pages

Chapter 4

Uploaded by

Adugna Negero
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)
23 views11 pages

Chapter 4

Uploaded by

Adugna Negero
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/ 11

WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem.

II, 2017 Chapter 4

Chapter Four

Arrays and Strings

4.1. Overview of an Array

 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.

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

 An array can be thought of as a collection of numbered boxes each containing one


data item. The number associated with the box is the index of the item.

 To access a particular item the index of the box associated with the item is used to
access the appropriate box.

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

Index 0 Index 1 Index 2 Index 3 Index 4

110 20 230 4550 52

Element at Element at Element at Element at Element at


index 0 index 1 index 2 index 3 index 4

4.2. One Dimensional Array

4.2.1. Declaration of Arrays

An array declaration is very similar to a variable declaration:

First, a type is given for the elements of the array; then an identifier for the array and,
within square brackets, the number of elements in the array.

For example, data on the average temperature over the year in Ethiopia for each of the
last 100 years could be stored in an array declared as follows:

float annual_temp[100];

~1~
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 4

The above declaration will cause the compiler to allocate space for 100 consecutive float
variables in memory.

It is possible to make the array size a constant as follows:

const int NE = 100;


float annual_temp[NE];

4.2.2. Accessing Array Elements

Given the declaration above of a 100 element array; the compiler reserves space for 100
consecutive floating point values and accesses these values using an index/subscript that
takes values from 0 to 99. The first element in an array in C++ always has the index 0,
and if the array has n elements the last element will have the index n-1.

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.

Look at the following C++ sample code that reads 10 even integer numbers and compute
their summation:

int number[10]; //memory location for ten integers

int sum=0;

for(int i=0;i<10;i++) {

cin>>number[i]; //reads the number and stores at index i

if(number[i]%2==0)

sum+=number[i]; }

cout<<sum;

4.2.3. Initialization of Arrays

An array can be initialized with either its size specified or not.

For example, initializing an array to hold the first few prime numbers could be written as
follows:

~2~
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 4

int primes[] = {1, 2, 3, 5, 7, 11, 13};

Note that the array has not been given a size; the compiler will make it large enough to
hold the number of elements in the list. In this case, primes would be allocated space for
seven elements. If the array is given a size then this size must be greater than or equal to
the number of elements in the initialization list.

For example,

int primes[10] = {1, 2, 3, 5, 7};

The above array would reserve space for a ten element array but would only initialize the
first five elements only.

Look at the following sample C++ code that declare an array with 100 elements and
assigns it to only 10 of them:

const int lim=100;

int data[lim]={1,3,5,7,9,11,13,15,17,19};

cout<<data[5]; // 11 (because 1 is found at data[0] !)

4.2.4. Copying Arrays

The assignment operator cannot be applied to array variables:

const int SIZE=10


int x [SIZE] ;
int y [SIZE] ;
x=y; // Error - Illegal
Only individual elements can be assigned to using the index operator, e.g., x[1] = y[2];.

For example, to make all elements in 'x' the same as those in 'y' (equivalent to
assignment), a loop has to be used.

// Loop to do copying, one element at a time


for (int i = 0 ; i < SIZE; i++)
x[i] = y[i];

~3~
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 4

Look at the following sample C++ code that declares two array variables; it initializes the
first array to ten consecutive integer numbers and copies only those odd numbers into the
second array to display them:
int num[10]={1,2,3,4,5,6,7,8,9,10};
int odd[10];
for(int i=0;i<10;i++) {
if(num[i]%2!=0) {
odd[i]=num[i];
cout<<odd[i]<<” ”; } } // 1 3 5 7 9

4.3. 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.

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.

int chess[8][8];

4.3.1. Initializing Multidimensional Arrays

To initialize multidimensional array, we must assign the list of values to array elements
in order, with last array subscript changing while the first subscript holds steady.
Therefore, if the program has an array int theArray[5][3], the first three elements go into
theArray[0]; the next three into theArray[1]; and so forth.

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} };
The compiler ignores the inner braces, which clarify how the numbers are distributed.

~4~
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 4

Each value should be separated by comma, regardless of whether inner braces are
included. The entire initialization must appear within braces, and it must end with a
semicolon.

NB: If one-dimensional array is initialized, the size can be omitted as it can be found
from the number of initializing elements. But, it is not possible in case of
multidimensional array.

int x[] = { 1, 2, 3, 4} ; // creates an array of four elements


int x[][] = { {1,2}, {3,4} } ; // error
int x[2][2] = { {1,2}, {3,4} } ; // ok
Look at the following sample C++ code of multidimensional array:

#include<iostream.h>
void main(){
int SomeArray[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};
for(int i=0;i<5;i++)
for(int j=0;j<2;j++)
cout<<"SomeArray["<<i<<"]["<<j<<"]: "<<SomeArray[i][j]<<endl; }
/* Output:
SomeArray[0][0]: 0
SomeArray[0][1]: 0
SomeArray[1][0]: 1
SomeArray[1][1]: 2
SomeArray[2][0]: 2
SomeArray[2][1]: 4
SomeArray[3][0]: 3
SomeArray[3][1]: 6
SomeArray[4][0]: 4
SomeArray[4][1]: 8 */
4.4. String Representation and Manipulation

String in C++ 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.

~5~
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 4

In C++ strings of characters are held as an array of characters, one character held in each
array element. In addition a special null character, represented by `\0', is appended to the
end of the string to indicate the end of the string. 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 "a" is stored in two consecutive bytes
holding the character `a' and the null character.

A string variable s could be declared as follows:

char s[10];

The string variable s 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";
/ * 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|?|?|?|?| */

 In the first case the array would be allocated space for eight characters that is
space for the seven characters of the string and the null character.

 In the second case the string is set by the declaration to be twenty characters long
but only sixteen of these characters are set, i.e. the fifteen characters of the string
and the null character.

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

Look at the following sample C++ code that reads in a name in the form of a Christian
name followed by a surname:

char christian[12], surname[12];


cout<<"Enter name: ";
cin>>christian;
cin>>surname;

~6~
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 4

cout<<"The name entered was "<< christian << " "<< surname;
The name would just be typed by the user as, for example, Abera Tola and the output
would then be:

The name entered was Abera Tola

4.4.1. String Constants

We can initialize a string to a constant value when we define it.

For example,
char str[] = "Welcome to C++ programming language!";
cout<<str; // Welcome to C++ programming language!
4.4.2. String Length
We use strlen function to count the number of characters in a particular string including
any blank space within that string. The prototype for this function is in string.h.
Example:
#include<iostream.h>
#include<string.h>
void main() {
char str[]=”Computer Programming”;
cout<<strlen(str); } // 20

4.4.3. Copying Strings

We can copy strings using strcpy or strncpy functions. The prototype for these functions
is in string.h.

i. The 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.

Its syntax is:

strcpy(destination, source);
Example:
#include<iostream.h>
#include<string.h>

~7~
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 4

void main(){
char me[20] = "Alemu";
cout<<me<<endl; // Alemu
strcpy(me, "You Are Not Me");
cout<<me<<endl ; } // You Are Not Me
ii. The strncpy copies only a specified number of characters. It may not copy the
terminating null character.

Its syntax is:

strncpy(destination, source, int n);


Example

#include<iostream.h>
#include<string.h>
void main() {
char str1[] = "String test";
char str2[] = "Hello";
char one[10];
strncpy(one, str1, 9);
one[9] = '\0';
cout<<one<<endl; // String te
strncpy(one,str2,2);
cout<<one<<endl; // Hering te
strcpy(one, str2);
cout<<one<<endl; } // Hello

4.4.4. Concatenating Strings

We can concatenate (append) strings using strcat or strncat functions. The prototype for
these functions is in string.h.

i. The function strcat concatenates (appends) one string to the end of another string.
Its syntax is:

strcat(destination, source);

~8~
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 4

o The first character of the source string is copied to the location of the terminating null
character of the destination string.

o The destination string must have enough space to hold both strings and a terminating
null character.

Example:

#include<iostream.h>
#include<string.h>
void main() {
char str1[30];
strcpy(str1, "abc");
cout<<str1<<endl; // abc
strcat(str1, "def");
cout<<str1<<endl; // abcdef
char str2[] = "xyz";
strcat(str1, str2);
cout<<str1<<endl; // abcdefxyz
str1[4] = '\0';
cout<<str1<<endl; } // abcd
ii. The function strncat is like strcat except that it appends only a specified number
of characters. It may not append the terminating null character.

Its syntax is:

strncat(destination, source, int n);


Example:

#include<iostream.h>
#include<string.h>
void main() {
char str1[30];
strcpy(str1, "abc");
cout<<str1<<endl; // abc
strncat(str1, "def", 2);
str1[5] = '\0';

~9~
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 4

cout<<str1<<endl; // abcde
char str2[] = "xyz";
strcat(str1, str2);
cout<<str1<<endl; // abcdexyz
str1[4] = '\0';
cout<<str1<<endl; } // abcd

4.4.5. Comparing Strings


Strings can be compared using strcmp or strncmp functions. The prototype for these
functions is in string.h.
i. The function strcmp compares two strings.
Its syntax is:
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
Example:

#include<iostream.h>
#include<string.h>
void main() {
cout<<strcmp("abc", "def")<<endl; // -3
cout<<strcmp("def", "abc")<<endl; // 3
cout<<strcmp("abc", "abc")<<endl; // 0
cout<<strcmp("abc", "abcdef")<<endl; // -100
cout<<strcmp("abc", "ABC")<<endl; } // 32
ii. The function strncmp compares only a specified number of characters. It does not
compare characters after a terminating null character has been found in one of
the strings.

Its syntax is:

strncmp(str1, str2, int n);

~ 10 ~
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 4

Example:

#include<iostream.h>
#include<string.h>
void main() {
cout<<strncmp("abc", "def", 2)<<endl; // -3
cout<<strncmp("abc", "abcdef", 3)<<endl; // 0
cout<<strncmp("abc", "abcdef", 2)<<endl; // 0
cout<<strncmp("abc", "abcdef", 5)<<endl; // -100
cout<<strncmp("abc", "abcdef", 20)<<endl; } // -100

~ 11 ~

You might also like