Arrays and Strings C++
Arrays and Strings C++
By
Irfan Abdullah
CONTENTS
• Concept of an array
• How array elements are arranged in memory
• Terms related with array
• Define and initialize array
• How to access and write at an index in array
• Traversing an array using all loop structures
• Use the sizeof() function to find the size of array
• Concept of two dimensional array
• Defining and initializing two dimensional array
• Accessing and writing at an index in two dimensional array
• Concept of strings
• Defining string
• Techniques of initializing string
• Most commonly used string functions
Introduction
• This unit describes a new type of data structure known as array
which provides a convenient way to manipulate a collection of
same type of data. Array is very commonly used in computer
programming as it provides simple solutions to many problems
when working with long lists of same type of data, such as
numbers. For example, array can be used to sort a list of
numbers or to find their total and average.
Introduction to Arrays
• Array allows programmer to use a single variable name to
represent a collection of same type of data. This reduces the
program size, provides an easy way of handling list of numbers
or strings and makes computer programming task simple and
easy.
Concept of an Array
• An array is a collection of same type of • Array consists of contiguous memory
elements stored in contiguous memory locations and each cell represents an
locations. For example, if we want of element of the array. In the array
store marks of six subjects in computer named marks, each element of the
memory, we have to declare six array represents marks of a subject.
variables, one for each subject. Instead The number within the square
of using six variables we can declare brackets is called index and it is used
one array variable called marks that to access a specific element of the
can store marks of six subjects. This array. The first element of the array
array could be represented as shown in always has the index 0. Therefore, the
Fig. index of the last element is one less
than the size of the array. In the marks
array, there are 6 elements so the
indexes are from 0 to 5. Index of array
is always an integer value.
Declaring an Array
• To declare an array in C++, the type of the elements, the name of array and the
number of elements it is required to store need to be mentioned in the declaration
statement.
• The following is the general form of declaration of array.
datatype arrayname [arraysize];
• Here, datatype is a valid data type (such as integer, float, etc.), arrayname is the
name of the array which is a valid variable name and array size is enclosed within
square brackets and it specifies the number of elements that can be stored in the
array. This type of array is known as one dimensional array.
• For example, the following statement declares an array called marks of type integer
that can store marks of six subjects.
int marks[6];
• The following are some more examples of array declaration.
int a[10],b[15];
float weight[8];
Initialization of Array
• An array can be initialized in declaration statement. The
following statement declares the marks array as integer of size 6
and assigns marks to each element of the array.
int marks[6]={45, 67, 50, 79, 58, 36};
• When initializing an array, it is not necessary to mention the
array size in the declaration statement since the compiler can
find out the array size by counting the values in the curly
brackets. Therefore, the above statement can also be written as :
int marks[ ]={45, 67, 50,79,58, 36};
Using Arrays in Programs
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
using namespace std
main() using namespace std
{ main()
int a[5], k, total; {
float avg; int arr[10], k, max; k=0;
for(k=0;k<5;k++) cout<< "Enter the numbers, one on each line:\n";
{ while(k<1 0)
cout<< "Enter a number:"; {
cin>> a[k]; cin>> arr[k];
} k=k+1;
total=0; }
for(k=0;k<5;k++) max=arr[0];
total=total+a[k]; k=1;
avg=total/5; while(k<10)
cout<< "\nTotal="<<total<<endl; if(arr[k]>max)
cout<< "Average="<<avg<<endl; max=arr[k];
getch(); cout<< "The biggest number is " <<max; getch();
} }
Using Arrays in Programs
Q.1: Write a program that reads marks of 25 students and prints
the number of students passed. The marks are in the range of 0 to
100 and passing marks are 50.
The sizeof() Function
• The sizeof() function provides #include<iostream>
the number of bytes occupied to using namespace std;
store values for data type named main()
within the parenthesis. It is used {
to determine the amount of cout<< "\nData Type Byte”;
storage reserved for int, float, cout<< "\n------------ -------”;
double, char, etc. data types. cout<< "\nInt “ << sizeof(int);
cout<< "\nFloat “ << sizeof(float);
cout<< "\nDouble“ << sizeof(double);
cout<< "\nChar “ << sizeof(char);
}
Two Dimensional Arrays
• A two dimensional array uses a • A two dimensional array a,
single variable name to that has three rows and five
represent a collection of same
type of data that is in the form of columns is shown below.
a table or matrix. It has two
dimensions i.e. vertical and
horizontal dimensions. Vertical
dimension represents rows and
horizontal dimension represents
columns. Two dimensional array
provides an easy way of
handling data that is stored in
the form of a table.
Defining a Two Dimensional Array
• To define a two dimensional array in C++, the type of the
elements, the name of the array and the number of elements it is
required to store in rows and columns is mentioned in the
declaration statement.
• The following is the general form of declaration of two
dimensional array.
datatype arrayname[rowsize][columnsize];
• For example
int a[3][5];
float height[8][10];
Initializing a Two Dimensional Array
• Just like one dimensional array, two • Here nested braces are used for
dimensional array can also be assigning values to each row of the
initialized in declaration statement. array. This statement can be written on
The following statement declares and a single line as:
initializes a two dimensional array int a[3][4]={{45,66, 39,72},{87, 50, 56,
called a that has 3 rows and 4 columns 63}, {44, 23, 58, 88}};
and assigns values to it. • The above statement can also be
• int a [3] [4] = written using a single set of braces as
{ shown below.
{45, 66, 39, 72}, //Elements of first row int a[3][4]={45, 66, 39, 72, 87, 50, 56, 63,
{87, 50, 56, 63}, //Elements of second row 44, 23, 58, 88};
{44,23, 58, 88} //Elements of third row • The following statement initializes a
} two dimensional array of type float
with 5 rows and 2 columns.
float weight[5][2]= { {3.40, 2.75}, {4.75,
3.28}, {8.10, 6.22}, {4.71, 3.92}, {1.43,
7.25} };
Accessing and Filling a Two Dimensional
Array
• Data can be written in any k[1][3]=15;
element of a two dimensional • Two dimensional arrays are
array as if it was a normal generally accessed row by row
variable by specifying the using nested loop. Therefore,
index of row and column. For the row index is used as outer
example the following loop variable and column
assignment statement will index as inner loop variable.
store the value 15 in the
element at row 2 and column
4 of two dimensional array
named k.
Accessing and Filling a Two Dimensional
Array
• The following program demonstrates how two-dimensional array elements are
accessed using nested loop.
#include<iostream.h>
using namespace std;
main()
{
int i, j, total,k[3][4]={{30, 20, 55, 206},{78, 81, 25, 94},{3, 48, 67, 104}};
total=0;
for(i=0;i<3;i++)
// i represents row number of array k
for(j=0;j<4;j++)
// j represents column number of array k
total=total+k[i][j];
cout<< "Total="<<total<<endl;
}
Accessing and Filling a Two-Dimensional
Array
#include<iostream>
#include<iostream.h> using namespace std;
#include<iomanip.h> main()
using namespace std; { int a[3][4], i,j, max;
main() for(i=0;i<3;i++)
{ for(j=0;j<4;j++)
int i, j, k[3][4]={{1,2,3,4}, {5,6,7,4},{9,10,11,12}}; {
for(i=0;i<3;i++) cout<<"Enter values for the matrix row "<<i+1 <<" and
for(j=0;j<4;j++) Column "<<j+1<<endl;
cout<<setwidth(5)<< k[i][j]*2; cout<<endl; cin>>a[i][j];
} }
max=a[0][0];
for(i=0;i<3;i++)
for(j=0;j<4;j++)
{
if(max<a[i][j])
max=a[i][j];
}
cout<<"The max values in the matrix is "<< max << endl;
}
String
• String is a sequence of characters. In C++, character string is
stored in a one dimensional array of char data type. Each
element of character string holds one character. All the strings
end with a special character, known as null character and it is
represented by '\O'. The null character is automatically
appended at the end of string. String is most commonly used
item is computer programming to represent name, address,
object, book title, etc.
A String
• To define a string in C++, the data type char, the name of string
and the number of characters it is required to store is
mentioned in the declaration statement.
• The following is the general form of declaration of string.
char stringname[stringsize];
• For example
char weekday[10];
char studentname[20];
• Note: Since the null character is appended at the end of string,
if a string has n characters then the stringsize should be at least
n+1.
Initializing Strings
• Just like arrays of integer and floating-point numbers, strings arrays
can also be initialized in the declaration statement.
• For example, the following statement declares and initializes the
string variable weekday to Sunday.
char weekday[10]= {'S', 'u', 'n', 'd', 'a', 'y'};
• The next statement provides another easy way for the same
declaration and initialization.
char weekday[10]= "Sunday";
• It allows to declare and initialize the string variable by including the
weekday within double quotes. When a string variable is initialized in
this way as a whole, the curly brackets are not required.
Initializing Strings
• The following diagram shows how the • The index starts from zero. The compiler
string variable weekday is represented in automatically places the null character (/0)
computer. after the last character. The remaining
three characters are not defined.
• Another way used to initialize a string
variable is to type the contents within the
curly brackets but without mentioning its
size by leaving the square brackets empty.
This is shown in the following example.
char city[]= "Karachi";
• In this statement city is a string variable
that holds 8 characters. Although,
"Karachi" has 7 characters, the null
character is automatically appended to the
end of the string which makes it a string of
size 8.
Commonly Used String Functions
• To use strings in computer programs, it is essential to learn how
string functions are used.
• The header file <string.h> is used when string functions are
used in the program. C++ supports a large number of string
handling functions in the standard library <string.h>.
• The most commonly used string functions are :
• cin.get() Function
• strcpy() Function
• strcat() Function
• strlen() Function
• strcmp() Function
cin.get() Function
• This function is used to read a #include<iostream.h>
string from the keyboard that #include<string.h>
may contain blank spaces. using namespace std;
The general form of cin.get() // header file to use string functions
function is: main()
cin.get(strvar, strsize); { char str[50];
• It has two arguments. First cout<< "Enter a string:";
argument strvar, is the name cin.get(str,50) ;
of the string variable and the cout<< "You typed:"<<str<<endl;
second argument strsize, is }
the maximum size of the
string or character array.
cin.get() Function
• A string can also be read using cin #include<iostream .h>
statement but it has some using namespace std;
limitation. This is shown in the main()
following program. { char str[50];
cout<< "Enter a string:";
cin>>str;
cout<< "You typed:"<<str<<endl;
}
• The following is the execution of the
program.
• Enter a string: Information Technology
• You types: Information
strcpy() Function
• The strcpy() functions is used to #include<iostream.h>
copy contents of a string #include<string.h>
variable or string constant to using namespace std;
another string variable. main()
• The general form of strcpy() {
function is: char string1 [10]= "ISLAMABAD",
string2[10], string3[10];
strcpy(string2,string1 ); strcpy(string2,string1 );
• It has two arguments, string1 cout<<"string2="<<string2<<endl;
and string2 which are string strcpy(string3, "PAKISTAN");
variables. When it is executed, cout<<"string3="<<string3<<endl;
contents of string1 will be copied }
to string2.
strcat() Function
• The strcat() function is used #include<iostream.h>
for concatenation or joining of #include<string.h>
two strings. using namespace std;
• The general form of strcat() main()
function is: {
strcat(string1 ,string2); char string1 [10]= “Pakistan ",
string2[10]=“Zindabaad”;
• When this function is strcat(string1,string2 );
executed, it will append cout<<string1<<endl;
(concatenate) string2 onto the }
end of string1.
strlen() Function
• The strlen() function is used to #include<iostream.h>
return the length (the number of #include<string.h>
characters) of a string. The general using namespace std;
form of strlen() function is: main()
strlen(string); {
char city1 ="LAHORE", city2= "ISLAMABAD",
• Here, string is a string variable. For city3= "KARACHI";
example, cout<<"Characters in city1 are: "<< strlen(city1 )<<endl;
char string[10]="COMPUTER"; cout<<"Characters in city2 are: "<< strlen(city2)<<endl;
cout<<"The number of characters in cout<<"Characters in city3 are: "<< strlen(city3)<<endl;
the string are“ <<strlen(string)<<endl; }
• The output of the above code will
be:
The number of characters in the string
are 8
strcmp() Function
• The strcmp() function compares two strings and #include<iostream>
returns an integer value based on the result of #include<string.h>
comparison. This comparison is based on ASCII
codes of characters. using namespace std;
• The general form of strcmp() functions is: main()
strcmp(string1 ,string2); {
char string1[10] ="MANGO", string2[10]= "MANGO",
• When it is executed, it will compare the first string3[10]= "POTATO", string4[10]="ORANGE";
characters of string1 and string2. If they are the
same, it will compare the second pair of int x, y, z;
characters. The comparison will continue until x=strcmp(string1 ,string2);
the characters differ or a terminating null- cout<<"string1 and string2 are equal, x="<<x<<endl;
character is reached. During comparison, A is
considered less than B and B is considered less y=strcmp(string3,string1);
than C and so on. cout<<"string3 is greater than string1, y="<<y<<endl;
• The function will return the following integer z=strcmp(string1 ,string4);
values based on the result of comparison. cout<<"string1 is less than string4, z="<<z<<endl;
• It will return O if string1 and string2 are the same. }
• It will return 1 if string 1 is greater than string2.
• It will return -1 if string1 is less than string2.