Notes on Program 2
Array Declaration
- Array size must be specified at compile time, not
run time.
- Right:
const MAX_ELEMENTS = 50;
int theArray[MAX_ELEMENTS];
float values[10];
- Wrong:
int size;
cin >> size;
int theArray[size];
Finding the Largest Value
in an Array (or the Mode)
- Choose a current largest value,
compare each array element to it.
If an element is larger than currentLargest, replace value of currentLargest with new value.
- Right:
currentLargest = frequency[0];
for(i = 1; i <
size; i++) // can also use a while loop
if (frequency[i] > currentLargest)
currentLargest
= frequency[i];
- Wrong:
currentLargest = frequency[0];
for(i = 0; i <
size; i++)
if (frequency[i+1] >
frequency[i])
currentLargest
= frequency[i + 1];
Finding The
Median In An Array
- Use the % operator to determine if the number
of elements is odd or even.
- For an even number of values, say 8, the array
indexes are 0, 1, 2, 3, 4, 5, 6, 7. The median is the average of the two
middle numbers in this case, array[3] and array[4]. In general, find the average of array[size/2 - 1] and array[size/2] (or, array[(size-1)/2] and array[(size-1)/2 + 1] )
- For an odd number of values, choose the middle
element: array[size/2] (or, array[(size-1)/2 ] - since its integer division, you get
the same answer either way).
Functions
- Use the BubbleSort
function as a function.
- Dont modify the function or add to it a
function should be cohesive.
- Cohesive functions have a single purpose solve
one logical problem
Printing 10 elements per
line
for
(i = 0; i < size; i++)
if(i % 10
== 0)
cout << endl;
cout
<< val[i] << endl;