02 Arrays
02 Arrays
02 Arrays
Programming
Lec # 2
By
Engr. Sajid Saleem
Arrays & Vectors
Arrays
Declaring / Accessing Arrays
Passing Arrays to functions
Multi-dimentional arrays
Vector
Arrays
Collection of similar data types in consecutive
memory locations.
Declaring / Accessing Arrays
// Calculating gas mileage
#include <iostream>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
using std::setw;
int main()
{
const int MAX = 20; // Maximum number of values
double gas[ MAX ]; // Gas quantity in gallons
long miles[ MAX ]; // Odometer readings
int count = 0; // Loop counter
char indicator = y; // Input indicator
while( (indicator == y || indicator == Y) && count < MAX )
{
cout << endl
<< Enter gas quantity: ;
cin >> gas[count]; // Read gas quantity
cout << Enter odometer reading: ;
cin >> miles[count]; // Read odometer value
++count;
cout << Do you want to enter another(y or n)? ;
cin >> indicator;
}
Declaring / Accessing Arrays
if(count <= 1) // count = 1 after 1 entry completed
{ // ... we need at least 2
cout << endl
<< Sorry - at least two readings are necessary.;
return 0;
}
// Output results from 2nd entry to last entry
for(int i = 1; i < count; i++)
cout << endl
<< setw(2) << i << . // Output sequence number
<< Gas purchased = << gas[i] << gallons // Output gas
<< resulted in // Output miles per gallon
<< (miles[i] - miles[i - 1])/gas[i] << miles per gallon.;
cout << endl;
return 0;
}
Passing Arrays to functions
// Passing arrays and individual array elements to functions.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
int main()
{
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
namespace identifier
{
entities
} */
int main()
{
vector<double> student_marks(20);
return 0;
}
Topics Covered
C++ How to Program, Fifth Edition By
H.M.Deitel (Ebook references)
7.1 to 7.5 , 7.8 to 7.11