/*--- CS 111 - Week 15 Lecture 1 - 2024-12-10 by: Sharon Tuttle last modified: 2024-12-10 ---*/ #include <cstdlib> #include <iostream> #include <string> #include <cmath> using namespace std; /*=== REFACTORED to use a for loop (and +=) ===*/ /*=== signature: get_smallest: double[] int -> double purpose: expects an array of numbers and its size, and returns the value of the smallest element(s) in that array tests: if I have: double my_list[5] = {10, 20.1, 3, 4, 100}; get_smallest(my_list, 5) == 3 if I have: double my_quants[4] = {20, 66, 34, -5}; get_smallest(my_quants, 4) == -5 ===*/ double get_smallest(double numbers[], int size) { // make the smallest yet seen the 1st element double smallest_so_far = numbers[0]; // look for smaller elements within the numbers array for (int i = 0; i < size; i += 1) { // is the current element the smallest yet seen? // update smallest_so_far if so if (numbers[i] < smallest_so_far) smallest_so_far = numbers[i]; } // when the while loop finished, smallest_so_far // should now contain the smallest value in // the numbers array return smallest_so_far; } /*--- test the function above, and try out some of C++'s "shorthand" operators ---*/ int main() { cout << boolalpha; cout << endl; cout << "*** Testing: (refactored) get_smallest ***" << endl; double my_list[5] = {10, 20.1, 3, 4, 100}; cout << (get_smallest(my_list, 5) == 3) << endl; double my_quants[4] = {20, 66, 34, -5}; cout << (get_smallest(my_quants, 4) == -5) << endl; // playing around with += -= *= /= double num_val = 10; cout << endl; cout << "to start, num_val is: " << num_val << endl; num_val += 5; cout << "after num_val += 5; num_val is: " << num_val << endl; num_val -= 3; cout << "after num_val -= 3; num_val is: " << num_val << endl; num_val *= 2; cout << "after num_val *= 2; num_val is: " << num_val << endl; num_val /= 3; cout << "after num_val /= 3; num_val is: " << num_val << endl; // playing around with ++ int quant = 5; cout << endl; cout << "quant is: " << quant << endl; int amount; amount = 3 + (quant++); cout << endl; cout << "after amount = 3 + (quant++); amount is: " << amount << endl; cout << "after amount = 3 + (quant++): quant is: " << quant << endl; quant = 5; amount = 0; cout << endl; cout << "after resetting quant, quant is: " << quant << endl; amount = 3 + (++quant); cout << endl; cout << "after amount = 3 + (++quant): amount is: " << amount << endl; cout << "after amount = 3 + (++quant): quant is: " << quant << endl; // is this allowed? Yes; (amount)++; cout << endl; cout << "after (amount)++: amount is: " << amount << endl; cout << endl; // NOT ALLOWED -- ++ and -- must be used for things that can // be assigned to (and (++amount) cannot be assigned to) // ++amount++; return EXIT_SUCCESS; }