You are on page 1of 17

Arrays

An array is a collection of several data items of the same data type. It consists of
several contiguous memory locations storing data. It removes the cumbersome task
of defining separate variables for each data item. A single variable can be used to
store one or more data items. For example, if you want to store ages of 10 students
of a class, you can easily declare an array of integer type of size 10 instead of
declaring 10 variables of integer type each storing age of a student. The general
form of the single dimension array is:-

General format:

type variable_name [size];

The type is the base type of the array and which is the type of each of the element
of the array. The size is the no of the elements in the array. The variable_name is
the name of the identifier holding the array. For example,

int age [10];

The age is an array of type integer whose size is 10. It can hold 10 data values. The specific
element in the array can be accessed using an index. An index is the offset from the first element
of the array. For example, first element has an index of 0 while the third element has an index of
2. The integer age has elements from age[0] to age[9]. Here is a program which illustrates the
working of arrays.

#include<iostream.h>

void main ()

int age[10];

int i,sum=0, avg=0;

int max,min;

Programming II C++- Prepared by Syed Ibrahim Page 1


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

cout << "Enter the age of the student " << i+1 <<endl;

cin >> age[i];

max=min=age[0];

for(i=1;i<10;i++)

sum=sum+age[i];

if(age[i]>max)

max=age[i];

if(age[i]<min)

min=age[i];

avg=sum/10;

cout << "Average age of the students of the class : " << avg <<
endl;

cout << "Maximum age of the student of the class : " << max <<
endl;

Programming II C++- Prepared by Syed Ibrahim Page 2


cout << "Minimum age of the student of the class : " << min <<
endl;

The result of the program is:-

Initializing Arrays

The arrays can be initialized by giving the initial values in a list and enclosed in
curly brackets, which is placed after the equal sign which is put after the declaration
of the array. For example,

int age[5]={12,13,10,24,15};

Elements of the array have values 12, 13, 10, 24, 15. The elements age[0] has
value 12 and age[4] will have 15. If the elements of the array are not initialized
then they take some garbage value before they are assigned to some specified
value. There is also another way of initializing all the elements of the array to be
zero. For example,

int age[5]={0};

Programming II C++- Prepared by Syed Ibrahim Page 3


will initialize all the elements of the array age to be zero. If you want some of the
elements to be initialized with specific value and rest of the values to be zero then
here is an example.

int age[5]={12,13};

The elements age[0] and age[1] will be initialized to 12 and 13 respectively and rest
of the elements will be initialized to zero.

Null Terminated Strings

The most common use of one dimensional array is for character strings. The null
terminated string is a character array with a null character at the end. The
characters form the string with a null character indicating the termination of the
string. A null terminated string can be declared as

char name[10];

it will hold 10 characters with a null at the end. The size of the array can be more
than the length of the array. The array can be initialized as

char name[10]={'f','a','t','h','m',’a’};

The first 6 elements are initialized and rest elements are null characters. Here is a
program which calculates the length of the string.

// program which calculates the length of the string

#include<iostream.h>

void main()

char name[15];

int i=0;

cout << " Enter your name " << endl;

cin >> name;

Programming II C++- Prepared by Syed Ibrahim Page 4


while(name[i]!='\0')

i++;

cout << "Lenght of the name is : " << i << endl;

OUTPUT:

Enter your name

ibrahim

Lenght of the name is : 7

Searching Arrays: Linear Search


• Search array for a key value

• Linear search

– Compare each element of array with key value

• Start at one end, go to other

– Useful for small and unsorted arrays

• Inefficient, if search key not present, examines


every element

#include<iostream.h>

void main ()

int array[10]={10,22,75,4,80,6,7,68,79,14};

int key,x;

cin>> key;

Programming II C++- Prepared by Syed Ibrahim Page 5


int flag = 0; // set flag to off

for(int i=0; i<10; i++) // start to loop through the array

if (array[i] == key) // if match is found

flag = 1; // turn flag on

x=i;

break ; // break out of for loop

if (flag) // if flag is TRUE (1)

cout<< "Your number is at subscript position " <<++x<<".\n";

else

cout<< "Sorry, I could not find your number in this array."<<endl<<endl;

Programming II C++- Prepared by Syed Ibrahim Page 6


Introduction to Two-Dimensional
Arrays
Objectives:

• To be able to declare a two-dimensional array.


• To be able to perform fundamental operations on a two-dimensional
array.
• To be able to view a two-dimensional array as an array of arrays.

Two-dimensional arrays, the most common multidimensional arrays, are


used to store information that we normally represent in table form. Two-
dimensional arrays, like one-dimensional arrays, are homogeneous. This
means that all of the data in a two-dimensional array is of the same type.
Examples of applications involving two-dimensional arrays include:

• a seating plan for a room (organized by rows and columns),


• a monthly budget (organized by category and month), and
• a grade book where rows might correspond to individual students and
columns to student scores.

The two dimensional array can be declared as

int age[2][5]; this array has two rows and 5 columns.

Two-Dimensional Array Initialization


We can declare and initialize an array A as follows:

//declaration

Programming II C++- Prepared by Syed Ibrahim Page 7


int A[3][4] = {{8, 2, 6, 5}, //row 0
{6, 3, 1 ,0}, //row 1
{8, 7, 9, 6}}; //row 2

Memory for the array may be visualized as:

Example-I

#include<iostream.h>

void main ()

int age[2][5]= { {12,13,14,15,15}, { 12,16,17,13,12}};

int i,j;

int sum=0,avg=0;

for(i=0;i<2;i++)

for(j=0;j<5;j++)

sum=sum+age[i][j];

avg=sum/5;

cout << "Average of the elements of the row " << i+1 << "
is " << avg << endl;

sum=0;

Programming II C++- Prepared by Syed Ibrahim Page 8


}

The result of the program is: -

Example-II

#include<iostream.h>

#include<conio.h>

main()

clrscr();

char week[7][9] =
{“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,”Saturday};

clrscr();

cout<<”The third element of the two dimensional array is”<<week[2]<<endl;

cout<<”The first element of second row of two dimensional array is”<<week[2][1];

getch();

Output:

The third element of the two dimensional array is Tuesday

The first element of second row of two dimensional array is u

Programming II C++- Prepared by Syed Ibrahim Page 9


No. of Rows =7 (0 -6) No.of.Columns = 9(0-8)

0 1 2 3 4 5 6 7 8

S U N D A Y
M O N D A Y
T U E S D A Y
W E D N E S D A Y
T H U R S D A Y
F R I D A Y
S A T U R D A Y

Example-III

#include <iostream.h>

int main()

int age [] = {16, 2, 77, 40, 12};

char name[5][5]={"jane","fred","mary","henry","john"};

int i;

int total_age = 0, average_age = 0;

for ( i=0 ; i<5 ; i++ )

cout << name[i] << ": " << age[i] << "\n";

total_age += age[i];

Programming II C++- Prepared by Syed Ibrahim Page 10


average_age = total_age/5;

cout << "Average Age: " << average_age << "\n";

return 0;

OUTPUT:

If the above program is compiled and run then it will give the following result:

Jane: 16

Fred: 2

Mary: 77

Henry: 40

John: 12

Average Age: 29

Example-IV

SEARCHING NAMES IN AN ARRAY- SEQUENTIAL SEARCH

#include<iostream.h>

#include<string.h>

main( )

int FOUND=1;

int NOTFOUND=0;

char name[6][10] = {"laila","hawa","halima","mabrooka","mohamed","syed"} ;

int i, flag, a ;

Programming II C++- Prepared by Syed Ibrahim Page 11


char yourname[10] ;

cout<< "\nEnter your name ";

cin>>yourname;

flag = NOTFOUND ;

for ( i = 0 ; i <= 5 ; i++ )

a = strcmp (name[i], yourname ) ;

if ( a == 0 )

cout<< "Welcome\t"<<name[i]<<" your name is in the list";

flag = FOUND ;

break ;

if ( flag == NOTFOUND )

cout<<"Sorry\t"<<yourname<<" your name is not in the list";

OUTPUT:

Enter your name syed

Welcome syed your name is in the list

Enter your name rahim

Sorry rahim your name is not in the list

Two dimensional Array- Find the highest


temperature

Programming II C++- Prepared by Syed Ibrahim Page 12


#include<iostream.h>

#include<conio.h>

main()

clrscr();

int temp[3][4] = {{26, 34, 22, 17},{24, 32, 19, 13},{28, 38, 25, 20}};

int highest = 0;

for (int i = 0; i < 3; ++i)

for (int j = 0; j < 4; ++j)

if (temp[i][j] > highest)

highest = temp[i][j];

cout<<"highest temperature is"<<highest;

Two-dimensional Array: Example

• Program showing

– initialization

– Compute the sum of array elements on the first diagonal

– Compute the sum of array elements on the second diagonal

– Compute the sum of array elements above the first diagonal

– Compute the sum of array elements bellow the first diagonal

Example: Values in the array are:

1 2 3

4 5 6

Programming II C++- Prepared by Syed Ibrahim Page 13


7 8 9

#include <iostream.h >

int main()

int array[ 3 ][ 3 ] = { { 1, 2, 3 },{ 4, 5, 6 } ,{ 7, 8, 9 } };

cout << "Values in the array are:" << endl;

// sum the values on the first diagonal

int sumDiag1 = 0;

for ( int i = 0; i < 3; i++ )

sumDiag1 += array[ i ][ i ] ;

cout << "Sum of Values on first diagonal:" << sumDiag1 << endl;

cout << endl;

// sum the values on the second diagonal

int sumDiag2 = 0;

for ( int i = 0; i < 3; i++ )

sumDiag2 += array[ i ][ 3 - i - 1 ] ;

cout << "Sum of Values on second diagonal:" << sumDiag2 << endl;

cout << endl;

// sum the values above the first diagonal

int sumAbove = 0;

for ( int i = 0; i < 3; i++ )

for ( int j = 0; j < 3; j++ )

if ( i < j )

sumAbove += array[ i ][ j ] ;

Programming II C++- Prepared by Syed Ibrahim Page 14


cout << "Sum of Values above diagonal:" << sumAbove << endl;

cout << endl;

// sum the values bellow the first diagonal

int sumBellow = 0;

for ( int i = 0; i < 3; i++ )

for ( int j = 0; j < 3; j++ )

if ( i > j )

sumBellow += array[ i ][ j ] ;

cout << "Sum of Values bellow diagonal:" << sumBellow << endl;

cout << endl;

return 0; // indicates successful termination

} // end main

OUTPUT:

Values in the array are:

Sum of Values on first diagonal:15

Sum of Values on second diagonal:15

Sum of Values above diagonal:11

Sum of Values bellow diagonal:19

Palindrome ( madam, amma, liril)


(A word or group of words that read the same forward and backward)

#include<iostream.h>

#include<conio.h>

#include<string.h>

Programming II C++- Prepared by Syed Ibrahim Page 15


void main()

clrscr();

int pos,i,j;

j=0;

char s[20],s1[20];

cout<<"enter a string\n";

cin>>s;

pos=strlen(s);

for(i=pos-1;i>=0;i--)

s1[j]=s[i];

j+=1;

s1[j]='\0';

cout<<strlen(s)<<endl;

cout<<strlen(s1)<<endl;

cout<<s<<endl;

cout<<s1;

if(strcmp(s,s1)==0)

cout<<"given string is palindrome";

else

cout<<"not a palindrome";

getch();

Programming II C++- Prepared by Syed Ibrahim Page 16


Programming II C++- Prepared by Syed Ibrahim Page 17

You might also like