More Practice Problems (Fall 2013)

From CDOT Wiki
Jump to: navigation, search
  • Walkthrough 1
#include <iostream>
 #include <cstring>
 using namespace std;

 class Data {
     char string[31];

     public:

     Data(char s[]) { strcpy(string, s); }

     const char* out() const { return string; }
 };

 struct Node {
     Data string;
     Node* next;
     Node(char* s, Node* n) : string(s), next(n) {}
 };

 void display(Node* n) {

         while(n) {
            cout << n->string.out();
            n = n->next;
         }
         cout << endl;
 }

 int main () {

     Node* node = NULL, *current, *remove;

     node = new Node("wolf ", node);
     node = new Node("bad ",  node);
     node = new Node("big ",  node);
     node = new Node("The ",  node);

     display(node);

     current = node->next;
     remove  = current;
     current = current->next;
     delete remove;

     node->next = current;

     display(node);

     current = node->next;
     remove  = current;
     current = current->next;
     delete remove;

     node->next = current;

     display(node);

     while (node) {

         remove = node;
         node = node->next;
         delete remove;
     }
 }
  • Walkthrough 2
#include <iostream>
 using namespace std;

 unsigned x(unsigned a, unsigned b) {
     unsigned c = 0u;

     while (b) {
         if (b & 1) {
               cout << "c: " << c << ", a: " << a << endl;
               c += a;
               cout << "c: " << c << endl;
             }
         a <<= 1;
         b >>= 1;
     }
     return c;
 }

 int main () {

     cout << 27u << " \? " << 2u << " = " << x(27u, 2u) << endl;
     cout <<  7u << " \? " << 3u << " = " << x(7u,  3u) << endl;
 }
  • Coding Question
Code a C++ class template FunnyQueue<T>. The template can be used to create queues of different data types.
The constructor takes an integer argument (size). It allocates memory for an array of size elements
and initializes the queue to be empty. The member function enqueue inserts an element of data type T
at the end of the queue. Note: Enqueue will not add the element if the queue is already full.
The member function dequeue removes an element from the front of the queue.
Note: It's all right that the memory location will be left unused as a result of calling the dequeue function.
The member function length returns the total number of values that are currently stored in the queue.
The destructor deallocates the memory.

int main(){
    FunnyQueue<int> queue(4);  // the queue is empty

    cout << queue.length() << endl;

    queue.enqueue(100);
    queue.enqueue(200);
    queue.enqueue(300);
    cout << queue.dequeue() << endl;
    cout << queue.dequeue() << endl;
    cout << queue.length() << endl;
   
    queue.enqueue(400);
    queue.enqueue(500);  // the queue is already full!!!
    queue.enqueue(600);  // the queue is already full
   
    cout << queue.length() << endl;
    return 0;
}

Output of the main program:

0
100
200
1
2