# CS210 Lab: Recursion Prelab Answers

1. Given the following piece of code, why aren't a and b exchanged after the call to exchange? (How could you modify the code?)
```void exchange(int, int);

int main
{
int a=5,b=7;

exchange(a,b);
}

void exchange (int x, int y)
{
int temp;

temp = x;
x = y;
y = temp;
return;
} // end exchange
```
In the above code, you are passing by value. This means that x and y are a copy of the arguments sent to this function. Instead, you want to use pass by reference, so that x and y refer to the same memory location as the arguments and thus, modify the contents at that address. To pass by reference, you can change the function header to the following:
```void exchange (int& x, int& y)
```
2. What is the difference between ClearPtr and ClearPtr2 in the following code? Will both pointer and pointer2 be set to 0 after the calls to ClearPtr and ClearPtr2. Why/Why not?
```#include<iostream>
using namespace std;

void ClearPtr(int *&p);
void ClearPtr2(int *p2);

int main()
{
int x=5, x2=6;
int *pointer, *pointer2;

pointer=&x;
pointer2=&x2;

cout << "x is: " << *pointer << endl;
cout << "pointer is holding address: " << pointer << endl;
cout << endl;
cout << "x2 is: " << *pointer2 << endl;
cout << "pointer2 is holding address: " << pointer2 << endl;
cout << endl;

ClearPtr(pointer);
ClearPtr2(pointer2);

cout <<"pointer is holding address: " << pointer << endl;
cout <<"pointer2 is holding address: " << pointer2 << endl;

return 0;
}

void ClearPtr(int *& p)
{
p=0;
}

void ClearPtr2(int *p2)
{
p2=0;
}
```
Try running this code.
In fact, pointer will be set to zero, but not pointer2.
The difference is in the "&", in void ClearPtr(int *& p) function. This means that you are passing by reference rather than by value.

The thing to remember about pass by reference is if you modify the value p, it will be remembered in "main".

3. Write a code segment to move through a linked list of characters and remove all occurances of the letter 'c'.
```
template < class DT >
void List<DT>:: cRemove ()
{
ListNode <DT> *prevptr, *ptr;
ptr=head; //start at the beginning

//cycle through list
while (ptr !=0)
{

//look for the letter 'c'
if (ptr->dataItem=='c') //process it
{
if (ptr==head) //special case when at beginning
{
delete ptr;
//reassign ptr and prevptr to beginning of new list
}
else
{
prevptr->next=ptr->next;
delete ptr;
ptr=prevptr->next;

}
}
else
{
prevptr=ptr;
ptr=ptr->next; //move along
}
}
}
```

 CS Dept Home Page CS Dept Class Files CS210 Class Files

Copyright: Department of Computer Science, University of Regina.