CHAPTER FOUR
Introduction to Arrays and string:
5.1 ARRAY
An array is a series of elements of the same type placed in contiguous memory locations a
unique identifier. That means that, for example, we can store 5 values of type int in an array
without having that can be individually referenced by adding an index to declare 5 different
variables, each one with a different identifier. Instead of that, using an array we can store 5
different values of the same type, int for example, with a unique identifier. For example, an array
to contain 5 integer values of type int called billy could be represented like this:
Where each blank panel represents an element of the array, that in this case are integer read
before it is used. A typical declaration where type is a valid type (like int, float...), name is a
valid identifier and the elements to contain as: values of type int. These elements are numbered
from 0 to 4 since in arrays the first index is always 0, independently of its length. Like a regular
variable, an array must be declaration for an array in C++ is: type name [elements]; field (which
is always enclosed in square brackets []), specifies how many of these elements the array has
Therefore, in order to declare an array called billy as the one shown in the above diagram it is as
simple int billy [5];
NOTE: The elements field within brackets [ ] which represents the number of elements the
array
is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory
whose size must be determined be for execution.
Array is a collection of items of same data type that are referenced by a common name. All the
variables are referred using an index value. The index value starts at 0 i.e., first value is referred.
The individual values are called elements. That element is referred by index of subscript. Array
may have several dimensions. 1) One-dimensional 2) Two-dimensional.
1. One-Dimensional Array: This is also called as a vector or list.
General form: Type-specifier Identifier-name [size];
Eg.: int a[10]; a[0],a[1],a[2],………..,a[9]
Declares b as an array containing maximum of 10 real
float b[10];
elements.
Arrays can be initialized at the time of declaration only. But it is not a good practice.
Eg. int i[5] = {1,2,3,4,5};
Character arrays hold the strings. Format: char array-name [size] = ‘string’;
Eg., char b[7] = { ‘w’,’e’,’l’,’c’,’o’,’m’,’e’};
Program 1: To find maximum number in an array.
// to find the maximum element.
#include<iostream.h>
void main()
{
int a[5], i, max;
cout<<”Enter 5 numbers \n”; // inputting the array elements
for( i=0; i<5; i++ )
cin>>a[ i ];
max = a[0]; // searching for the largest element.
for (i=1; i<5; i++)
if (max < a[ i ])
max = a [ i ];
// print the maximum element in the list.
cout << “ Maximum element in the list is : “ << max;
}
2. Two-dimensional arrays:
This is an array of one-dimensional arrays. It can store table of values. It is also called as matrix
of elements. General form: type specifier array-name [row-size] [column-size]; The element
declaration here is also done with ‘zero origin subscript’. Thus, an array a [3][3] will
have
a [0][0] a[0][1] a[0][2] This may be called as Table or
a[1][0] a[1][1] a[1][2] Matrix as they store
a[2][0] a[2][1] a[2][2] Table of values in rows & columns.
This can also be initialized by following declaration.
int a[2][3], b[3][3];
Program 4: For a two-dimensional array 3x3 find (1) sum of all elements.(2)row-wise sum.
(3)Column –wise sum.
// to find sum of matrix elements.
#include<iostream.h>
// to sum elements row-wise.
main()
for(i=0; i<m; i++)
{
{
int a[10][10], i, j, sum, rsum, csum, m, n; cout
<<”enter the order of matrix \n”; rsum = 0;
cin>>m>>n; for(j=0; j<n; j++)
cout<<”enter the elements of the matrix one by rsum += a[i][j];
one \n”; cout<<"row number:"<<(i+1)<<"\t row
for(i=0; i<m; i++) sum = "<<rsum<<" \n";
for(j=0; j<n; j++) // To sum column-wise
cin>>a[ i ][j]; for(j=0; j<n; j++)
{
//to sum all elements of matrix.
csum=0;
sum = 0; for(i=0; i<m; i++)
csum += a[i][j];
for(i=0; i<m; i++) cout<<"column number:"<<(j+1)<<"\
for(j=0; j<n; j++) tcolumn
sum= "<<csum<<"\n";
sum += a[i][j]; }}
cout<<”sum of the elements of the matrix is :
“<<sum;
5.2 STRINGS
A String is an array of characters i.e., they are defined between the single quotes.
A string is a character array terminated by a null character. Null character is specified as
‘ \0 ’ So, the size should be equal to maximum on. Of characters in the string plus one.
Eg: char name [5] = { ‘j’ , ‘o’, ‘n’, ‘y’, ‘\0’}
Declaration of string variable: char string-name [size] { Size — No. of characters in the
String-name }
Eg., char sname[30],country[40];
Reading strings: cin operator can be used to read a string eg., char name[50];
cin>>name; — terminates when first blank character is encountered.
Thus, usually we use a new command to read entire line
— reads entire string until terminated by the enter key or 49
[Link](name,50);
characters are read(which ever occurs first)
String handling functions (string.h file to be included)
a) Length of a string (strlen): defines the length or number of characters in the specified
string.
//Program to implement strlen
function:
#include<iostream.h>
#include<string.h>
main()
{
char name[80];
int a;
cout<<” Enter the string \n”;
cin>>name;
a= strlen(name);
cout<<” \n length of string is
“<<a;
}
b) String Concatenation (strcat): This function adds 2 strings & places in the first string.
i.e., the function appends the second string to the first
Program to test the strcat function.
#include<iostream.h> cout<<”Enter the second string \n”;
#include<string.h> cin>>n2;
main() strcat(n1,n2);
{ cout<<” Concatenated strings are :”<< n1;
char n1[100], n2[50]; }
int i, c;
cout<<” enter the first string \n”;
cin>>n1;
c) Copying two strings (strcpy): This will assign the contents of one string or character
array to the string variable.
Eg. strcpy(n, "Ethiopia") Stores the character array ’Ethiopia’ in string n.
Stores the contents of n2 to n1 erasing the contents of
strcpy(n1,n2)
n1 if any
d) Comparing two strings (strcmp): This function is used to compare two strings. This
compares the ASCII values of the strings.
For example strcmp(s1,s2) will return:
(i) Zero if s1 & s2 are equal.
(ii) Positive value if s1>s2.
(iii) Negative value if s1<s2.
The comparison is done on their ASCII values.
[viz., ASCII value of A=65, Z=90, a=97, z=122]
e) Reversing the String (strrev): This function is used to reverse the given string.
Program. To count number of characters, words & blank spaces in the given line.
// to count no. of characters, words & blank spaces.
Program 2. : To convert uppercase to
#include <iostream.h> lowercase & vice-versa.
#include <conio.h>
#include<iostream.h>
#include <string.h>
#include<ctype.h>
void main()
#include<string.h>
{
main()
int now,noc,nos,i;
{
char st[100];
int i;
cout<<"enter the string: "; char str[50],ch=’y’;
[Link](st,100); while(ch==’y’)
noc=now=nos=0; { cout<<”Enter the string to convert \
for(i=0;i<strlen(st);i++) n”;
{ [Link](str,20);
noc++; i= 0;
if(st[i]==' ')
while(str[i]!=’\0’)
{
{
now++;
if(islower(str[i]))
nos++;
str[i] = toupper(str[i]);
noc--;
else
}
str[i] = tolower(str[i]);
}
i++;
now++;
}
cout<<"\nno of characters "<<noc;
cout<<”converted string is :”<<str<<”\
cout<<"\nno of words: "<<now;
n”;
cout<<"\n no of spaces: "<<nos;
cout<<”do U continue(y/n)? \n”;
getch();
cin>>ch;
}
}
}