Module 16
Module 16
Declaration of arrays:
type name [elements];
Note: The 1st element in array is always initialized as 0, meaning if foo have 6
elements then panel numbering will be 0-5 to locate all foo elements in the
panel.
0 1 2 3 4
foo
regular arrays of local scope (for example, those declared within a function) are
left uninitialized. This means that none of its elements are set to any particular
value; their contents are undetermined at the point the array is declared.
But the elements in an array can be initialized to specific values when it is
declared, by enclosing those initial values in braces {}.
Example:
int foo [5] = { 16, 2, 77, 40, 12071 }; or int foo [] = { 16, 2, 77, 40, 12071 };
Represented as
0 1 2 3 4
foo 16 2 77 40 12071
The number of values between braces {} shall not be greater than the number of
elements in the array.
Example:
int foo [5] = { 16, 2, 77}; or int foo [] = { 16, 2, 77};
0 1 2 3 4
foo 16 2 77 0 0
When NO VALUES in {}
int foo [5] = {};
0 1 2 3 4
foo 0 0 0 0 0
Access the value of any of the elements in an array
Declaration:
name[index]
name is the identifier
index is the location of the value will be pull out within the array – int foo [5] = {
16, 2, 77, 40, 12071 };
foo 0 foo 1 foo 2 foo 3 foo 4
16 2 77 40 12071
Example:
foo [2] returns the value 77
foo [4] returns the value 12071
foo [5] will not return a value, the location is only 0-4 which is the 5
element
1. Create a C++ program that allows the user to choose what
element to access from {52, 85, 77, 21, 85, 54, 58, 32, 100, 98}.
2. Create a C++ program that lets users input an initialized value
for eight (8) elements.
#include <iostream>
using namespace std;
int main()
{
int element[8];
for(int x=0; x<=8;x++)
{
cout<<"Input value: ";
cin>>element[x];
}
cout<<"OUTPUT: ";
for(int y=0; y<=8;y++)
{
cout<<element[y]<<" ,";
}
return 0;
}