Hi all,
I'm teaching myself C++ from a textbook ( C++ HOW TO PROGRAM by Deitel&Deitel ) but after successfully creating a program using C style arrays I'm having trouble converting it into vetors.
Any help much appreciated!!!
Please see both programs code below:
Code:
// recursiveFindMinimum.cpp ( WITH ARRAYS )
#include <iostream>
using namespace std;
const int arraySize = 5;
void initializeArray( int[] ); // to ask the user for numbers
int findMinimum( int[], int, int ); // to recursively find the smallest number
int main()
{
cout << "Welcome! This program recursively locates the smallest number in an array!" << endl;
int array1[ arraySize ];
int startSubscript = 0;
initializeArray( array1 );
int smallest = array1[ 0 ];
smallest = findMinimum( array1, startSubscript, smallest );
cout << "\nYour smallest number was: " << smallest << "!" << endl;
} // end main
// to recursively find the smallest number
int findMinimum( int array[], int counter, int smallest )
{
while ( counter < arraySize )
{
if ( smallest > array[ counter ] )
{
smallest = array[ counter ];
} // end if
counter++;
findMinimum( array, counter, smallest );
} // end while
return smallest;
} // end function findMinimum
// to ask the user for numbers
void initializeArray( int array[] )
{
cout << endl;
for ( int i = 0; i < arraySize; i++ )
{
cout << "Enter a number into the array: ";
cin >> array[ i ];
} // end for
} // end function initializeArray
Code:
// recursiveFindMinimumWithVectors.cpp ( WITH VECTORS )
#include <iostream>
#include <vector>
using namespace std;
const int arraySize = 5;
void initializeArray( vector < int > ); // to ask the user for numbers
int findMinimum( vector < int >, int, int ); // to recursively find the smallest number
int main()
{
cout << "Welcome! This program recursively locates the smallest number in an array!" << endl;
vector < int > array1( arraySize );
int startSubscript = 0;
initializeArray( array1 );
int smallest = array1[ 0 ];
smallest = findMinimum( array1, startSubscript, smallest );
cout << "\nYour smallest number was: " << smallest << "!" << endl;
} // end main
// to recursively find the smallest number
int findMinimum( vector < int > array, int counter, int smallest )
{
while ( counter < arraySize )
{
if ( smallest > array[ counter ] )
{
smallest = array[ counter ];
} // end if
counter++;
findMinimum( array, counter, smallest );
} // end while
return smallest;
} // end function findMinimum
// to ask the user for numbers
void initializeArray( vector < int > array )
{
cout << endl;
for ( int i = 0; i < arraySize; i++ )
{
cout << "Enter a number into the array: ";
cin >> array[ i ];
} // end for
} // end function initializeArray