Programming With C++ - Lecture7
Programming With C++ - Lecture7
Lecture 7: Arrays
Sikander Naseem
2
Introduction
Sequential data storage
Tabulated database
An array is a sequence of data objects all of which have the
same type.
The data objects are called the elements of the array and are
numbered as 0, 1, 2, 3, ....
These numbers are called subscripts of the array pointing to
and giving access to the position of element.
Types
• One dimensional arrays (linear array)
• Multidimensional arrays
3
One dimensional
Syntax for defining arrays Data-type name[size];
float a[3]
Example float a[3]; 0 0.99
a[0] = 0.99;
1 78.1
a[1] = 78.1;
a[2] = 22.1; 2 22.1
One dimensional
Direct access
int main()
{ double a[3];
cin>>a[0];
cin>>a[1];
cin>>a[2];
cout << "a[0] = " << a[0] << endl;
cout << "a[1] = " << a[1] << endl;
cout << "a[2] = " << a[2] << endl;
}
5
One dimensional
Sequential access
int main()
{ int n;
cout << " Enter the size of array = ";
cin>>n;
double a[n];
cout << "Enter " <<n<< " numbers = ";
for (int i=0; i<n; i++)
{ cin >> a[i];}
for (int i=0; i<n; i++)
cout << "[" << i << "] = "<< a[i]<<endl;
}
6
Arithmetic operations between the
elements of arrays
int main()
{ int n;
int cost=0;
cout <<"Enter the no of cost items = ";
cin>>n;
float a[n];
cout<<"Enter "<< n <<" costs of items = ";
for (int i=0; i<n; i++)
cin>>a[i];
for (int i=0; i<n; i++)
cout<<"cost "<<i<<" = " <<a[i]<<endl;
for (int i=0; i<n; i++)
cost=cost+a[i];
cout<<" Total cost = "<<cost<<endl;
}
7
Multidimensional arrays
The element of an array can be almost any type, including
an array type.
So an array of array produces multi dimensional array
A one-dimensional array of one-dimensional arrays gives
a two-dimensional array; a one-dimensional array of two-
dimensional arrays gives a three-dimensional array; etc.
Example: double a[32][10]; //is a two dimensional array
a[25][8] = 99.1; // assign the value 99.1
to the element with
subscript (25,8).
8
Practice
Use the above example of multi dimensional array and
create a program to enter a matrix with m rows and n
columns.
Create one dimensional array of size n. The array asks
for data and calculates the average.
Enter two matrices and perform athematic operations
between the elements of the two.
10
The End
Reference book:
Programming with C++, SCHAUM’s outlines, John Hubbard,
3rd/2nd Edition, McGraw Hill, New Delhi