3. What is a Array?
An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
An array must be defined before it can be used to store information.
An array definition specifies a variabel type and a name.
6. Two-Dimensional Arrays
you can create an array of an array known as multi-dimensional array.
data_type array_name[x][y]; For example: int x[3][4];
Here, x is a two dimensional array. It can hold a maximum of 12 elements. You can think
this array as table with 3 rows and each row has 4 columns as shown below.
7. Two-Dimensional Arrays
#include <iostream>
using namespace std;
int main () {
// an array with 2 rows and 2 columns.
int a[2][2];
Int i,j;
// input each array element's value
for ( i = 0; i < 2; i++ )
for ( j = 0; j < 2; j++ ) {
cout << "a[" << i << "][" << j << "]: ";
cin>> a[i][j];
cout<< endl;
}
// output each array element's value
cout<< "PRINT" <<endl;
for ( i = 0; i < 2; i++ )
for ( j = 0; j < 2; j++ ) {
cout << "a[" << i << "][" << j << "]: ";
cout<<a[i][j]<< endl;
}
}
8. Passing Arrays to Functions
C program to pass an array containing age of person to a function. This function should
find average age and display the average age in main function.
#include <iostream>
#include <iomanip>
using namespace std;
float average(float age[]);
int main()
{
float avg, age[6];
cout<<"age:"<<endl;
for (int i=0;i<6;i++){
cin>>age[i];
}
avg = average(age); /* Only name of array is passed as
argument. */
cout<<"Average age="<<setprecision(2)<<avg;
}
float average(float age[])
{
int i;
float avg, sum = 0.0;
for (i = 0; i < 6; ++i) {
sum += age[i];
}
avg = (sum / 6);
return avg;
}
9. EXERCISES 1
Write a program that to store and print odd & even number entered
by the user (Storing 10 number entered by user in an array)
10. EXERCISES 2
Write a program using function and array that to store and print value of f(x) = x2+
3x + 1, then find the values. (Storing 5 number entered by user in an array)
11. EXERCISES 3
Write a program that calculates Two-Dimensional
Arrays (Add & Substract)