Professional Documents
Culture Documents
COURSE/YEAR/SECTION INSTRUCTOR
Activity No. 7
Arrays (Part I)
Learning Outcomes The above program declares an array test with initial values
Discuss what are Arrays (1 to 5). The code demonstrates how to access array elements
Demonstrate how to work with one-dimensional in two ways:
arrays
test[3] = 8; // directly overwrites
Introduction // array element #3
// using the assignment
An Array is a variable that can hold multiple values of the
// operator
same data type.
and
Consider the following:
cin >> test[2]; // accepts input from the
double grade[27]; // user and assigns it to
// array element #2
The above declaration creates a one-dimensional array grade
that can hold a maximum of 27 values, or elements, of the To display array elements, we can use a loop to iterate from
type double. array element 0 to the last element:
NOTE: Declaring arrays this way gives the variable a fixed int main()
size that can’t be changed afterwards. {
int test[5] = {1, 2, 3, 4, 5};
In C++, each element in an array is associated with a number, int i;
called an array index. This index is used to access each value
cout << "The array elements are: ";
in an array. In the previous example, the first element of the
array grade is accessed as grade[0] and the last element is for(i=0; i<5; i++)
accessed as grade[26] or grade[array_size-1]. {
cout << test[i] << " ";
It is considered good practice to initialize our variables in }
order to prevent getting unpredictable results.
return 0;
}
Below is an example of initializing one-dimensional arrays
during declaration:
Try running the above program. What is the output?
int x[3] = {10, 9, 8};
return 0;
}
As mentioned earlier, we use indices to access and work with For array B:
each array element. Consider the following lines of code: Array Element Value
0 60
int main() 1 110
{ 2 40
int n[5] = {9, 5, 8, 7, 2}; 3 20
int sum;
Display the difference of each matching array value
int sum = n[0]+n[1]+n[2]+n[3]+n[4]
indices (for example, A[0] and B[0]).
cout<<"The sum of the elements are: ";
cout<<sum; Observation/Conclusion/Summary
return 0;
}
Programming Exercises
For array A:
Array Element Value
0 110
1 120
2 115
3 30