Home > Mobile >  Why can’t my code find the second smallest elements array?
Why can’t my code find the second smallest elements array?

Time:05-15

int smallindex = 0;
int secsmallindex = 0;

I put the lines above into gobalslope.
The rest of the code:

#include <iostream> 
using namespace std;

int main() {
    int list[10] = { 33,6,3,4,55,22,5,6,7,6 };
    for (int a = 1; a <= 10; a  )
    {
        if (smallindex > list[a]) {
            secsmallindex = smallindex;
            smallindex = a;
        }
        else if (list[a] < secsmallindex && list[a] > smallindex) {
            secsmallindex = a;
        }
    }
    cout << secsmallindex << "   " << smallindex;
}

I want to find the second smallest elements and smallest number.
But it can not find it.
The output is 2 and 10.

CodePudding user response:

You had some problems. Mostly index ranges of an array, and comparing index with the actual value stored in the array. I commented out the old (problematic) lines and added the correct ones with some description. (Demo)


#include <iostream>

using namespace std;

int main() {
    /// You don't need these variables to be global.
    /// Minimise the scope of the variables!
    int smallindex = 0;
    int secsmallindex = 0;

    int list[10] = {33, 6, 3, 4, 55, 22, 5, 6, 7, 6};
    
    /// for (int a = 1; a <= 10; a  ) <- old line
    /// In C and C  , array indexing is 0 based!
    ///     The 1st element has the index 0
    for (int a = 0; a < 10; a  )
    {
        /// if (smallindex > list[a]) <- old line
        /// You comparing the index to the ath element but you should
        ///     compare element to element
        if (list[smallindex] > list[a]) 
        {
            secsmallindex = smallindex;
            smallindex = a;
        }
        /// else if (list[a] < twosmallindex && list[a] > smallindex) <- old line
        /// Same as before, compare element to element not element to index
        else if (list[a] < list[secsmallindex] && list[a] > list[smallindex])
        {
            secsmallindex = a;
        }
    }
    cout << secsmallindex << " " << smallindex;
}

Output: 3 2

CodePudding user response:

You need to compare the elements of the array. Not the index vs element

if(list[smallindex] > list[a])

  •  Tags:  
  • c
  • Related