'Why is this happening with my C++ application? [closed]

I'm currently learning C++, and at the moment I'm starting off by making multiple kinds of calculators to test my problem solving capabilities.

Below is the issue, along with a working version of what I'm trying to accomplish:

Functions:

int largestNumber(int nVariables, int numbers[]){
    int largest = numbers[0];
    
    for (int i = 1; i <= nVariables; i++) {
        largest = (largest<numbers[i]?numbers[i]:largest);
    }
    
    return largest;
}

int smallestNumber(int nVariables, int numbers[]){
    int smallest = numbers[0];
        
    for (int i = 1; i <= nVariables; i++) {
        smallest = (smallest>numbers[i]?numbers[i]:smallest);
    }
    
    return smallest;
}

simplified Main():

    switch (algoOption) {
        case 1:{
            int nOfVariables;
            std::cout << "Input number of variables: ";
            std::cin >> nOfVariables;

            int variables[nOfVariables];

            for (int i = 0; i < nOfVariables; i++) {
                std::cout << "Enter Variable #" << i + 1 << ": ";
                std::cin >> variables[i];
            }
            std::cout << std::endl;

            std::cout << std::endl << largestNumber(nOfVariables, variables) << std::endl;
            nOfVariables = 0;
            break;
        }
        case 2:
            int nOfVariablesS;
            std::cout << "Input number of variables: ";
            std::cin >> nOfVariablesS;

            int variables[nOfVariablesS];

            for (int i = 0; i < nOfVariablesS; i++) {
                std::cout << "Enter Variable #" << i + 1 << ": ";
                std::cin >> variables[i];
            }
            std::cout << std::endl;

            std::cout << std::endl << smallestNumber(nOfVariablesS, variables) << std::endl;
            nOfVariablesS = 0;
            break;
    }
} while (algoOption < 3);

Ok here is an example:

I choose case 1 through the terminal to find the largest number, and say I want 3 variables total.

Cool, now I am prompted to enter each number one by one...

So I enter 1 2 3...

result -> 3

Perfect. It works.

If I change largest = (largest<numbers[i]?numbers[i]:largest); to largest = (largest<numbers[i]?largest:numbers[i]); it returns the smallest number of the array...

But, if I do the same thing with the smallestNumber() function, it just returns 0.

example of case 2:

So I enter 1 2 3...

result -> 0

Why?

For some reason, when smallestNumber() has the opposite of largest = (largest<numbers[i]?numbers[i]:largest); as smallest = (smallest>numbers[i]?numbers[i]:smallest); it doesn't work, but when I do the same for largestNumber() it does.

c++


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source