COMP 1672 Sections 1 & 2 Homework #3, solutions 1. What is the output from the following program? Give an explanation of what is happening line-by-line output is: 10 100 2000 3000 int main() { int nums[5]; // declare a 5-member integer array called nums nums[0] = 10; // initialize the nums[1] = 100; // values of the nums[2] = 1000; // array nums[3] = 2000; nums[4] = 3000; bar(nums); // call the function called bar, pass it the array return 0; // exit program, successfully } void bar(int *input) { cout << *input << endl; // input points to the first array element // (which is element number 0) // output its contents, which is the number 10 input++; // update the pointer to point to the 2nd // array element (which is element number 1) cout << *input << endl; // output its contents, which is the number 100 input+=2; // increment the pointer by 2, so it now points // to the 4th array element (element 3) cout << *input << endl; // output its contents, which is 2000 input++; // increment the pointer by 1, it points // to the 5th array element (element 4) cout << *input << endl; // output its contents, which is 3000. } 2. After the initializations, the memory map looks like this: 0x100: 6 /* note: the integer x is stored here 0x104: 7 /* note: the integer y is stored here 0x108: 0x100 /* note: the integer pointer p is stored here 0x10C: 0x104 /* note: the integer pointer q is stored here cout << x << " " << y << " " << p << " " << q << " " << *p << " " << *q << endl; The above line outputs 6 7 0x100 0x104 6 7 *p = 7; After this line is executed, here's the new memory map: 0x100: 7 /* note: the integer x is stored here 0x104: 7 /* note: the integer y is stored here 0x108: 0x100 /* note: the integer pointer p is stored here 0x10C: 0x104 /* note: the integer pointer q is stored here cout << x << " " << y << " " << p << " " << q << " " << *p << " " << *q << endl; The above line now outputs 7 7 0x100 0x104 7 7 if(p == q) // (No, p and q point to different places in memory!) { cout << "Equal" << endl; // this does NOT get output } p = q; // Now p takes the value 0x104 y = 10; // The value of y has been changed Here's the new memory map: 0x100: 7 /* note: the integer x is stored here 0x104: 10 /* note: the integer y is stored here 0x108: 0x104 /* note: the integer pointer p is stored here 0x10C: 0x104 /* note: the integer pointer q is stored here cout << x << " " << y << " " << p << " " << q << " " << *p << " " << *q << endl; The above line now outputs 7 10 0x104 0x104 7 10 3. Write a program using vectors that does the following (in order). #include #include using namespace std; int main() { vector myvector; vector ::iterator myiterator; myvector.push_back(3); myvector.push_back(6); myvector.push_back(8); myvector.pop_back(); cout << "The size of the vector is " << myvector.size() << endl; myvector.push_back(5); for (myiterator=myvector.begin(); myiterator!=myvector.end();myiterator++) cout << *myiterator << endl; myvector.clear(); return 0; }