Arrays
Arrays Hold Multiple values
Unlike regular variables, arrays can hold multiple values.
Accessing Array elements
The individual elements of an array are assigned unique subscripts. These subscripts are used to access the elements.
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element int array to store the
// values.
#include
void main(void)
{
short hours[6];
cout << « Enter the hours worked by six employees: « ; cin >> hours[0];
cin >> hours[1];
cin >> hours[2];
cin >> hours[3];
cin >> hours[4];
cin >> hours[5];
cout << « The hours you entered are: »;
cout << » » << hours[0];
cout << » » << hours[1];
cout << » » << hours[2];
cout << » » << hours[3];
cout << » » << hours[4];
cout << » » << hours[5] << endl;
}
Program Output with Example Input
Enter the hours worked by six employees: 20 12 40 30 30 15 [Enter]
The hours you entered are: 20 12 40 30 30 15
Program 7.2
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element short array to store the
// values.
#include
void main(void)
{
short hours[6];
cout << « Enter the hours worked by six employees: « ;
for (int count = 0; count < 6; count++) cin >> hours[count];
cout << « The hours you entered are: »;
for (count = 0; count < 6; count++)
cout << » » << hours[count];
cout << endl;
}
Enter the hours worked by six employees: 20 12 40 30 30 15 [Enter]
The hours you entered are: 20 12 40 30 30 15
Program 7.3
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element short array to store the
// values.
#include
void main(void)
{
short hours[6];
cout << « Enter the hours worked by six employees.\n »;
for (int count = 1; count <= 6; count++)
{
cout << « Employee » << count << « : « ; cin >> hours[count – 1];
}
cout << « The hours you entered are\n »;