Week#11 Arrays
Week#11 Arrays
Arrays
Lecture Outline
1 What is an array?
2 Defining and accessing Arrays
3 Arrays input
4 Arrays output
5 Example
1. What is an Array?
• Simple data types use a single memory cell to store a single value
of data
• For many problems you need to group data items together
• Array allows a programmer to group such related data items of
the same data type together into a single data structure (Array).
Syntax
Array_Type Array_Name[Length];
2. Defining an Array(initialization)
• We use indices to differentiate between the individual array elements
• If you have all the values at the point of declaring the array, you can
declare and initialize the array at the same time,
• If there are values in the initialization block, an explicit size for the
array does not need to be specified. Only an empty array element is
sufficient, C++ will count the size of the array for you.
#include <iostream>
using namespace std;
Write a int main( )
{
program to get const int SIZE = 10;
int a[ SIZE ], i, total = 0;
the average of float avg;
10 integers in for ( i = 0; i < SIZE; i++ )
{
an array. cout<<“\n enter the value”;
cin>>a[i];
total += a[ i ];
}
avg=total/10;
cout<< “Average of 10 elements =“<<avg;
return 0;
}
5. Example 2 #include <iostream>
using namespace std;
int main( void )
Write a program to {
const int SIZE =5;
input data into two int first[SIZE], second[SIZE], diff[SIZE], i;
arrays of size 5 cout<<“Enter”<<SIZE<<“data items for 1st array: ";
for(i=0;i<SIZE; i++) // input first array
elements each and cin>>first[i];
subtract their
cout<<"Enter”<<SIZE<<“data items for 2nd array : ";
corresponding for(i=0;i<SIZE; i++) // input second array
elements, cin>>second[i];
for(i=0;i<SIZE; i++) // compute the differences
storing the result in diff[i]= second[i] - first[i];
another array.
cout<<"\n\nOutput of the arrays : \n";
for(i=0;i<SIZE; i++) // output the arrays
cout<<“\t“<< first[i]<<“\t”<<second[i]<<“\t”<<
diff[i]<<endl ;
return 0;
}
5. Example 3