121: Computer Science 1 --- Lectures March 2,5

Topics:

Strings and Pointers

Call by Reference with pointers
Sorting routine Bubblesort
Pointer arithmetic and arrays  

Card Shuffling and Dealing Simulation

Discussion of example in Section 5.10 (Pages 333-338). Program Fig05_24.cpp

 

Call by Reference with Pointers

There are three ways to pass arguments to a function in C++, call-by-value, call-by-reference with reference arguments and call-by-reference with pointer arguments. We have already seen the first two ways. The following function utilizes call by references with pointers

 
void Square(int *NumberPtr) 
{
    *NumberPtr = *NumberPtr * *NumberPtr:
}

When this function is invoked in the main program, e.g.,

 
int main()
{
    int Number = 5;
    Square(&Number);
    cout << "\nThe new value of number is " << Number;
    return 0;
}

the new value of Number is 25. The following illustrates the swap function using call-by-reference with pointers.

Swap function

#include<iostream.h>
void Swap(int *, int *);
int main()
{          int Number1, Number2;
            cout << "Enter two integers: ";
            cin >> Number1 >> Number2;
            Swap(&Number1,&Number2);
            cout << "\nSwapped numbers are: " << Number1 << '\t' << Number2 << "\n\n";
    return 0;

}//END main()

void Swap (int *Element1Ptr, int *Element2Ptr)

{          int Temp = *Element1Ptr;
            *Element1Ptr = *Element2Ptr;
            *Element2Ptr = Temp;

}//END Swap()

The following is a rewrite of the program involving sorting grades where the functions including Insertion Sort use call-by-reference with pointers.

Insertion Sort

In class we will discuss Bubblesort. A discussion of Bubblesort is given in Section 4.7 on page 245 of text. Bubblesort using call-by-reference with pointers is discussed in Section 5.6 on page 299 of text. The following is a rewrite of the program involving sorting grades, where Bubblesort using call-by-reference with pointers is called instead of Insertionsort.

Bubblesort

Pointer Arithmetic and Arrays

Consider the example

int Numbers = {23, 5, 6, 7, 11};

int *NumPtr = &Number[0]

Then, *NumPtr = 23

Further,

*(NumPrt + 1) = 5, *(NumPrt + 2) = 6, *(NumPrt + 3) = 7, (NumPrt + 4) = 11

Now suppose we execute:

++NumPtr;

Then, *NumPtr = 5