C++ Chapter 5 Arrays and String
C++ Chapter 5 Arrays and String
CHAPTER FIVE
ARRAYS AND STRINGS
Introduction
An array consists of a set of objects (called its elements), all of which are of the same type
and are arranged contiguously in memory. In general, only the array itself has a symbolic
name, not its elements. Each element is identified by an index which denotes the position
of the element in the array. The number of elements in an array is called its dimension. The
dimension of an array is fixed and predetermined; it cannot be changed during program
execution.
Arrays are suitable for representing composite data which consist of many similar,
individual items. Examples include: a list of names, a table of world cities and their current
temperatures, or the monthly transactions for a bank account.
Defining Arrays
Like any other variable, array must be defined before it can be used to store data. The array
definition comprises the variable type(which could be a char, an int, a float, etc;), the
name of array and size in square brackets.
Syntax
Data_type ArrayName [size];
The items in an array are called elements. The elements in an array should have same data
type. Only their values vary.
E.g. int num[10]; ( assuming this array has the elements 20, 30, 70, …, 21, it looks the
following in the computer’s memory)
The first element in an array has an index value of 0, the second 1, and so on. If an array
has 10 elements, then the first element has index value of 0 and the 10 th element has an
index value of 9.
20 num [0]
30 num [1]
70 num [2]
64 num [3]
29 num [4]
37 num [5]
16 num [6]
19 num [7]
26 num [8]
21 num [9]
Memory
Example 1
The following program stores 10 natural numbers in one array and displays them
(with enough space between the numbers when displayed).
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main ( )
{
int n[10];
for(int i = 0;i<10;i++)
{
cout <<"enter natural number "<<i+1<<" ";
cin>>n[i];
}
cout<<"Now displaying ";
for(int j = 0;j<10;j++)
cout<<setw(4)<<n[j];
getch();
}
Initializing Arrays
It is possible to initialize the elements of the array during defining arrays. When initializing
arrays there is no need to write the array size in the square brackets.
Syntax
Data_type ArrayName [ ] = {initializes};
initializes the three elements of nums to 5, 10, and 15, respectively. When the number of
values in the initializer is less than the number of elements, the remaining elements are
initialized to zero:
When a complete initializer is used, the array dimension becomes redundant, because the
number of elements is implicit in the initializer. The first definition of nums can therefore
be equivalently written as:
The following program finds displays the sum of the initialized array elements.
Example 1
#include <iostream.h>
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}
Example 2
The following program finds average of numbers that are stored in array.
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main ( )
{
int num[10]= { 10,20,50,70,75,60,80,95,55,100};
float sum = 0;
float av;
for(int i = 0;i<10; i++)
sum+=num[i];
av=sum/10;
cout<<"The average is\t"<<av;
getch();
}
Operations on Arrays
Each member of an array is a pseudo-variable and can be processed as such. This means
that you can add the values of two members of the array(Number[2]+Number[0]), you
can subtract the value of one of the members from another member(member[1]-
Number[4]). In the same way, you can perform multiplication, division, or remainder
operations on members of an array.
One of the regular operations performed on an array consists of adding the values of the
members to produce a sum. Here is an example:
#include <iostream.h>
int main()
{
// We know that we need a constant number of elements
const int max = 10;
int number[max];
cout << "\n\nThe sum of these numbers is " << Sum << "\n\n";
return 0;
}
int main()
{
// Declare the members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int find;
int i, m = 8;
int main()
{
// The members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int minimum = numbers[0];
int a = 8;
You can use this same approach to get the maximum value of the members of an array.
Here is an example:
return 0;
}
Example 1
#include <iostream.h>
return 0;
}
Example2
#include <iostream.h>
void DisplayTheArray(double mbr[], int count);
int main()
{
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12};
return 0;
}
As before, elements are accessed by indexing the array. A separate index is needed for each
dimension. For example, Addis Abeba’s average summer temperature (first row, second
column) is given by seasonTemp[0][1]. The array may be initialized using a nested
initializer:
int seasonTemp[3][4] = {26, 34, 22, 17, 24, 32, 19, 13, 28, 38, 25, 20};
The nested initializer is preferred because as well as being more informative, it is more
versatile. For example, it makes it possible to initialize only the first element of each row
and have the rest default to zero:
We can also omit the first dimension (but not subsequent dimensions) and let it be
derived from the initializer:
Example 1
The following program finds the highest temperature out of the three cities and the four
seasons.
int main()
{
const int rows = 3;
const int columns = 4;
int seasonTemp[rows][columns] = { {26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}};
int highest = 0;
for (int i = 0; i < rows; ++i)
for (int j = 0; j < columns; ++j)
if (temp[i][j] > highest)
{
highest = temp[i][j];
cout<<"The highest temperature is =:"<<highest;
}
}
Example 2
The following program stores sales of commodities in 5 stations for 3 months. You can
also display what you stored for checkup purpose.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main ( )
{
float sales[5][3];
for(int s=0;s<5;s++)
for (int m=0;m<3;m++)
{ cout <<"enter sales for station "<<s+1;
cout<<" month "<<m+1<<" ";
cin>>sales[s][m];
}
for (int j=0; j<=4; j++)
for (int k=0;k<=2;k++)
{cout<<" sales "<<j+1 <<" month "<<k+1;
cout<<setw(4)<<sales[j][k];
if (k= =2)
cout<<"\n";
}
getch( );
}
Strings
Fundamentals of Computer Programming 10
Adama Science and technology University
Since you have some understanding about arrays, it is very simple to examine strings.
Strings are arrays of characters. In the arrays of characters, the null character is always
added to the end of the characters. The null character is ’\0’; with ASCII value of 0. In C++
there is no means to check the array bounds. Therefore, be careful when putting data into
arrays not to exceed its maximum bounds.
For example the inbuilt C++ function setw(bound) helps to read characters as much as size
of bound. When we display strings, characters inside an array are displayed until a null (‘\
0’) character is encountered.
Examples
The following C++ program reads your name from keyboard and displays it.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main ()
{ char name[20];
cout<<"Enter your name \t";
cin>>setw(20)>>name;
cout<<name;
getch();
}
If you need to read a string with blank spaces in between, the extraction operator>>
considers the space to be a terminating character of a string. Thus, characters after a space
will be ignored. To avoid this problem you can use the function cin.get(). This helps to
read strings along with blank spaces.
e.g.
The following program reads your name and father’s name and displays it.
#include<iostream.h>
#include<conio.h>
void main ( )
{
char str [20];
cout<<"Enter Full Name\t";
cin.get(str,20);
cout<<"your name and fathers name is \n"<< str;
}
Some time it is necessary to read multiple lines of string from the key board. The default
terminating character is the new line (‘\n’) character. But it is possible to override the
default character with some other characters so that we can read multiple lines of text until
that terminating character is typed.
This can be achieved by adding the terminating character in the cin:: get ( ) function as an
argument.
Example
The following program reads multiple lines of text and stores it in an array.
#include<iostream.h>
#include<conio.h>
void main ( )
{char str[100];
cout<<"Enter a sstring and $ when finish \n";
cin.get (str,100,'$');
cout<<"you entered \n"<<str;
getch ( ) ;
}
Arrays of strings
Like arrays of arrays, it is also possible to have arrays of strings. This is important to store
arrays of names of people, or other strings for some other purpose. To define such
constructions, we should write the size of the array and the maximum size of each string.
Example
The following program stores list of people in an array and display it.
#include<iostream.h>
#include<conio.h>
void main( )
{
char name[5][10]={"kebede", "Ayele","Tufa","Almaz", "Kasa"};
for (int i=0; i<5;i++)
cout<<name[i]<<'\n';
}
String Manipulation
strlen( ): this c++ library function finds the length of a string, i.e. how many characters are
in the string, excluding the null (‘\0’) character. This function takes the name of the string
variable or constant as an input (argument) and returns an integer value. We must include
the <string.h> header file to use this function.
Example
The following program takes your name and tells the length of your name.
#include<iostream.h>
#include<string.h>
#include<conio.h>
void main()
{
char name[25];
cout<<"Enter your name: ";
cin>>name;
cout<<"your name is "<<strlen(name)<<" characters long";
getch();
}
strcpy():It is a common process to copy one string into another. You can have many ways
to copy a string. Copying a string character by character is one option to do so. It needs to
access characters of a string character by character. Using the built in function strcpy() to
copy a string is another easier method.
Example
#include<iostream.h>
#include<string.h>
#include<conio.h>
void main ()
{ const int SIZE=100;
char str1[SIZE];
char str2[SIZE];
cout<<"Enter a string\n";
cin.get(str1,SIZE);
strcpy(str2,str1);
cout<<"Copy of your string is \n"<<str2;
getch ();
}
strcpy( ) takes two arguments and copies the second variable ( the right hand side) to the
first (left hand side) variable.
strcat( ): this function takes two arguments and concatenates (appends) the second variable
to the first one.
Example
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main ( )
{ const int p=30;
char ch1[50],ch2[100]="I am proud ";
cout<<ch2<<endl;
cout<<"Enter a string to concatenate :";
cin.get(ch1,50);
strcat(ch2,ch1);
cout<<"The concatenated is "<<ch2;
getch();
}
strcmp( ): this function takes two string arguments and compares them. The result of the
comparison is an integer value of either negative, positive, or zero based on the following
facts.
Example strcmp(str1,str2);
0 if str1 is the same as str2
+ve (>0) if str2 comes first alphabetically
-ve (<0) if str1 comes first alphabetically
Example: the following program takes two words from a user and compares their
alphabetical precedence.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
const int p=15;
char ch1[p],ch2[p];
cout<<"Enter first string: ";
cin>>ch1;
cout<<"enter second string: ";
cin>>ch2;
if(strcmp(ch1,ch2) = = 0)
cout<<"The two words are the same";
else if(strcmp(ch1,ch2)>0)
cout<<ch2<<" comes first alphabetically";
else if(strcmp(ch1,ch2)<0)
cout<<ch1<<" comes first alphabetically";
getch();
}
Examples
The following C++ program reads your name from keyboard and display it in reverse
order.
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<iomanip.h>
void main ( )
{ char name[20];
cout<<"Enter your name \t";
cin>>setw(20)>>name;
for(int i=(strlen(name)-1);i>=0;i--)
cout<<name[i];
getch();
}
Exercise
1. Define two functions which, respectively, input values for the elements of an array
of reals and output the array elements:
2. Define a function which reverses the order of the elements of an array of reals:
void Reverse (double nums[], const int size);
3. The following table specifies the major contents of four brands of breakfast cereals.
Define a two-dimensional array to capture this data:
4. Write a C++ program that stores a 4 by 5 integer matrix and display it.