nerdsley
nerdsley

Reputation: 223

C++ Variable not properly receiving new value from vector?

I'm trying to write a program that creates and fills a vector with int values, then searches through it and returns the minimum value, recursively. I have the code written out and building, but it returns a weirdly large value for minimum every time- I have a feeling it's not properly assigning the smallest value to int minimum, but I'm not sure. Any thoughts?

#include <iostream>
#include <conio.h>
#include <vector>

using namespace std;

int vectorSize;
int minimum;
int result = -1;
int start;
int ending;
int answer;
int test;

int recursiveMinimum(vector<int>, int, int);

void main() {
    cout << "How many values do you want your vector to be? ";
    cin >> vectorSize;
    cout << endl;

    vector<int> searchVector(vectorSize);

    start = 0;
    ending = searchVector.size() - 1;

    for (int i = 0; i < vectorSize; i++) {
        cout << "Enter value for position " << i << " " << endl;
        cin >> searchVector[i];
    }

    for (int x = 0; x < vectorSize; x++) {
        cout << searchVector[x] << " ";
    }

    int answer = recursiveMinimum(searchVector, start, ending);
    cout << "The smallest value in the vector is: " << answer;

    _getch();
}

int recursiveMinimum(vector<int> searchVector, int start, int end) {
    if (start < end) {
        if (searchVector[start] < minimum) {
            minimum = searchVector[start]; //this part seems to not work
        }

        start++;
        recursiveMinimum(searchVector, start, end);
    }
    else {
        return minimum;
    }
}
`

Upvotes: 0

Views: 88

Answers (2)

Stephan Lechner
Stephan Lechner

Reputation: 35154

The main issue is that you do not initialise minimum. Hence, comparison searchVector[start] < minimum might never become true, and minimum remains uninitialized.

As a quick fix, write int minimum = MAX_INT; instead of int minimum;. MAX_INT is the maximum positive integer value (defined in limits.h). So the values in your array will never be greater that this value, and your minimum search loop will work (unless there are other issues; but for that, please consult the debugger :-) )

Upvotes: 0

Emily
Emily

Reputation: 1096

Your minimum variable is not initialised, which leads to undefined behaviour. It should be set to the first value in the vector:

minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending);

Additionally, ending is off by one, which makes it pick 6 as the smallest value out of [6, 9, 8, 4].

So, ultimately, your code should look like this:

minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending + 1); // note the + 1

While irrelevant to the question, I advise you to use a tail call in recursiveMinimum, as explained here:

start++;
return recursiveMinimum(searchVector, start, end);

Upvotes: 2

Related Questions