/* * File: prog.cpp * Written by: Gali Diamant * Based on idea by: Robert I. Pitts * Last Modified: February 22, 2003 */ #include #include "Node.h" using namespace::std; /************************ Function Prototypes *********************/ // PrintValues: Prints the values with +'s between each. void PrintArray(float values[], int howmany); // SumValues: Returns the sum of the values. float ArraySumValues(float values[], int howmany) // ArrayToList: Create a linked list from values in array bool ArrayToList(float values[], int howmany, Node *); // ListSumValues: Compute the sum of the values in the linked list float ListSumValues(Node *list); // PrintList: Print values in linkied list void PrintList(Node *list); // FreeList: Free all allocated memory void FreeList(Node *list); /*************************** Main Function *************************/ int main() { const int MAX_VALUES = 10; // Can deal with at most MAX_VALUES numbers. float values[MAX_VALUES]; // Array to hold the numbers. int howmany; // How many numbers entered. node *list = NULL; cout << "Enter numbers to sum below (separated by spaces)." << endl << "Enter 0 (zero) as the last number." << endl; do { // Read the next number. cin >> values[howmany]; // Increment the count. howmany++; // Should error check "howmany"! } while (values[howmany-1] != 0); if (ArrayToList(values, howmany, list) == false) { // something went wrong, so free the memory and exit FreeList(list); return 1; } float array_sum = ArraySumValues(values, howmany); float list_sum = ListSumValues(list); cout << "ArraySum = " << array_sum << endl; cout << "ListSum = " << list_sum << endl; FreeList(list); return 0; } void test(int *num) { if (num) cout << "yes" << endl; else { cout << "no" << endl; num = new int(3); } } /************************ Function Definitions *********************/ void PrintArray(float values[], int howmany) { for (int i = 0; i < howmany; i++) { if (i != 0) // Print "+" before all but first number cout << " + "; cout << values[i]; } } float ArraySumValues(float values[], int howmany) { float sum = 0; for (int i = howmany; i > 0; i--) { sum += values[i]; } return sum; } bool ArrayToList(float values[], int howmany, Node *list) { // PrintArray(values, howmany); int i = 0; Node *tmp; list = NULL; for (i = 0; i < howmany; i++) { tmp = new Node; if (tmp == NULL) return false; tmp->item = values[i]; tmp->next = list; list = tmp; } return true; } float ListSumValues(Node *list) { Node *tmp=list; float sum = 0; while (tmp) { sum += tmp->item; tmp = tmp->next; } return sum; } void PrintList(Node *list) { Node *tmp=list; cout << endl << "list:" << endl; while (tmp) { cout << tmp->item << " "; tmp=tmp->next; } cout << endl; } void FreeList(Node *list) { Node *tmp = list; while (tmp) { list=list->next; delete tmp; tmp = list; } }