Pointers

Additional Example


PROBLEM:

Write a program which prompts the user to enter 10 integer numbers into an array. The program will then search the array to find if a zero is present in the array. If a zero is present it will print out the number of elements in the array before the zero occurs.

Write this program making use of pointers to search the array and compare it to writing the solution using arrays only.


SOLUTION:

The program will still need to declare an array of 10 elements as normal. It will also declare a pointer to an integer.


        int     array[10];
        int     *array_ptr;
The program will then prompt the user to enter the elements into the array. It uses the variable index to count when 10 integers have been entered. The integers are read into successive elements. The name of the array is a pointer to the beginning of the array, this pointer is moved along the array by adding the index to it.

        cout << "Enter 10 numbers \n";
        for (index =0; index < 10; index ++)
                cin >> *(array + index);

The pointer is then set to point to the beginning of the array.

        array_ptr = array;
The program then increments along the array looking for a zero and checking that it has not reached the end of the array.

        while (*array_ptr != 0 && (array_ptr - array < 10))
                array_ptr ++;
This checks if the contents of the array poistion the array_ptr is pointing to contains a zero and if it has yet looked at 10 elements. If both condtions are false it increments the pointer to point to the next element in the array.

Final Program:


#include <iostream.h>

main()
{
        int     array[10];
        int     *array_ptr;
        int     index;


        cout << "Enter 10 numbers \n";
        for (index =0; index < 10; index ++)
                cin >> *(array + index);

        array_ptr = array;

        while (*array_ptr != 0 && (array_ptr - array < 10))
                array_ptr ++;

        if (array_ptr - array < 10)
                cout << "There are " << array_ptr - array << 
                        " elements before the zero\n";
        else
                cout << "There is no zero in the array\n";
}

The same program could also have been written using the array and the integer index. No pointers are required.


#include <iostream.h>

main()
{
        int     array[10];
        int     index;


        cout << "Enter 10 numbers \n";
        for (index =0; index < 10; index ++)
                cin >> array[index];

	// reset index back to 0
        index = 0;

        while (array[index] != 0 && index < 10)
                index ++;

        if (index < 10)
                cout << "There are " << index << 
                        " elements before the zero\n";
        else
                cout << "There is no zero in the array\n";
}

Both programs perform the same task.


Back to Main Page for Lecture 7