Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

1.

int array[10] = {4, 6, 2, 3, -1, -3, 2, 2, -7, 9}; int index; cin >> index; //7 int *p = array + index; //p points to array[7] for (int i = 0; i < 5; i++) { int hops = *p; //hops = 2 hops = -9 hops = 4 hops = -1 hops = 3 p += hops; //array[9] array[0] array[4] array[3] array[6] } cout << *p << endl 2. Design the class Goldfish class Goldfish { public: Goldfish(int capacity); ~Goldfish(); void remember(char c); void forget(); //Clears memory using . void printMemory() const; //Prints contents of m_memory private: char *m_memory; //Pointer to memory int m _amount; //# of chars remembered int m_capacity; //# of chars this fish can remember }; a. Define the constructor. Dynamically allocate capacity-many characters to m_memory. Initialize m_memory with dots. If capacity is not positive, then set it to 3 by default. Remember to set m_capacity. Goldfish::Goldfish(int capacity) { if (capacity < 1) m_capacity = 3; else m_capacity = capacity; //Record the capacity m_memory = new char[m_capacity]; //Allocate the memory m_amount = 0; //Initialize the amount of memory used forget(); //Fill in the dots } b. Implement remember. Store the character c into m_memory. If you already have m_capacity characters memorized, then discard the oldest character in m_memory to open up a free slot. void Goldfish::remember(char c) { if (m_memory == m_capacity) { for (int i = 0; i < m_capacity 1; i++) m_memory[i] = m_memory[m_memory + 1]; m_amount--; } m_memory[m_amount] = c; m_amount++; } c. Implement forget(). Goldfish::forget() { for (int i = 0; i < m_capacity; i++) m_memory[i] = .; m_amount = 0; } d. Implement destructor(). Goldfish::~Goldfish() { delete [] m_memory; } 3. int *p1, *p2, v1; p1 = &v1; //p1 contains pointer that points to v1 v1 = 0; *p1 = 42; //*p1 and v1 refer to same variable cout << v1; //42 cout << *p1; //42 p2 = p1; cout << &p2; //42 &x: generate a pointer to x address of x *p: follow pointer p object that p points to dereference p

4. int MAX_FISH = 20; class Aquarium { public: Aquarium(); bool addFish(int capacity); Goldfish *getFish(int n ); void oracle(); ~Aquarium(); private: Goldfish *m_fish[MAX_FISH]; //pointers to fish int m_nFish; //# of fish }; a. Define the constructor. Initially, there is no fish in Aquarium. Aquarium::Aquarium():m_nFish(0) {} b. Implement addFish, which (dynamically) adds a new Goldfish into the Aquarium, with the specified memory capacity. If the fish cannot be added because the Aquarium already has MAX_FISH residing, return false and dont add any. Else, return true. bool Aquarium::addFish(int capacity) { if (m_nFish >= MAX_FISH) return false; m_fish[m_nFish] = new Goldfish(capacity); m_nFish++; return true; } c. Implement getFish, which returns the pointer to the nth Goldfish that is added. Return NULL if there is less than n fish in the Aquarium, or if n is an invalid position. Goldfish* Aquarium::getFish(int n) { if (n < 0 || n >= m_nFish) return NULL; return m_fish[n]; } d. Implement the destructor. Remove all dynamically allocated objects. Aquarium::~Aquarium() { for (int i = 0; i < m_nFish; i++) delete m_fish[i]; } e. Implement oracle(). It prints the memory of ALL Goldfish in the Aquarium. You can use the member function printMemory of Goldfish class. Once everything is printed, reset all Goldfishs memories using forget function. void Aquarium::oracle() { for (int i = 0; i < m_nFish; i++) { m_fish[i]->printMemory(); m_fish[i]->forget(); } } 5. Design BankAccount class, which lets the owner to deposit and withdraw money using a password. -There should be no default constructor. -There should only be one constructor, which takes in the initial balance in dollars, and the password. The password is an integer, most likely 4 digits. The initial amount must not be negative, if it is negative, set it to $0.00 by default. Your BankAccount class should be able to keep track of the balance up to the last cent. -It should support two operations, deposit and withdraw. Both must be Boolean functions. One must specify the amount of money he wants to deposit/withdraw, and the password. If the password is incorrect, the return value must be false. Also, for withdraw, if the requested amount exceeds the current balance or is negative, return false and do not change anything. If the deposit amount is negative, do not change the balance and return false. -Add a Boolean function setPassword, which takes in 2 passwords the original password and the new password. If the original password does not match, return false and do not change password. If the original password is correct, update the password with the new password. -Provide an accessor function balance, which accepts the password. If the password is correct, return the balance. If not, return -1.

class BankAccount { public: BankAccount(double initAmt, int pwd); double balance(int pwd) const; bool deposit(double amt, int pwd); bool withdraw(double amt, int pwd); bool setPassword(int oldPwd, int newPwd); private: double m_balance; int m_password; bool checkPwd(int pwd) const; }; BankAccount::BankAccount(double initAmt, int pwd):m_password(pwd) { if (initAmt > 0) m_balance = initAmt; else m_balance = 0; } double BankAccount::balance(int pwd) const { if (checkPwd(pwd)) return m_balance; else return -1; } bool BankAccount::deposit(double amt, int pwd) { if (checkPwd(pwd) && amt >= 0) { m_balance += amt; return true; } return false; } bool BankAccount::withdraw(double amt, int pwd) { if (checkPwd(pwd) && amt >= 0 && amt <= m_balance) { m_balance -= amt; return true; } return false; } bool BankAccount::setPassword(int oldPwd, int newPwd) { if (checkPwd(oldPwd)) { m_password = newPwd; return true; } return false; } bool BankAccount::checkPwd(int pwd) const { return m_password == pwd; } Write a (global) function getNewAccount which takes in a password as the only parameter and returns a pointer to a dynamically created BankAccount instance with $10 in it. BankAccount* getNewAccount(int pwd) { return new BankAccount(10, pwd); } 6. double w = 5.2; double x = 5.1; double *p = &w; *p = 8.5; p = &x; cout << *p; //writes 5.1 cout << w; //writes 8.5 double *q; q = p; double *r = &w; *r = x; if (p == q) //true both point to x if (*p == *r) //true, comparing doubles

7. class CoinMoon { public: CoinMoon(); void addDollar(); //Add a dollar coin to the machine void addQuarter(); //Add a quarter to the machine void addDime(); //Add a dime to the machine void addPenny(); //Add a penny to the machine void giveMeBills(); //Print what the user will get private: int totalInCents; }; CoinMoon::CoinMoon():totalInCents(0) {} void CoinMoon::addDollar() { totalInCents += 100; } void CoinMoon::addQuarter() { totalInCents += 25; } void CoinMoon::addDime() { totalInCents += 10; } void CoinMoon::addPenny() { totalInCents += 1; } void CoinMoon::giveMeBills() { int dollars = totalInCents/100; totalInCents %= 100; int quarters = totalInCents/25; totalInCents %= 25; int dimes = totalInCents/10; totalInCents %= 10; int nickels = totalInCents/5; totalInCents %= 5; int pennies = totalInCents; cout << dollars, quarters, etc totalInCents = 0; } 8. Implement the class Hotel, as declared below, which keeps track of the reservation status of each room in the hotel. Each room can be RESERVED, OCCUPIED, or EMPTY, and this information is stored in a 2-dimensional array, where each row represents a floor, and each column represents a room. Each room is represented by an integer (e.g., 425). For example, the status of room 425 is stored in m_rooms[4][25]. const char RESERVED = R; const char OCCUPIED = O; const char EMPTY = E; const int FLOORS = 20; const int ROOMSPERFLOOR = 50; class Hotel { public: Hotel(); bool reserve(int roomNum); bool cancel(int roomNum); bool checkIn(int roomNum); bool checkOut(int roomNum); int numEmpty(int floor) const; private: char m_rooms[FLOORS][ROOMSPERFLOOR]; bool validNum(int roomNum); bool changeState(int roomNum, char from, char to); }; Hotel::Hotel() { for (int i = 0; i < FLOORS; i++) for (int j = 0; j < ROOMSPERFLOOR; j++) m_rooms[i][j] = EMPTY; }

bool Hotel::reserve(int roomNum) { return changeState(roomNum, EMPTY, RESERVED); } bool Hotel::cancel(int roomNum) { return changeState(roomNum, RESERVED, EMPTY); } bool Hotel::checkIn(int roomNum) { return changeState(roomNum, RESERVED, OCCUPIED); } bool Hotel::checkOut(roomNum) { return changeState(roomNum, OCCUPIED, EMPTY); } int Hotel::numEmpty(int floor) { if (floor < 0 || floor >= FLOORS) return -1; int count = 0; for (int i = 0; i < ROOMSPERFLOOR; i++) { if (m_rooms[floor][i] == EMPTY) count++; } return count; } bool Hotel::validNum(int roomNum) { int floor = roomNum/100; int room = roomNum % 100; return (floor >= 0 && floor < FLOORS) && (room >= 0 && room < ROOMSPERFLOOR); } bool Hotel::changeState(int roomNum, char from, char to) { if (validNum(roomNum) && m_rooms[roomNum/100][roomNum%100] == from) { m_rooms[roomNum/100][roomNum % 100] = to; return true; } return false; } 9. int main() { int arr[3] = { 5, 10, 15 }; int* ptr = arr; *ptr = 10; // set arr[0] to 10 *(ptr + 1) = 20; // set arr[1] to 20 ptr += 2; ptr[0] = 30; // set arr[2] to 30 while (ptr >= arr) { cout << ' ' << *ptr; // print values ptr--; } cout << endl; } b. void findDisorder(int arr[], int n, int* &p) { for (int k = 1; k < n; k++) { if (arr[k] < arr[k-1]) { p = arr + k; return; } } p = NULL; } The original findDisorder function does not work because it only changes the local variable (int* p) and if you want to change the actual pointer, youd have to access the pointer (address) itself.

c. int main() { double* p = new double; hypotenuse(1.5, 2.0, p); cout << "The hypotenuse is " << *p << endl; } It may not work because it is simply a pointer to a double and it is pointing to nothing in memory. d. bool match(const char str1[], const char str2[]) { while (*str1 != 0 && *str2 != 0) // zero bytes at ends { if (*str1 != *str2) // compare corresponding characters return false; str1++; // advance to the next character str2++; } if (*str1 == 0 && *str2 != 0) return false; if (*str1 != 0 && *str2 == 0) return false; else return true; } The first problem with this code is that its comparing addresses of str1 and str2 to each other rather than the characters held at the addresses. The second problem is that when the loop ends, it is supposed to return true if the strings are the same. The third problem is that this function does not take into consideration if one of the strings were shorter than the other. 10a. string* fp; //Declares a pointer variable fp that points to type string b. string fish[5]; //Declares fish to be 5-element array of strings c. fp = &fish[4]; //Makes fp point to last element of fish d. *fp = salmon; //Makes string pointed by fp equal to salmon e. *(fish+3) = yellowtail; //Sets 4th element of fish array = yellowtail f. fp -= 3; //Moves fp pointer back by 3 strings g. fp[1] = eel; //Sets 3rd element (index[2]) of fish = eel h. fp[0] = tuna; //Sets string pointed by fp = tuna i. bool d = (fp == fish); j. bool b = (*fp == *(fp+1)); 11a. double computeAverage(const double* scores, int numScores) { const double* ptr = scores; double tot = 0; int pos = 0; while (ptr + pos != scores + numScores) { tot += *(ptr + pos); pos++; } return tot/numScores; } b. const char* findTheChar(const char* str, char chr) { for (int k = 0; *(str + k) != 0; k++) if (*(str + k) == chr) return (str + k); return NULL; } c. const char* findTheChar(const char* str, char chr) { while (*str != \0) { if (*str == chr) return str; str++; } return NULL; 12. int* minimart(int* a, int* b) { if (*a < *b) return a; else return b; }

void swap1(int* a, int *b) { int* temp = a; a = b; b = temp; } void swap2(int* a, int *b) { int temp = *a; *a = *b; *b = temp; } int main() { int array[6] = { 5, 3, 4, 17, 22, 19 }; int* ptr = minimart(array, &array[2]); //returns address of array[2] because 5 > 4 == pointer is pointing to element 3 (index 2) ptr[1] = 9; //sets value at ptr[1] to 9, so array[3] is 9 ptr += 2; //increments pointer by 2, so at array[5] *ptr = -1; //set value at array[5] to -1 *(array+1) = 79; //sets value at array[1] to 79 because array was at initial position cout << "diff=" << &array[5] - ptr << endl; //5th element of array pointed to array[6] ptr (pointer pointed to array[5]) = 6-5 = 1 swap1(&array[0], &array[1]); //swaps addresses of array[0] and array[1] only swap2(array, &array[2]); //swaps the elements of array[0] and array[2] for (int i = 0; i < 6; i++) cout << array[i] << endl; } //4 //79 //5 //9 //-1 //19 13. void deleteG(char* c) { char* temp = c; while (*c != '\0') { *c = *temp; temp++; if (*c != 'g' && *c != 'G') c++; } *c = *temp; } int main() { char msg[100] = "I recall the glass gate next to Gus in Lagos, near the gold bridge."; deleteG(msg); cout << msg; // prints I recall the lass ate next to us in Laos, near the old bride. } 14. cons tint MAXSIZE = 5; double da[MAXSIZE]; double *dp; for (int k = 0; k < MAXSIZE; k++) da[k] = 3.6; for (dp = &da[0]; dp < &da[5]; dp++) == (dp = da; dp < da+MAXSIZE; dp++) *dp = 3.6; 15. string names[5] = {meg, haley, maebe, lisa, mallory}; int n = lookup(&names[2], 3, lisa) // 1 maebe, lisa, mallory C-strings char string[] = xxxxxxxxxxx strcpy(target, source, delimiter) stcmp(string 1, string 2) -string 1 > string 2 return + else return strlen(string)

Strings str.substr(pos, length) //returns string starting at pos w/ length str.size() cin.ignore(100000, \n) cin.getline(string var, maxchar)

You might also like