MCC - CIS162AB - C++ Level I
P09ex Loading, Sorting, and Searching Arrays an Example
   cpp.gif

The purpose of this C++ programming example is to demonstrate the switch statement and for loops, as well as to introduce the loading, sorting, and searching of a partially filled array. The program reads up to 20 numbers from a text file (P09ex.txt). A menu allows the user to display the numbers as loaded, ascending, or descending order. Each time the numbers are displayed, their corresponding index value is also displayed. The search option asks the user to enter a number to search for. If the value is found, its location in the array is displayed, else an error message is displayed.
P09ex.txt: 

50 40 100 30 10 20


Sample Output: 
Opening File...
Loading up to 20 whole numbers.
Closing File...


P09ex  Juan Marquez   

Enter the letter of the desired menu option.
Press the Enter key after entering the letter.

  A: List Numbers as Loaded
  B: List Numbers Ascending Order
  C: List Numbers Descending Order
  D: Search Number List
  X: Exit the Number Module

Choice: A 

Values as read:

position =  1  index =  0  value =  50
position =  2  index =  1  value =  40
position =  3  index =  2  value = 100
position =  4  index =  3  value =  30
position =  5  index =  4  value =  10
position =  6  index =  5  value =  20

Procedure completed. Press Enter to continue:


Choice: B

Values sorted ascending:

position =  1  index =  0  value =  10
position =  2  index =  1  value =  20
position =  3  index =  2  value =  30
position =  4  index =  3  value =  40
position =  5  index =  4  value =  50
position =  6  index =  5  value = 100

Procedure completed. Press Enter to continue:


Choice: c

Values sorted descending:

position =  1  index =  0  value = 100
position =  2  index =  1  value =  50
position =  3  index =  2  value =  40
position =  4  index =  3  value =  30
position =  5  index =  4  value =  20
position =  6  index =  5  value =  10

Procedure completed. Press Enter to continue:


Choice: d

Enter a number to search for: 40

40 is stored in array position 4 and is
referenced with an index value of 3.


Procedure completed. Press Enter to continue:


Choice: d

Enter a number to search for: 25
Early exit...25 is not on the list.

Procedure completed. Press Enter to continue:


Choice: x

Now exiting Number Module...please wait.

Press any key to continue


Source Code:
//P09ex - Array and File Processing  - Juan Marquez  
//
//Loads, sorts and searches a partially filled array of integers

#include <iostream>      // cout and cin
#include <fstream>       // file processing
#include <cctype>        // tolower
#include <iomanip>       // setw
#include <stdlib.h>      // system()
using namespace std;

//Declare global variables
//Normally variables that change values are declared locally, 
//but here the array and supporting variables are declared globally
//to simplified the function definitions.

const int DECLARED_SIZE = 20;
int numberArray[DECLARED_SIZE], numbersEntered;

void loadArray( );

void sortArrayAscending( );

void sortArrayDescending( );

void displayArray( );

void searchArray( );

void displayContinuePrompt( );

void bubbleSort( );
//bubbleSort included as an informational item.

void main( )
{
    char choice;

//loadArray with numbers from the data file
    loadArray( );

//check to see what the user wants to do
    do  // while (choice != 'X')
    {
        cout << "P09ex  Juan Marquez    \n\n";

        cout << "Enter the letter of the desired menu option. \n"
             << "Press the Enter key after entering the letter. \n \n"

             << "  A: List Numbers as Loaded \n"
             << "  B: List Numbers Ascending Order \n"
             << "  C: List Numbers Descending Order \n"
             << "  D: Search Number List \n"

             << "  X: Exit the Number Module \n \n"

             << "Choice: ";

        cin >> choice;

        choice = toupper(choice);

        switch (choice)
        {
            case 'A':
                cout << "\nValues as read:\n";
                displayArray( );
                displayContinuePrompt( );
                break;
            case 'B':
                cout << "\nValues sorted ascending:\n";
                sortArrayAscending( );
                displayArray( );
                displayContinuePrompt( );
                break;
            case 'C':
                cout << "\nValues sorted descending:\n";
                sortArrayDescending( );
                displayArray( );
                displayContinuePrompt( );
                break;
            case 'D':
                searchArray( );
                displayContinuePrompt( );
                break;
            case 'X':
                cout << "\nNow exiting Number Module...please wait.\n\n";
                break;
            default:
                cout << "\a \n\n Invalid Option Entered - Please try again. \n\n";

        } // end of switch

    } while (choice != 'X');
    
    return;
}//end of main


void loadArray( )
{
    cout << "Opening File...\n";

//Open the file for input;
    ifstream inFile;
    inFile.open("P09ex.txt"); 
//If there are any errors, display an error message and return.
    if (inFile.fail())
    {
        cout << endl << endl
             << "Error: Input file NOT found. " << endl << endl;
        numbersEntered = 0;
        return;
    }

    cout << "Loading up to " << DECLARED_SIZE << " whole numbers.\n";

//initialize index to zero for first array element
    int  i = 0;
//read the first number
    inFile >> numberArray[i];        

//Only loads up to 20 numbers.
//Additional data in the file is ignored.
    while (! inFile.eof())
    {
        i++;
        if (i < DECLARED_SIZE)
            inFile >> numberArray[i];
        else
            break;    //get out of the loop
    }
    numbersEntered = i;

    cout << "Closing File...\n\n";
    inFile.close();
    return;
}


void sortArrayAscending( )
{
    int minIndex, minValue, holdValue;

    for (int i = 0; i < (numbersEntered - 1); i++)   //walk through array
    {                                                //outer loop keeps track
        minIndex = i;                                //of where the next value
        minValue = numberArray[i];                   //should be placed.

        for (int i2 = i + 1; i2 < numbersEntered; i2++)
        {                                            //inner loop finds the   
            if (numberArray[i2] < minValue)          //lowest value to move   
            {
                minIndex = i2;                       //save the new low number
                minValue = numberArray[i2];          //found
            }
        }
        holdValue = numberArray[i];                  //swap the values
        numberArray[i] = numberArray[minIndex];
        numberArray[minIndex] = holdValue;
    }
    return;
}


void sortArrayDescending( )
{
//For a descending sort we still walk through the array, but this
//time we are searching for the highest values.
    int maxIndex, maxValue, holdValue;

    for (int i = 0; i < (numbersEntered - 1); i++)   //walk through array
    {                                                //outer loop keeps track
        maxIndex = i;                                //of where the next value
        maxValue = numberArray[i];                   //should be placed.

        for (int i2 = i + 1; i2 < numbersEntered; i2++)
        {                                            //inner loop finds the   
            if (numberArray[i2] > maxValue)          //highest value to move  
            {
                maxIndex = i2;                       //save the new high number
                maxValue = numberArray[i2];          //found
            }
        }
        holdValue = numberArray[i];                  //swap the values
        numberArray[i] = numberArray[maxIndex];
        numberArray[maxIndex] = holdValue;
    }
    return;
}


void displayArray( )
{
    cout << endl;
    cout.setf(ios::right);  //already on by default for numbers

    for (int i = 0; i < numbersEntered; i++)
    {
        cout << "position ="; 
        cout << setw(3)  << (i + 1);

        cout << "  index ="; 
        cout << setw(3)  << i;

        cout << "  value =";
        cout << setw(4)  << numberArray[i] 
             << endl;
    }
    return;
}


//Early exit - an early exit from a search can occur when we know that
//the value we are looking for will not be found in the array.  To
//implement an early exit, the array most be sorted ascending.
//If  we can determine that a value will not be found, we should
//not search the remainder of the array.

void searchArray( )
{ 
//array must be sorted ascending for early exit logic to work  
    sortArrayAscending( ); 

    int  searchNumber;
    bool numberFound = false;

    cout << "\nEnter a number to search for: ";
    cin >> searchNumber;

    for(int i=0; i < numbersEntered; i++)
    {
        if (searchNumber == numberArray[i])      //check if the value entered is
        {                                        //= to the current array element
            numberFound = true;    
            cout << endl 
                 << searchNumber << " is stored in array position "
                 << i + 1 
                 << " and is \nreferenced with an index value of "
                 << i << ". \n\n";
            break;                              //get out of for-loop
        }
        else if (searchNumber < numberArray[i]) //Early exit
        {
            cout << endl << "Early exit...";
            break;                              //get out of for-loop
        }
    }

    if (false == numberFound)
        cout << searchNumber << " is not on the list.\n";

    return;
}


void displayContinuePrompt( )
{
    char prompt;

    cout << "\nProcedure completed. Press Enter to continue: ";
    cin.ignore(); 
    prompt = cin.get( );

    system("cls");    //clear the screen

    return;
}


//presented as informational item
void bubbleSort( )
{
    int holdValue;

    for (int i = 0; i < (numbersEntered - 1); i++)     //Number of entries in array.
    {                                                 
        for (int i2 = 0; i2 < numbersEntered - 1; i2++)//Inner loop finds the 
        {                                              //lowest value to move.
            if (numberArray[i2] > numberArray[i2 + 1]) //Low values float up.
            {
                holdValue = numberArray[i2];           //swap the values
                numberArray[i2] = numberArray[i2 + 1];
                numberArray[i2 + 1] = holdValue;
            }
        }
    }
    return;
}
// end of program

Revised: 08/15/2006 - www.mc.maricopa.edu/~marquez/cis162ab/p09_ex_arrays.html