/* Mukkarum Amin Spring 2002 CS 201 Assignment 5 Pascal's Triangle */ #include #include struct Node //Linked List struct { long double data; Node *link; }; void prompt (); void chkval(int& ); void chkchr(char& ); void list_fill (Node*& ); void list_walk (Node*& ); void list_clear (Node*& ); void main () // Driver only { prompt (); } void prompt () { //Prompt for # of rows to print out int triangle_size; char print_again; Node *head_ptr; head_ptr = NULL; cout << "How many rows of Pascal's triangle would you like to output? "; cin >> triangle_size; chkval(triangle_size); cout << endl; for (int count = 0; count < triangle_size; count++) { list_fill (head_ptr); cout << endl; } cout << "\n\nWould you like to print another triangle (Y/N) ? "; cin >> print_again; print_again = tolower(print_again); chkchr(print_again); if (print_again == 'y') { list_clear(head_ptr); prompt(); } else list_clear(head_ptr); //Delete Nodes before exiting program } void chkval(int& value) { //Check if the number of rows entered by user is valid do { if (value < 0) { cout << "The number you entered is not valid." << "\nPlease enter a positive integer: "; cin >> value; } } while (value < 0); } void chkchr (char& character) { //Check if character entered by user is valid do { if (character != 'y' && character != 'n') { cout << "The character you entered is not valid." << "\nPlease enter Y/y or N/n: "; cin >> character; } } while (character != 'y' && character != 'n'); } void list_fill (Node*& head_ptr) { //Check if header is null if it is add the first node otherwise call list_walk if (!head_ptr) { Node *insert_ptr; insert_ptr = new Node; insert_ptr->data = 1; insert_ptr->link = head_ptr; head_ptr = insert_ptr; cout << insert_ptr->data << " "; } else if (head_ptr != NULL) list_walk(head_ptr); } void list_walk (Node*& head_ptr) { /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Walk through linked list adding the data values and storing them in cursor Since no new node is created in the for loop after each execution the first '1' in the triangle has been replaced by another value; to counter this a new node is added to the beginning of the list and set to '1' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ Node *cursor; cursor = head_ptr; cout << cursor->data << " "; for (cursor = head_ptr; cursor != NULL; cursor = cursor->link) { Node *next; next = cursor; if (cursor->link) { next = next->link; cursor->data = next->data+cursor->data; } cout << cursor->data << " "; } Node *insert_ptr; insert_ptr = new Node; insert_ptr->data = 1; insert_ptr->link = head_ptr; head_ptr = insert_ptr; } void list_clear (Node*& head_ptr) { //Clears the list so when a new triangle is printed the data will not be corrupt Node *remove; while (head_ptr != NULL) { remove = head_ptr; head_ptr = head_ptr->link; delete remove; } }