Arrays
One Dimensional arrays
Contents
 Arrays
Types of Arrays
 One-Dimensional Array
 Declaring One-Dimensional Array
 Initializing One-Dimensional Array
 Accessing elements of One-Dimensional Array
 Inputting elements of One-Dimensional Array
 Displaying elements of One-Dimensional Array
 Example programs
Need for array
Imagine you have to write a program to find the sum of marks of
15 students in a class.
For this we would have to declare 15 variables of the same type.
Further to enforce uniformity, we could take the names of the
variables as marks1, marks2, marks3….etc.
The program would look like this:
Need for array
#include<iostream.h>
void main()
{ int marks1, marks2, marks3, marks4, marks5, marks6, sum;
cout<<“n enter the marks of 6 students”;
cin>>marks1>>marks2>>marks3>>marks4>>marks5>>marks6;
sum= marks1+marks2+marks3+marks4+marks5+marks6;
cout<<“average marks are “<<sum/6;
}
In the above program, we have declared 6 variables to store marks of each of the 6 students and one
variable to accumulate the sum of marks. To declare and maintain such a large number of similar
variables makes the program bulky and inefficient. To avoid such a situation, we can use arrays.
What is an array?
An array is a series of elements (variables) of the same type which
can be referenced collectively by a common name.
These elements are placed in consecutive memory locations .
They can be individually referenced by adding an index or
subscript to the unique name.
In the above scenario, to store marks of the 6 students, we could
declare an array:
int marks[6];
Declaration of marks array and memory
representation
int marks[6]; Memory Representation
array name subscript or index value
array element
Name of the array
Number of elements
Data type of
the array
marks[5]
marks[3]
marks[2]
marks[1]
marks[0]
marks[4]
Types of arrays
There are basically two types of
arrays depending on the dimension
One dimensional arrays are used to
store lists of data items like marks of
20 students, age of 15 people in a
family etc.
Two dimensional arrays are used to
store list of lists, for example to store
the marks of 20 students in 6 subjects
Types of
Arrays
One
Dimensional
Two
Dimensional
Declaring a one-dimensional array
Syntax :
type name[integer constant/literal];
• type is the data type of the array. It can be int, float or char or
user defined(discussed in later chapters)
• name is any valid c++ identifier
• the number of elements in the array has to be an integer
constant or literal.
• The size of the array in bytes= data type size X no of elements
The elements of an array are the individual variables which can be
referenced by a subscript value
One dimensional array declarations
int runs[6];
Size of array=2X6=12 bytes
(size of int X no of elements)
Data type of
each element
Name of
the array
const int x=8;
int scores[x];
Here x is a named
constant with value 8.
Thus number of
elements in the above
array=8
float salary[20];
Size of array=4X20=80 bytes
(size of floatX no of elements)
Data type of
each element
No of elementsNo of elements
No of
elements
One dimensional arrays examples
One dimensional arrays are simple lists. They may be lists of
numbers, marks or characters depending on the data type of the
array. Examples:
 int age[20]; //represents the age of 20 people
 float salary[15];// represents the salary of 15 employees
 char alphabets[24];// represents the alphabets
Memory representation of an array
Consider the following array declaration:
int a[4]; memory representation
 Data type =integer
 Name=a
 Number of elements=4
 Size = 4 X 2=8 bytes array elements
Here a is an array having 4 elements , each of type int. Each of the element can
be referred individually using name of the array and subscript value eg, a[0],
a[1] etc.
a[0] a[2] a[3]a[1]
Note: the array subscript always starts from 0. The numbering of subscript of an
array with n elements varies from 0 to n-1. Thus an array of 4 elements will be
having subscripts from 0 to 3
Initializing an array
To initialize a one dimensional array we need to specify data values enclosed in
curly braces. These data values are called initializers.
Data-type name[size]={initialvalue1,initialvalue2, initialvalue3,initialvalue4…..};
The data type of the initializers should match with the data type of the array
and number of initializers should match with the size of the array.
If the number of initializers are more than the size of the array, an error is
generated.
Initializing an array
• Example :
int marks[6]={15, 24, 20, 18, 22, 25};
15 24 20 18 22 25
More examples of array initializations
• int age[4]={25, 34, 60, 22};
0 1 2 3
• float salary[8]={45.5, 34,5, 45.0, 87.0,56.5, 78.0, 90.0, 54.5, 67.0};
0 1 2 3 4 5 6 7
25 34 60 22
45.5 34.5 45.0 87.0 56.5 78.0 54.5 67.0
Accessing array elements
In one dimensional array, every element has one index number
 The index number always starts from 0.
For an array of n elements the index varies from 0 to n-1
Thus the index of the element is always one less than the element
number. For example the index value of the 6th element will be 5 and
the index of 1st item is 0.
 We can access any element using the array name along with the
element index value inside the square brackets.
We can display, input or perform any other action with the elements just
like simple c++ variables
Accessing array elements
The elements of an array can be accessed individually as well as
collectively.
To access individual array elements the syntax is :
name[subscript]
• Example :
For the array marks :
cout<< marks[1]; // displays 24
cout<<marks[4]; // displays 22
15
24
20
18
22
25
marks[0]
marks[1]
marks[2]
marks[3]
marks[4]
marks[5]
Accessing array elements individually
Consider an array : int num[4];
Let us assign some values to the
elements individually:
• Example :
num[0]=9;
num[2]=6;
9
6
0
1
2
3
Let us now do some more calculations
with elements of the same array :
• Example :
num[0]=num[0]+2 ;
(num[0]=9, num[0]+2=11)
num[3]=num[2]+num[0];
(num[2]=6, num[0]=11)
11
6
17
Some more examples of accessing array
elements
Example Statement Meaning
age[3]=22; Assign the value 22 to the 2nd element of the array age
runs[4]=20*2; Assign the product of 20 and 2 to the 5th element of the array
runs
cin>>list[5] ; Input the 6th element of the array list
scores[7]=scores[4]+90; Add 90 to the 5th element of array score and assign the result to
the 8th element of the array
cout<<age[8 ]; Display the content of the 9th element of array age.
average=(scores[0]+scores[1])/2; find the average of score 1 and 2 and assign it to the variable
average.
age[i-2]= s+t; Assign the sum of s and t to the element of array whose index is
given by the expression i-2
Accessing array elements collectively
To assign values collectively we use a loop
Let us assign some values to the elements of the same array
collectively:
• Example : num[0]:= i=0, i*2=0
for(int i=0;i<4; i++) num[1]:= i=1, i*2=2
num[i]=i*2; num[2]:= i=2, i*2=4
num[3]:= i=3, i*2=6
Thus using a loop we can access all the elements of the array one
by one(or sequentially). The value of the index varies from 0 to 3
thus assigning the values to the elements accordingly.
0
2
4
6
Input into an array
To input values into an array we can use the for loop. Each element is accessed
individually.
int nums[4];
for(int i=0; i<4; i++)
cin>>nums[i];
The value of i will vary from 0 to 3, thus in the first pass, value of i=0.
cin>>nums[i]= cin>>nums[0]
In the second pass, value of i=1, thus
cin>>nums[i]= cin>>nums[1] and so on.
Displaying contents of an array
To diplay values of an array we can use the for loop again to access each
element individually.
for( i=0; i<4; i++)
cout<<nums[i];
The value of i will vary from 0 to 3, thus in the first pass, value of i=0.
cout<<nums[i]= cout<<nums[0]
In the second pass, value of i=1, thus
cout<<nums[i]= cout<<nums[1]
and so on.
Program to input values into an array and
display array contents
#include<iostream.h>
void main()
{
int nums[4];
cout<<“Enter the list of numbers :”;
for(int i=0; i<4; i++)
cin>>nums[i];
cout<<“n The numbers you entered are :”;
for (i=0;i<4;i++)
cout<<nums[i]<<“n”;
}
Enter the list of numbers :
2
5
6
8
The numbers you entered are :
2
5
6
8
Output
Program to input the marks of 6 students and
find the average score
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float marks[6], sum=0;
for(int i=0; i<6; i++) //loop for reading marks
{
cout<< “Enter marks of student “<< i+1<<”:”;
cin>> marks[i];
}
for(int j=0; j<6; j++) //loop for accumulating sum of marks
{
sum=sum+marks[j];
}
cout<<endl<<”Marks you have entered are :”<<endl;
for(j=0; j<6; j++) //loop for displaying the marks
{
cout<< “Marks of student “<< j+1<<”:”;
cout<< a[j]<<endl;
}
cout<<”nTotal marks : “<<sum;
cout<<“nAverage marks :”<<sum/6;
getch();
}
Enter marks of student 1: 24
Enter marks of student 2: 25
Enter marks of student 3: 22
Enter marks of student 4: 20
Enter marks of student 5: 25
Enter marks of student 6: 22
Marks you have enetered are :
Marks of student 1:24
Marks of student 2:25
Marks of student 3:22
Marks of student 4:20
Marks of student 5:25
Marks of student 6:22
Total marks :138
Average marks :23
Output
Entering unknown number of elements
The memory is allocated to an array at compile time. So this makes
it compulsory to declare an array size at the time of declaration.
But at times we do not need to input or fill each and every array
element. For example, in a school we have to define an array
marks to store data of 50 students because maximum number of
students in any class in the school is 50. But there will be classes
having lesser number of students.
Entering unknown number of elements…contd
For this we need to partially
fill the array depending on
the number of students eg 25
or 40 etc. So we take a
variable say n and run the
loop from 0 to n-1.
int marks[50], n;
cout<<“nenter number of students:
“;
cin>>n;
for(int i=0;i<n;i++)
cin>>marks[i];
Here marks[50] is the array and n is
the number of students whose marks
are to be entered. So the loop will run
from 0 to n-1 and input marks of n
students.
Explanation
Example
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float marks[50], sum=0,n;
cout<<“Enter number of students in class:”;
cin>>n;
for(int i=0; i<n; i++) //loop for reading marks
{
cout<< “Enter marks of student “<< i+1<<”:”;
cin>> marks[i];
}
for(int j=0; j<n; j++) //loop for accumulating sum of marks
{
sum=sum+marks[j];
}
cout<<”nTotal marks : “<<sum;
cout<<“nAverage marks :”<<sum/n;
getch();
}
Program to input the marks of n students and
find the average score
Enter number of students in class
4
Enter marks of student 1: 90
Enter marks of student 2: 80
Enter marks of student 3: 75
Enter marks of student 4: 85
Total marks : 330
Average marks :82.5
Output
Program to read temperatures for unknown
number of days and find average temperature
#include<iostream.h>
void main()
{
float temp[20]; int n=0;char ch=‘y’;
do
{cout<<“nEnter temperature for day ”<<n+1<<“:”;
cin>>temp[n];
cout<<“nEnter more (y/n)? ”;
cin>>ch;
n++;
}while(ch!=‘n’ || ch!=‘n’);
for(int i=0; i<n;i++)
sum+=temp[i];
cout<<“nAverage temp is :”<<sum/n;
}
Enter temperature for day 1: 25.5
Enter more(y/n)? Y
Enter temperature for day 2: 26.5
Enter more(y/n)? Y
Enter temperature for day 3: 27.0
Enter more(y/n)? Y
Enter temperature for day 4: 24.5
Enter more(y/n)? Y
Enter temperature for day 5: 25.0
Enter more(y/n)? N
Average temp is : 25.7
Output
Array out of bounds
Consider the array marks declared in the above program to store
the marks of 6 students. Although we have input marks of 6
students using the loop. But what if a user enters more than 6
marks. Lets say marks of 20 students?
We would expect an error. But this does NOT happen. The data
thus entered will be placed in locations outside the array , maybe
in other programs’ memory.
This happens because, in c++ there is no way to check if the
number of elements entered into an array exceeds the size or
number of elements declared in the array.
This may cause some unexpected program behavior and may
cause errors.
Program to find maximum number in an array
#include<iostream.h>
void main()
{
int nums[20];
cout<<Ënter the number of list items:”;
cin>>n;
cout<<“Enter the list of numbers :”;
for(int i=0; i<n; i++)
cin>>nums[i];
int max=nums[0];
for (i=0;i<n;i++)
if(nums[i]>max)
max=nums[i];
cout<<“n The largest number is :”<<max;
}
Enter the number of list items:
6
Enter the list of numbers :
22
11
56
62
80
44
The largest number is : 80
Output

Arrays

  • 1.
  • 2.
    Contents  Arrays Types ofArrays  One-Dimensional Array  Declaring One-Dimensional Array  Initializing One-Dimensional Array  Accessing elements of One-Dimensional Array  Inputting elements of One-Dimensional Array  Displaying elements of One-Dimensional Array  Example programs
  • 3.
    Need for array Imagineyou have to write a program to find the sum of marks of 15 students in a class. For this we would have to declare 15 variables of the same type. Further to enforce uniformity, we could take the names of the variables as marks1, marks2, marks3….etc. The program would look like this:
  • 4.
    Need for array #include<iostream.h> voidmain() { int marks1, marks2, marks3, marks4, marks5, marks6, sum; cout<<“n enter the marks of 6 students”; cin>>marks1>>marks2>>marks3>>marks4>>marks5>>marks6; sum= marks1+marks2+marks3+marks4+marks5+marks6; cout<<“average marks are “<<sum/6; } In the above program, we have declared 6 variables to store marks of each of the 6 students and one variable to accumulate the sum of marks. To declare and maintain such a large number of similar variables makes the program bulky and inefficient. To avoid such a situation, we can use arrays.
  • 5.
    What is anarray? An array is a series of elements (variables) of the same type which can be referenced collectively by a common name. These elements are placed in consecutive memory locations . They can be individually referenced by adding an index or subscript to the unique name. In the above scenario, to store marks of the 6 students, we could declare an array: int marks[6];
  • 6.
    Declaration of marksarray and memory representation int marks[6]; Memory Representation array name subscript or index value array element Name of the array Number of elements Data type of the array marks[5] marks[3] marks[2] marks[1] marks[0] marks[4]
  • 7.
    Types of arrays Thereare basically two types of arrays depending on the dimension One dimensional arrays are used to store lists of data items like marks of 20 students, age of 15 people in a family etc. Two dimensional arrays are used to store list of lists, for example to store the marks of 20 students in 6 subjects Types of Arrays One Dimensional Two Dimensional
  • 8.
    Declaring a one-dimensionalarray Syntax : type name[integer constant/literal]; • type is the data type of the array. It can be int, float or char or user defined(discussed in later chapters) • name is any valid c++ identifier • the number of elements in the array has to be an integer constant or literal. • The size of the array in bytes= data type size X no of elements The elements of an array are the individual variables which can be referenced by a subscript value
  • 9.
    One dimensional arraydeclarations int runs[6]; Size of array=2X6=12 bytes (size of int X no of elements) Data type of each element Name of the array const int x=8; int scores[x]; Here x is a named constant with value 8. Thus number of elements in the above array=8 float salary[20]; Size of array=4X20=80 bytes (size of floatX no of elements) Data type of each element No of elementsNo of elements No of elements
  • 10.
    One dimensional arraysexamples One dimensional arrays are simple lists. They may be lists of numbers, marks or characters depending on the data type of the array. Examples:  int age[20]; //represents the age of 20 people  float salary[15];// represents the salary of 15 employees  char alphabets[24];// represents the alphabets
  • 11.
    Memory representation ofan array Consider the following array declaration: int a[4]; memory representation  Data type =integer  Name=a  Number of elements=4  Size = 4 X 2=8 bytes array elements Here a is an array having 4 elements , each of type int. Each of the element can be referred individually using name of the array and subscript value eg, a[0], a[1] etc. a[0] a[2] a[3]a[1] Note: the array subscript always starts from 0. The numbering of subscript of an array with n elements varies from 0 to n-1. Thus an array of 4 elements will be having subscripts from 0 to 3
  • 12.
    Initializing an array Toinitialize a one dimensional array we need to specify data values enclosed in curly braces. These data values are called initializers. Data-type name[size]={initialvalue1,initialvalue2, initialvalue3,initialvalue4…..}; The data type of the initializers should match with the data type of the array and number of initializers should match with the size of the array. If the number of initializers are more than the size of the array, an error is generated.
  • 13.
    Initializing an array •Example : int marks[6]={15, 24, 20, 18, 22, 25}; 15 24 20 18 22 25
  • 14.
    More examples ofarray initializations • int age[4]={25, 34, 60, 22}; 0 1 2 3 • float salary[8]={45.5, 34,5, 45.0, 87.0,56.5, 78.0, 90.0, 54.5, 67.0}; 0 1 2 3 4 5 6 7 25 34 60 22 45.5 34.5 45.0 87.0 56.5 78.0 54.5 67.0
  • 15.
    Accessing array elements Inone dimensional array, every element has one index number  The index number always starts from 0. For an array of n elements the index varies from 0 to n-1 Thus the index of the element is always one less than the element number. For example the index value of the 6th element will be 5 and the index of 1st item is 0.  We can access any element using the array name along with the element index value inside the square brackets. We can display, input or perform any other action with the elements just like simple c++ variables
  • 16.
    Accessing array elements Theelements of an array can be accessed individually as well as collectively. To access individual array elements the syntax is : name[subscript] • Example : For the array marks : cout<< marks[1]; // displays 24 cout<<marks[4]; // displays 22 15 24 20 18 22 25 marks[0] marks[1] marks[2] marks[3] marks[4] marks[5]
  • 17.
    Accessing array elementsindividually Consider an array : int num[4]; Let us assign some values to the elements individually: • Example : num[0]=9; num[2]=6; 9 6 0 1 2 3 Let us now do some more calculations with elements of the same array : • Example : num[0]=num[0]+2 ; (num[0]=9, num[0]+2=11) num[3]=num[2]+num[0]; (num[2]=6, num[0]=11) 11 6 17
  • 18.
    Some more examplesof accessing array elements Example Statement Meaning age[3]=22; Assign the value 22 to the 2nd element of the array age runs[4]=20*2; Assign the product of 20 and 2 to the 5th element of the array runs cin>>list[5] ; Input the 6th element of the array list scores[7]=scores[4]+90; Add 90 to the 5th element of array score and assign the result to the 8th element of the array cout<<age[8 ]; Display the content of the 9th element of array age. average=(scores[0]+scores[1])/2; find the average of score 1 and 2 and assign it to the variable average. age[i-2]= s+t; Assign the sum of s and t to the element of array whose index is given by the expression i-2
  • 19.
    Accessing array elementscollectively To assign values collectively we use a loop Let us assign some values to the elements of the same array collectively: • Example : num[0]:= i=0, i*2=0 for(int i=0;i<4; i++) num[1]:= i=1, i*2=2 num[i]=i*2; num[2]:= i=2, i*2=4 num[3]:= i=3, i*2=6 Thus using a loop we can access all the elements of the array one by one(or sequentially). The value of the index varies from 0 to 3 thus assigning the values to the elements accordingly. 0 2 4 6
  • 20.
    Input into anarray To input values into an array we can use the for loop. Each element is accessed individually. int nums[4]; for(int i=0; i<4; i++) cin>>nums[i]; The value of i will vary from 0 to 3, thus in the first pass, value of i=0. cin>>nums[i]= cin>>nums[0] In the second pass, value of i=1, thus cin>>nums[i]= cin>>nums[1] and so on.
  • 21.
    Displaying contents ofan array To diplay values of an array we can use the for loop again to access each element individually. for( i=0; i<4; i++) cout<<nums[i]; The value of i will vary from 0 to 3, thus in the first pass, value of i=0. cout<<nums[i]= cout<<nums[0] In the second pass, value of i=1, thus cout<<nums[i]= cout<<nums[1] and so on.
  • 22.
    Program to inputvalues into an array and display array contents #include<iostream.h> void main() { int nums[4]; cout<<“Enter the list of numbers :”; for(int i=0; i<4; i++) cin>>nums[i]; cout<<“n The numbers you entered are :”; for (i=0;i<4;i++) cout<<nums[i]<<“n”; } Enter the list of numbers : 2 5 6 8 The numbers you entered are : 2 5 6 8 Output
  • 23.
    Program to inputthe marks of 6 students and find the average score #include<iostream.h> #include<conio.h> void main() { clrscr(); float marks[6], sum=0; for(int i=0; i<6; i++) //loop for reading marks { cout<< “Enter marks of student “<< i+1<<”:”; cin>> marks[i]; } for(int j=0; j<6; j++) //loop for accumulating sum of marks { sum=sum+marks[j]; } cout<<endl<<”Marks you have entered are :”<<endl; for(j=0; j<6; j++) //loop for displaying the marks { cout<< “Marks of student “<< j+1<<”:”; cout<< a[j]<<endl; } cout<<”nTotal marks : “<<sum; cout<<“nAverage marks :”<<sum/6; getch(); } Enter marks of student 1: 24 Enter marks of student 2: 25 Enter marks of student 3: 22 Enter marks of student 4: 20 Enter marks of student 5: 25 Enter marks of student 6: 22 Marks you have enetered are : Marks of student 1:24 Marks of student 2:25 Marks of student 3:22 Marks of student 4:20 Marks of student 5:25 Marks of student 6:22 Total marks :138 Average marks :23 Output
  • 24.
    Entering unknown numberof elements The memory is allocated to an array at compile time. So this makes it compulsory to declare an array size at the time of declaration. But at times we do not need to input or fill each and every array element. For example, in a school we have to define an array marks to store data of 50 students because maximum number of students in any class in the school is 50. But there will be classes having lesser number of students.
  • 25.
    Entering unknown numberof elements…contd For this we need to partially fill the array depending on the number of students eg 25 or 40 etc. So we take a variable say n and run the loop from 0 to n-1. int marks[50], n; cout<<“nenter number of students: “; cin>>n; for(int i=0;i<n;i++) cin>>marks[i]; Here marks[50] is the array and n is the number of students whose marks are to be entered. So the loop will run from 0 to n-1 and input marks of n students. Explanation Example
  • 26.
    #include<iostream.h> #include<conio.h> void main() { clrscr(); float marks[50],sum=0,n; cout<<“Enter number of students in class:”; cin>>n; for(int i=0; i<n; i++) //loop for reading marks { cout<< “Enter marks of student “<< i+1<<”:”; cin>> marks[i]; } for(int j=0; j<n; j++) //loop for accumulating sum of marks { sum=sum+marks[j]; } cout<<”nTotal marks : “<<sum; cout<<“nAverage marks :”<<sum/n; getch(); } Program to input the marks of n students and find the average score Enter number of students in class 4 Enter marks of student 1: 90 Enter marks of student 2: 80 Enter marks of student 3: 75 Enter marks of student 4: 85 Total marks : 330 Average marks :82.5 Output
  • 27.
    Program to readtemperatures for unknown number of days and find average temperature #include<iostream.h> void main() { float temp[20]; int n=0;char ch=‘y’; do {cout<<“nEnter temperature for day ”<<n+1<<“:”; cin>>temp[n]; cout<<“nEnter more (y/n)? ”; cin>>ch; n++; }while(ch!=‘n’ || ch!=‘n’); for(int i=0; i<n;i++) sum+=temp[i]; cout<<“nAverage temp is :”<<sum/n; } Enter temperature for day 1: 25.5 Enter more(y/n)? Y Enter temperature for day 2: 26.5 Enter more(y/n)? Y Enter temperature for day 3: 27.0 Enter more(y/n)? Y Enter temperature for day 4: 24.5 Enter more(y/n)? Y Enter temperature for day 5: 25.0 Enter more(y/n)? N Average temp is : 25.7 Output
  • 28.
    Array out ofbounds Consider the array marks declared in the above program to store the marks of 6 students. Although we have input marks of 6 students using the loop. But what if a user enters more than 6 marks. Lets say marks of 20 students? We would expect an error. But this does NOT happen. The data thus entered will be placed in locations outside the array , maybe in other programs’ memory. This happens because, in c++ there is no way to check if the number of elements entered into an array exceeds the size or number of elements declared in the array. This may cause some unexpected program behavior and may cause errors.
  • 29.
    Program to findmaximum number in an array #include<iostream.h> void main() { int nums[20]; cout<<Ënter the number of list items:”; cin>>n; cout<<“Enter the list of numbers :”; for(int i=0; i<n; i++) cin>>nums[i]; int max=nums[0]; for (i=0;i<n;i++) if(nums[i]>max) max=nums[i]; cout<<“n The largest number is :”<<max; } Enter the number of list items: 6 Enter the list of numbers : 22 11 56 62 80 44 The largest number is : 80 Output