'Why can’t my code find the second smallest elements array?
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.
Solution 1:[1]
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! Your last index is 9
for (int a = 1; 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
Solution 2:[2]
You need to compare the elements of the array. Not the index vs element
if(list[smallindex] > list[a])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | user438383 |
