0

I have a function that outputs the outliers of an array of numbers with these given parameters:

// countArray is an array of numbers
// numCounts is a global int = 15
// avgComputed is the computed average of the numbers in countArray
// stdDev is the standard deviation of the numbers in countArray
// numOutliers is the number of outliers in countArray
void outputOutliers(int &countArray[], const int numCounts, double &avgComputed, double &stdDev, int &numOutliers)

This function outputs the outliers in angle brackets, e.g. < 90, 76, 101 >.

What I'm really struggling with right now is knowing how to identify when I've reached the last outlier, and to not display a comma after it's been printed.

Here's the code I have so far inside the function:

cout << "Outliers: < ";

for (int i = 0; i < numOutliers; i++) {
  for (int i = 0; i < countArray.size(); i++) {
     if (abs(countArray[i] - stdDev) > 0) {
        cout << countArray[i] << ", ";
     }
  }
}
Lendit
  • 1
  • 1
  • 5
    Print the comma before every number but the first one. – Retired Ninja Apr 11 '22 at 22:10
  • Print the 1st number by itself, then loop through the remaining numbers, printing a comma before each number – Remy Lebeau Apr 11 '22 at 22:25
  • @RemyLebeau Both you and Ninja offered great answers, I guess now my question is what for-loop do I incorporate to utilize that? Do I iterate through the number of outliers, or the array itself? – Lendit Apr 11 '22 at 22:42
  • "*the number of outliers, or the array itself*" - What's the difference? It would have been great if you had actually shown the code *inside the function* that you are struggling with. How are you printing out the numbers to begin with? – Remy Lebeau Apr 11 '22 at 22:56
  • @RemyLebeau I've edited my original post to display the contents of my function. You should now see what I mean when I'm referencing the number of outliers and the countArray[]. – Lendit Apr 11 '22 at 23:40
  • @Lendit why do you have nested loops both using `i` for their counters? Why do you have two loops at all? In any case, since you don't know which elements of `countArray` will be output, the best simplest would be to use a `bool` variable on the inner loop, eg: `bool commaNeeded = false; for (size_t i = 0; i < countArray.size(); i++) { if (abs(countArray[i] - stdDev) > 0) { if (commaNeeded) { cout << ", " } cout << countArray[i]; commaNeeded = true; } }` ... – Remy Lebeau Apr 12 '22 at 00:26
  • @Lendit Alternatively, you could use `std::find_if()` for the inner loop, eg: `auto comp = [&](int elem){ return abs(elem - stdDev) > 0; }; auto iter = find_if(countArray.begin(), countArray.end(), comp); if (iter != countArray.end()) { cout << *iter; while ((iter = find_if(++iter, countArray.end(), comp)) != countArray.end()) { cout << ", " << *iter; } }` – Remy Lebeau Apr 12 '22 at 00:30

0 Answers0