1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
// Array demo - demonstrate the use of arrays by
// reading a sequence of integers and then displaying them in order.
#include <cstdlib>
#include <iostream>
using namespace std;
// Prototype Declarations
int sumArray(int integerArray[], int sizeOffloatArray);
void displayArray(int integerArray[], int sizeOffloatArray);
int main(int argc, char *argv[])
{
//input the loop count
int nAccumulator = 0;
cout << "This program sums the values entered "
<< "by the user.\n";
cout << "Terminate the loop by entering a"
<< " negative number.\n";
cout << endl;
//store numbers into an array
int inputValues[128];
int numberOfValues;
for(numberOfValues =0;
numberOfValues < 128;
numberOfValues++)
{
//fetch another number
int integerValue;
cout << "Enter next number: ";
cin >> integerValue;
//if its negative...
if (integerValue < 0)
{
//...the break and exit
break;
}
//otherwise store the number into a new storage array
inputValues[numberOfValues] = integerValue;
}
//now output the values and the sum of the values
displayArray(inputValues, numberOfValues);
cout << "The sum is "
<< sumArray(inputValues, numberOfValues)
<< endl;
//wait until the user is ready before terminating the program
// to allow the iser to see the program results
system("PAUSE");
return 0;
}
//display array - Display the number of members of an array of length
// sizeOfArray
void displayArray(int integerArray[], int sizeOfArray)
{
cout << "The value of the array is: " << endl;
for (int i = 0; i < sizeOfArray; i++)
{
cout.width(3);
cout << i << ": " << integerArray[i] << endl;
}
cout << endl;
}
//sumArray - return the result of the memnbers of an integer array
int sumArray(int integerArray[], int sizeOfArray)
{
int accumulator = 0;
for (int i = 0; i < sizeOfArray; i++)
{
accumulator += integerArray[i];
}
return accumulator;
}
|