// Some examples that are somewhat like homework 1 as far as being // wrong and yet close to working #include // Purpose: A function to return the sum of the elements of the integer array // Parameters: list = array of integers, size = length of the array // Returns: sum of the numbers in list // Bug: Works only if the last number happens to be the sum // (everything else adds up to 0) int sum(int * list, int size) { int result = 0; for (int i = 0; i < size; i++) result = list[i]; // another possibility to get the same problem is // the following loop body: // { // result = 0; // result = result + list[i]; // } return result; } // Purpose: Another function to return the sum of the elements of the // integer array // Parameters: list = array of integers, size = length of the array // Returns: sum of the numbers in list // Bug: Works only if the first number happens to be 0 int sum2(int * list, int size) { int result = 0; for (int i = 1; i < size; i++) result = result + list[i]; return result; } // Purpose: Print out the numbers in the array on a line // Does not end with an end-of-line character // Parameters: list = array of integers, size = length of the array // Returns: nothing // Bug :) Not really good if the list of numbers is too big to fit on a line void printarray(int * list, int size) { for (int i = 0; i < size; i++) cout << ' ' << list[i]; } int main() { // Array where last element is the sum int v1[4] = { 8, -15, 7, 20 }; const int V1SIZE = sizeof(v1)/sizeof(int); // Array where first element is 0 int v2[5] = { 0, -1, 7, 2, 3 }; const int V2SIZE = sizeof(v2)/sizeof(int); // Displaying the data to make it easier to check if the results // satisfy the requirements cout << "v1 = "; printarray(v1, V1SIZE); cout << endl; cout << "v2 = "; printarray(v2, V2SIZE); cout << endl; cout << "--------------------------------" << endl; cout << "PROBLEM 1" << endl; cout << "--------------------------------" << endl; // correctly handles case where last element is sum cout << "The sum of v1 = " << sum(v1, V1SIZE) << endl; // incorrectly handles case where last element is not the sum cout << "The sum of v2 = " << sum(v2, V2SIZE) << endl; cout << "--------------------------------" << endl; cout << "PROBLEM 2" << endl; cout << "--------------------------------" << endl; cout << "The sum of v1 = " << sum2(v1, V1SIZE) << endl; cout << "The sum of v2 = " << sum2(v2, V2SIZE) << endl; }