Wednesday, September 21, 2011

USING POINTERS IN A FUNCTION TO REVERSE AN ARRAY IN C++









REVISED: Sunday, March 3, 2013




CONTENTS:
I.        INTRODUCTION
II.      DOWNLOADING A FREE C++ COMPILER
III.     USING POINTERS IN A FUNCTION TO REVERSE AN ARRAY EXAMPLE PROGRAM SOURCE CODE
IV.      POINTERS
V.       POINTERS AND ARRAY NAMES
VI.     HOW TO DECLARE AND USE POINTERS
VII.    THE sizeof OPERATOR
VIII.  USING POINTERS IN A FUNCTION TO REVERSE AN ARRAY


YOU WILL LEARN HOW TO:
1. Download a free C++ compiler.
2. Install the Visual C++ Express Edition and start a new project.
3. Build, debug and compile a C++ program.
4. Declare and use pointers.
5. Use pointers in a function to reverse an array. 

I. INTRODUCTION

Welcome to the "Using Pointers in a Function to Reverse and Array Tutorial."


I do not know what your life experiences are or what you have already learned and done on your computer. Therefore, read the following steps and ignore any that you have either already done or do not want to do.

II. DOWNLOADING A FREE C++ COMPILER


Open Google and search for Microsoft's FREE Visual C++ Express Edition download page, or use the following link:

http://www.microsoft...press/download


Click download in the yellow Visual C++ box.

Click Run.

Click Next.


Read and, if you agree, accept the license terms, then click Next.

Complete the optional installation options, and then click Next.


Click Next to accept default location to download Google Microsoft's FREE Visual C++ Express Edition.

Open Visual C++ Express Edition.


After Visual C++ Express Edition opens, we have to start a new project for this tutorial.

Click File

Then click New

Then click Project

When the next window appears, click Win32

Then click Win32 Console Application.

Replace <Enter_name> with "first"

Press OK


When the next window appears, in the top left corner click Application Settings

Then click Console application

Then click Empty project

Then click Finish.

This creates a new project named first.


Now you need to add a .cpp file and a header file to your first project.


On the left center of your screen you will see a yellow folder marked Header. Right click the Header folder.

Then click Add

Then click New Item

Under Categories click Code

Under Templates click Header File

Replace <Enter_name> with first

Click Add


On the left center of your screen you will see a yellow folder marked Source Files. Right click the Source Files folder

Then click Add

Click New Item

Under Categories click Code

Under Templates click C++ File (cpp)

 Replace <Enter_name> with first

Click Add

Open the .cpp file

This is where you type your program.


III. USING POINTERS IN A FUNCTION TO REVERSE AN ARRAY EXAMPLE PROGRAM SOURCE CODE


To speed things up I have written the following example program for you.

Copy and past the example program shown below into your .cpp file.
//********************
//Using Pointers to
//Reverse an Array
//********************

#include <iostream>

using namespace std;

//********************

int reverseArray(float AnyArray[], int max);

//********************

int main(int argc, char* argv[])

{

    float AnyArray[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};

    int max = (AnyArray, (sizeof AnyArray)/(sizeof AnyArray[0]));

    cout << "The length of AnyArray is " << max
         << " elements." << endl << endl;

    cout << "The initial contents of the elements of AnyArray are as follows:"
         << endl << endl << endl;

    for(int nIndex = 0; nIndex < max;

 ++nIndex)

        cout << "AnyArray[" << nIndex << "]" << " = " << AnyArray[nIndex] << endl;

        cout << endl << endl << endl;

//********************

    reverseArray(AnyArray, max);

    cout << "The reversed contents of the elements of AnyArray are as follows:"
         << endl << endl << endl;

    for(int nIndex = 0; nIndex < max;

 ++nIndex)

        cout << "AnyArray[" << nIndex << "]" << " = " << AnyArray[nIndex] << endl;

    cout << endl << endl << endl;

    system("PAUSE");

    return 0;
}

//********************
//The reverseArray
//function reverses the
//elements of an array.

int reverseArray(float AnyArray[], int max)

{

    float* pPort = &AnyArray[0]; 
           
//declare pointer, assign
//address to pointer

    float* pStarboard = &AnyArray[max-1];
   
//declare pointer, assign
//address to pointer

    while(pPort < pStarboard) 
           
//establish loop condition

    {

        float exchange = *pPort;
   
        *pPort++ = *pStarboard;

        *pStarboard-- = exchange;

    }

    return max;

}

//********************



After you have done the copy and past, click Build

Then click Build Solution

When the build is completed click Debug

Then click Start Debugging


If everything went smoothly you will see displayed the output showing the original sample file we are working with, and the reverse of the file.


The program you copied and pasted is what we will be talking about during this tutorial.

IV. POINTERS

What is a pointer?


A pointer is a variable that holds a memory address. That’s it! If you understand this sentence you know the core of what there is to know about pointers.

V. POINTERS AND ARRAY NAMES


The array we are going to reverse in this tutorial is named AnyArray.

In C++ an array name is a constant pointer to the first element of an array.


Therefore, AnyArray == AnyArray[0] == *AnyArray


VI. HOW TO DECLARE AND USE POINTERS


Many programmers follow the convention of naming all pointers with the prefix p.


All pointers when they are declared should be initialized to something.


If you do not know what to initialize them to, initialize them to zero.


For example, the following statement declares pPort to be a pointer pointing to a float.


The type tells the compiler how much memory is needed for the object at the address.


The address of operator (&) is used to initialize

pPort to &AnyArray[0];


which is the address of the first element of AnyArray.

float* pPort = &AnyArray[0];

Every variable has an address.


The & address of operator is used to get the address of the variable.


The indirection operator (*), also called the dereference operator, retrieves the value at the address stored by the pointer.


The indirection operator (*), also called the dereference operator, retrieves the value at the address stored by the pointer.

VII. THE sizeof OPERATOR


The sizeof operator is used in the program to divide the number of bytes of the whole pointer array, the numerator by the number of bytes occupied by the first element of the array, the denominator.


Because each element of the array occupies the same amount of memory, the result, the quotient, is the number of elements in the array.


The quotient is passed to the function using the int variable named max.

VIII. USING POINTERS IN A FUNCTION TO REVERSE AN ARRAY


Now we ready for the fun part, the function!


The function is of type int, which means it passes an int type variable back to the main function.

The name of the function is reverseArray.


The function takes two arguments. The first argument is an array of type float named

AnyArray[] 


The second argument is a variable named max of type int.


To understand the function it is a good idea to look back and see how the main function provides the arguments for the function.

int max = (AnyArray, (sizeof AnyArray)/(sizeof AnyArray[0]));


Notice the use of the word AnyArray, as mentioned earlier this is the same as typing AnyArray[0] or *pAnyArray.


AnyArray[0] is used as the last denominator to help the compiler keep things straight.

The sizeof operator is used to get max.


The pointers *pPort and *pStarboard point to the leftmost (Port) and rightmost (Starboard) elements that have not been exchanged.


Each iteration of the loop exchanges those two elements and increments the *Port element (moves it to the right) and decrements the *Starboard element (moves to the left).

The loop terminates when *pPort (the left pointer) is no longer to the left of *pStarboard the right pointer.


The console screen print out shows the array in its original form.

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}


Then after it has been reversed by the function pointers.

{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}

YOU HAVE LEARNED HOW TO:
1. Download a free C++ compiler.
2. Install the Visual C++ Express Edition and start a new project.
3. Build, debug and compile a C++ program.
4. Declare and use pointers.
5. Use pointers in a function to reverse an array. 


Elcric Otto Circle




-->

-->

-->







How to Link to My Home Page

It will appear on your website as:
"Link to ELCRIC OTTO CIRCLE's Home Page"




No comments:

Post a Comment