Adding an index and specified number to an array in c++ - c++

I am making a program that removes a number from the index that the user provides from the array, displays the new array, then asks the user to insert a number at whatever index they choose. The first part of this program works fine when it comes to removing an index, but I am having trouble with adding an index and number. For example, if the NEW array after the user deletes the number from index 5 is: 12 34 45 2 8 16 180 182 22, which is correct if you remember that arrays start at 0, then they request for example index 5 to be added again with the number 78, it gets messed up. It displays 12 34 45 2 78 8 16 180 182 22 (and then it also outputs the number -858993460 for some reason?) SO the problem basically is that it adds the new index and number one index BEFORE it is supposed to. Im sorry if this sounds so confusing but I have been stuck on it for hours. Thank you!
//This program demos basic arrays
#include <iostream>
using namespace std;
const int CAP = 10;
int main()
{
int size;
int list[CAP] = { 12, 34, 45, 2, 8, 10, 16, 180, 182, 22 };
size = 10;
int i, delIndex, addIndex, newInt = 0;
cout << "Your list is: " << endl;
for (i = 0; i < CAP; i++)
{
cout << list[i] << endl;
}
//Deleting an index
cout << "\nPlease enter index to delete from: ";
cin >> delIndex;
for (i = delIndex; i <= 10; i++)
{
list[i] = list[i + 1];
}
cout << "The index position you specified has been deleted." << endl;
cout << "The new array is: " << endl;
for (i = 0; i < (size - 1); i++)
{
cout << list[i] << endl;
}
//Adding an index
cout << "\nNow, please enter the index position to add to: " << endl;
cin >> addIndex;
cout << "\nEnter the number to add to the index: " << endl;
cin >> newInt;
for (i = size - 1; i >= addIndex - 1; i--)
{
list[i + 1] = list[i];
}
list[addIndex - 1] = newInt;
size++;
cout << "The number has been added at the specified index position." <<
endl;
cout << "The new array is: " << endl;
for (i = 0; i < size; i++)
{
cout << list[i] << endl;
}
return 0;
}

The problem is with handling size variable in your code.
Following is corrected code. See it working here:
#include <iostream>
using namespace std;
const int CAP = 10;
int main()
{
int size;
int list[CAP] = { 12, 34, 45, 2, 8, 10, 16, 180, 182, 22 };
size = CAP;
int i, delIndex, addIndex, newInt = 0;
cout << "Your list is: " << endl;
for (i = 0; i < size; i++)
{
cout << list[i] << endl;
}
//Deleting an index
cout << "\nPlease enter index to delete from: ";
cin >> delIndex;
for (i = delIndex; i < size; i++)
{
list[i] = list[i + 1];
}
size--;
cout << "The index position you specified has been deleted." << endl;
cout << "The new array is: " << endl;
for (i = 0; i < size; i++)
{
cout << list[i] << endl;
}
//Adding an index
cout << "\nNow, please enter the index position to add to: " << endl;
cin >> addIndex;
cout << "\nEnter the number to add to the index: " << endl;
cin >> newInt;
for (i = size - 1; i >= addIndex; i--)
{
list[i + 1] = list[i];
}
list[addIndex] = newInt;
size++;
cout << "The number has been added at the specified index position." <<endl;
cout << "The new array is: " << endl;
for (i = 0; i < size; i++)
{
cout << list[i] << endl;
}
return 0;
}
Note: Since we are talking about index and not position in the array, so it is treated as 0 based and element is added at index addIndex, not at addIndex-1.

There are some loopholes in your program, that you can improve.
You are declaring a constant (CAP), but the array size is changing, so point doing that.
You are printing the array multiple times, its better to use a function, and call it every time, when you need to print the entire array.
You are using literals like 10, in some sections of the program. It is advisable to use the same variable like size or CAP instead of 10 to improve readability.
You can even put insert & delete in functions so that they can be called multiple times.
This is a sample working code, you can take the idea of that. I haven't implemented Step 4, I hope you can do that easily,
LIVE CODE
Working Code
//This program demos basic arrays
#include <iostream>
using namespace std;
int CAP = 10;
void printArr(int list[]){
for (int i = 0; i < CAP; i++)
cout << list[i] << " ";
cout<<endl;
}
int main()
{
int list[CAP] = { 12, 34, 45, 2, 8, 10, 16, 180, 182, 22 };
int i, delIndex, addIndex, newInt = 0;
cout << "Your list is: " << endl;
printArr(list);
//Deleting an index
cout << "\nPlease enter index(0 indexed based) to delete from: ";
cin >> delIndex;
for (i = delIndex; i < CAP - 1; i++)
list[i] = list[i + 1];
CAP--;
cout << "The index position you specified has been deleted." << endl;
cout << "The new array is: " << endl;
printArr(list);
//Adding an index
cout << "\nNow, please enter the index position(0 indexed based) to add to: " << endl;
cin >> addIndex;
cout << "\nEnter the number to add to the index: " << endl;
cin >> newInt;
for (i = CAP; i > addIndex; i--)
list[i] = list[i-1];
list[addIndex] = newInt;
CAP++;
cout << "The number has been added at the specified index position." << endl;
cout << "The new array is: " << endl;
printArr(list);
return 0;
}

Related

How to print values in descending order for every number entered?

I need to create a program that asks the user for N unique values and print the values in descending order for every number entered. The problem is it only outputs the number 0. Can anyone point out what is wrong with my code?
#include <iostream>
using namespace std;
int main(){
//declare the variables
int N, j, i, k, z, desc, temp, sorter[N];
bool found;
//Ask the user for N size array
cout << "Enter array size: ";
cin >> N;
while(N<5){
cout << "Invalid value. N must be greater than five(5)" << endl;
cout << "Enter array size: ";
cin >> N;
}
int list[N];
//Printing how many values they need to enter
cout << " " << endl;
cout << "Please enter " << N << " values" << endl;
//Code of the program
for (int i = 0; i < N; i++){
do{
found = false;
cout << "\n" << endl;
cout << "Enter value for index " << i << ": ";
cin >> temp;
for (int j = 0; j < i; j++)
if (list[j] == temp)
found = true;
if (found == true)
cout << "Value already exist";
else{
for(int k = 0; k < i; k++){
int key = sorter[k];
j = k - 1;
while(j >= 0 && key >= sorter[j]){
sorter[j + 1] = sorter[j];
j--;
}
sorter[j + 1] = key;
}
cout << "\nValues: ";
for(int z = 0; z <= i; z++){
cout << sorter[z] <<" ";
}
}
} while(found == true);
sorter[i] = temp;
}
You shouldn't be defining the array 'sorter[N]', the position, where you are currently, because you don't have the value of 'N', during compilation the arbitrary amount of space will be allocated to the the array.
solve the other compiling errors in your code.
What you want is just a 3-line code:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> vecOfNumbers = { 1,3,5,7,9,8,6,4,2 }; // scan these numbers if you want
std::sort(vecOfNumbers.begin(), vecOfNumbers.end());
std::copy(vecOfNumbers.rbegin(), vecOfNumbers.rend(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
Make sure you understand it before using it

How would you go about resolving this output value?

I finished this code homework assignment tonight. I thought I was done, but I just realized that my "Average" value is coming out wrong with certain values. For example: When my professor entered the values 22, 66, 45.1, and 88 he got an "Average" of 55.27. However, when I enter those values in my program, I get an "Average" of 55.25. I have no idea what I am doing wrong. I was pretty confident in my program until I noticed that flaw. My program is due at midnight, so I am clueless on how to fix it. Any tips will be greatly appreciated!
Code Prompt: "Write a program that dynamically allocates an array large enough to hold a user-defined number of test scores. Once all the scores are entered, the array should be passed to a function that sorts them in ascending order. Another function should be called that calculates the average score. The program should display the sorted list of scores and averages with appropriate headings. Use pointer notation rather than array notation whenever possible."
Professor Notes: The book only states, "Input Validation: Do not accept negative numbers for test scores." We also need to have input validation for the number of scores. If it is negative, including 0, the program halts, we should consider this situation for 'counter' not to be negative while we have a loop to enter numbers. So negative numbers should be rejected for the number of scores and the values of scores.
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
void showArray(double* array, int size);
double averageArray(double* array, int size);
void orderArray(double* array, int size);
int main()
{
double* scores = nullptr;
int counter;
double numberOfScores;
cout << "\nHow many test scores will you enter? ";
cin >> numberOfScores;
if (numberOfScores < 0) {
cout << "The number cannot be negative.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
if (numberOfScores == 0) {
cout << "You must enter a number greater than zero.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
scores = new double[numberOfScores];
for (counter = 0; counter < numberOfScores; counter++) {
cout << "Enter test score " << (counter + 1) << ": ";
cin >> *(scores + counter);
if (*(scores + counter) < 0) {
cout << "Negative scores are not allowed. " << endl
<< "Enter another score for this test : ";
cin >> *(scores + counter);
}
}
orderArray(scores, counter);
cout << "\nThe test scores in ascending order, and their average, are: " << endl
<< endl;
cout << " Score" << endl;
cout << " -----" << endl
<< endl;
showArray(scores, counter);
cout << "\nAverage Score: "
<< " " << averageArray(scores, counter) << endl
<< endl;
cout << "Press any key to continue...";
delete[] scores;
scores = nullptr;
system("pause>0");
}
void orderArray(double* array, int size)
{
int counterx;
int minIndex;
int minValue;
for (counterx = 0; counterx < (size - 1); counterx++) {
minIndex = counterx;
minValue = *(array + counterx);
for (int index = counterx + 1; index < size; index++) {
if (*(array + index) < minValue) {
minValue = *(array + index);
minIndex = index;
}
}
*(array + minIndex) = *(array + counterx);
*(array + counterx) = minValue;
}
}
double averageArray(double* array, int size)
{
int x;
double total{};
for (x = 0; x < size; x++) {
total += *(array + x);
}
double average = total / size;
return average;
}
void showArray(double* array, int size)
{
for (int i = 0; i < size; i++) {
cout << " " << *(array + i) << endl;
}
}
I try to start my answers with a brief code review:
#include <iostream>
#include <iomanip>
using namespace std; // Bad practice; avoid
void showArray(double* array, int size);
double averageArray(double* array, int size);
void orderArray(double* array, int size);
int main()
{
double* scores = nullptr;
int counter;
double numberOfScores;
cout << "\nHow many test scores will you enter? ";
cin >> numberOfScores;
// This is not input validation, I can enter two consecutive bad values,
// and the second one will be accepted.
if (numberOfScores < 0) {
// Weird formatting, this blank line
cout << "The number cannot be negative.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
// The homework, as presented, doesn't say you have to treat 0 differently.
if (numberOfScores == 0) {
cout << "You must enter a number greater than zero.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
scores = new double[numberOfScores];
// Declare your loop counter in the loop
for (counter = 0; counter < numberOfScores; counter++) {
cout << "Enter test score " << (counter + 1) << ": ";
cin >> *(scores + counter);
if (*(scores + counter) < 0) {
cout << "Negative scores are not allowed. " << endl
<< "Enter another score for this test : ";
cin >> *(scores + counter);
}
}
orderArray(scores, counter); // Why not use numberOfScores?
cout << "\nThe test scores in ascending order, and their average, are: " << endl
<< endl;
cout << " Score" << endl;
cout << " -----" << endl
<< endl;
showArray(scores, counter); // Same as above.
cout << "\nAverage Score: "
<< " " << averageArray(scores, counter) << endl
<< endl;
cout << "Press any key to continue...";
delete[] scores;
scores = nullptr;
system("pause>0"); // Meh, I suppose if you're on VS
}
void orderArray(double* array, int size)
{
int counterx;
int minIndex;
int minValue; // Unnecessary, and also the culprit
// This looks like selection sort
for (counterx = 0; counterx < (size - 1); counterx++) {
minIndex = counterx;
minValue = *(array + counterx);
for (int index = counterx + 1; index < size; index++) {
if (*(array + index) < minValue) {
minValue = *(array + index);
minIndex = index;
}
}
*(array + minIndex) = *(array + counterx);
*(array + counterx) = minValue;
}
}
double averageArray(double* array, int size)
{
int x;
double total{};
for (x = 0; x < size; x++) {
total += *(array + x);
}
double average = total / size;
return average;
}
void showArray(double* array, int size)
{
for (int i = 0; i < size; i++) {
cout << " " << *(array + i) << endl;
}
}
When you are sorting your array, you keep track of the minValue as an int and not a double. That's why your average of the sample input is incorrect. 45.1 is truncated to 45 for your calculations. You don't need to keep track of the minValue at all. Knowing where the minimum is, and where it needs to go is sufficient.
But as I pointed out, there are some other serious problems with your code, namely, your [lack of] input validation. Currently, if I enter two consecutive bad numbers, the second one will be accepted no matter what. You need a loop that will not exit until a good value is entered. It appears that you are allowed to assume that it's always a number at least, and not frisbee or any other non-numeric value.
Below is an example of what your program could look like if your professor decides to teach you C++. It requires that you compile to the C++17 standard. I don't know what compiler you're using, but it appears to be Visual Studio Community. I'm not very familiar with that IDE, but I imagine it's easy enough to set in the project settings.
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
// Assumes a number is always entered
double positive_value_prompt(const std::string& prompt) {
double num;
std::cout << prompt;
do {
std::cin >> num;
if (num <= 0) {
std::cerr << "Value must be positive.\n";
}
} while (num <= 0);
return num;
}
int main() {
// Declare variables when you need them.
double numberOfScores =
positive_value_prompt("How many test scores will you enter? ");
std::vector<double> scores;
for (int counter = 0; counter < numberOfScores; counter++) {
scores.push_back(positive_value_prompt("Enter test score: "));
}
std::sort(scores.begin(), scores.end());
for (const auto& i : scores) {
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "\nAverage Score: "
<< std::reduce(
scores.begin(), scores.end(), 0.0,
[size = scores.size()](auto mean, const auto& val) mutable {
return mean += val / size;
})
<< '\n';
}
And here's an example of selection sort where you don't have to worry about the minimum value. It requires that you compile to C++20. You can see the code running here.
#include <iostream>
#include <random>
#include <vector>
void selection_sort(std::vector<int>& vec) {
for (int i = 0; i < std::ssize(vec); ++i) {
int minIdx = i;
for (int j = i + 1; j < std::ssize(vec); ++j) {
if (vec[j] < vec[minIdx]) {
minIdx = j;
}
}
int tmp = vec[i];
vec[i] = vec[minIdx];
vec[minIdx] = tmp;
}
}
void print(const std::vector<int>& v) {
for (const auto& i : v) {
std::cout << i << ' ';
}
std::cout << '\n';
}
int main() {
std::mt19937 prng(std::random_device{}());
std::uniform_int_distribution<int> dist(1, 1000);
std::vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(dist(prng));
}
print(v);
selection_sort(v);
print(v);
}
I opted not to give your code the 'light touch' treatment because than I would have done your homework for you, and that's just not something I do. However, the logic shown should still be able to guide you toward a working solution.

Find the product of elements located between the maximum and minimum elements of an array

#include <iostream>
using namespace std;
int main()
{
int n, a, b,min,max, Prod = 1, Sum = 0;
cout << "Initialize an array n: ";
cin >> n;
do
{
cout << "Input the start value: ";
cin >> a;
cout << "Input the end value: ";
cin >> b;
if (!(a < b))
{
cout << "a is bigger than b, please enter new values " << endl;
continue;
}
} while (!(a < b));
int* lpi_arr;
lpi_arr = new int[n];
srand(time(NULL));
cout << "Int numbers from " << a << " to " << b << endl;
for (int i = 0; i < n; i++)
{
lpi_arr[i] = rand() % (b - a) + a;
cout << lpi_arr[i] << " ";
}
max = lpi_arr[0];
for (int i = 0; i < n; i++)
{
if (max < lpi_arr[i])
max = lpi_arr[i];
}
min = lpi_arr[0];
for (int i = 0; i < n; i++)
{
if (min > lpi_arr[i])
min = lpi_arr[i];
}
cout << "\nmin element is = " << min << endl;
cout << "\nmax element is = " << max << endl;
for (int i = max + 1; i < min; i++)
Prod *= lpi_arr[i];
for (int i = 0; lpi_arr[i] < 0 && i < n; i++)
Sum += lpi_arr[i];
cout << "Summ =" << Sum << endl << "Prod = " << Prod << endl;
delete[] lpi_arr;
}
The main purpose of this code is to calculate the sum of negative numbers of an array, and multiplication of elements located between the maximum and minimum elements of an array.
The problem is that the code implements only 1(one) as an answer, and I don't know how to change it. Every other part of the code works well, but if you have any recommendations I'd also like to read it. Waiting for your help.
Your issue is that you're confusing array indexes with array values.
Here you're assigning max (and same with min) to an array value.
max = lpi_arr[i];
Here you're treating max (and same with min) as an array index.
for (int i = max + 1; i < min; i++)
Prod *= lpi_arr[i];

C++ How to the total number of duplicate elements in the array?

I am trying to finish my homework, but I have encountered some problems in the item of Duplicate Elements. I have tried to find out where the problem is, but I cannot find it. My code works fine when the sequence is small, but it becomes problematic when the sequence is large.
In this sequence, I expect to get the number in the picture, but I always get the number in the second picture. As you can see, there is always a problem in this item in the duplicate element.
#include <iostream>
using namespace std;
int main()
{
int count = 0;
int arrayA[25];
int arrayB[25];
int min,max;
int num;
int i = 0;
int n = 0;
int temp = 0;
int sum = 0;
//Input
cout << "Input the number of elements to store in the array: ";
cin >> n;
cout << n << endl;
cout << "Input "<< n <<" integers:" << endl;
//Store arrayA
if(count < n){
for(i = 0; i < n; i++){
cin >> num;
cout << "integer - " << count;
cout << " : " << num <<endl;
arrayA[count] = num;
count++;
}
}
//store arrayB
for(i = 0;i < count; i++){
arrayB[i] = arrayA[count - i - 1];
}
//Forwards Array
cout << "The values stored into the array are :" << endl;
for(i = 0;i < count; i++){
cout << arrayA[i] << " ";
}
cout << endl;
//Backwards Array
cout << "The values stored into the array in reverse are :" << endl;
for(i = 0; i < count; i++){
cout << arrayB[i] <<" ";
}
cout << endl;
//Sum
for(i = 0; i < count; i++){
sum += arrayA[i];
}
//Max & Min
for(i = 0; i < count;i++){
if(max < arrayA[i]){
max = arrayA[i];
}
}
for(i = 0; i < count; i++){
if(min > arrayA[i]){
min = arrayA[i];
}
if(arrayA[i]== 0){
min = 0;
break;
}
}
//Duplicate elements
count = 0;
for(i = 0; i < n; i++){
for(temp = i + 1; temp < n; temp++){
if(arrayA[i] == arrayA[temp] ){
count++;
break;
}
}
}
cout << "The sum of all elements of the array is ";
cout << " " << sum << endl;
cout << "The total number of duplicate elements in the array is ";
cout << count << endl;
cout << "The maximum and minimum element in the array are ";
cout << min << " , " << max;
return 0;
}
You should try debugging more by printing, to know what is happening. You are not really taking into account that a number can be repeated several times and depending on the spread, it will count them several times. And here is why:
//Duplicate elements
count = 0;
for(i = 0; i < n; i++){
for(temp = i + 1; temp < n; temp++){
//cout << "Comparing "<< arrayA[i] << " to "<< arrayA[temp]<<endl;
if(arrayA[i] == arrayA[temp] ){
cout << "ITEM DUPLICATED at i , "<<i<< " item "<< arrayA[i]<< " and temp "<< temp<< " item "<< arrayA[temp] << endl;
count++;
break;
}
}
}
ITEM DUPLICATED at i , 0 item 4 and temp 7 item 4
ITEM DUPLICATED at i , 2 item -2 and temp 10 item -2
ITEM DUPLICATED at i , 4 item -3 and temp 14 item -3
ITEM DUPLICATED at i , 5 item 3 and temp 11 item 3
ITEM DUPLICATED at i , 7 item 4 and temp 8 item 4
ITEM DUPLICATED at i , 12 item -1 and temp 13 item -1
As you can see, there is a 4 - 4 twice. It can be seen quite easily if you do it in paper (although you shouldn't)
4A -4B -2C 1D -3E 3F 5G 4H 4I 0J -2K 3L -1M -1N -3O
4a -4b -2c 1d -3e 3f 5g 4h 4i 0j -2k 3l -1m -1n -3o
Connections made:
4A 4h
-2C -2k
-3E -3o
3F 3l
4H 4i
So the code technically is doing what you are asking it to do. if you want to count UNIQUELY (if a 4 appears 15 times, count it as only that 4 is repeated), you should be checking if the number has already been checked. Using a vector or map (dictionaries in C++) can allow you to do that! Or lists with lists (the element, and the number of occurences)

Need help on getting the smallest three numbers on an array

For this program a user must enter 10 contestants and the amount of second it took for them to complete a swimming race. My problem is that I must output the 1st, 2nd and 3rd placers, so I need to get the three smallest arrays (as they would be the quickest times) but I'm unsure on how to do it. Here is my code so far.
string names[10] = {};
int times[10] = { 0 };
int num[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int min1 = 0, min2 = 0, min3 = 0;
cout << "\n\n\tCrawl";
for (int i = 0; i < 10; i++)
{
cout << "\n\n\tPlease enter the name of contestant number " << num[i] << ": ";
cin >> names[i];
cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
cin >> times[i];
while (!cin)
{
cout << "\n\tError! Please enter a valid time: ";
cin.clear();
cin.ignore();
cin >> times[i];
}
if (times[i] < times[min1])
min1 = i;
cout << "\n\n\t----------------------------------------------------------------------";
}
system("cls");
cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
cout << "\n\n\t1st Place - " << names[min1];
cout << "\n\n\t2nd Place - " << names[min2];
cout << "\n\n\t3rd Place - " << names[min3];
}
_getch();
return 0;
}
As you can see, it is incomplete. I know how to get the smallest number, but its the second and third smallest that is giving me trouble.
your code is full of errors:
what do you do with min2 and min3 as long as you don't assign them?? they are always 0
try checking: cout << min2 << " " << min3;
also you don't initialize an array of strings like that.
why you use an array of integers for just printing number of input:
num? instead you can use i inside loop adding to it 1 each time
to solve your problem use a good way so consider using structs/clusses:
struct Athlete
{
std::string name;
int time;
};
int main()
{
Athlete theAthletes[10];
for(int i(0); i < 10; i++)
{
std::cout << "name: ";
std::getline(std::cin, theAthletes[i].name);
std::cin.sync(); // flushing the input buffer
std::cout << "time: ";
std::cin >> theAthletes[i].time;
std::cin.sync(); // flushing the input buffer
}
// sorting athletes by smaller time
for(i = 0; i < 10; i++)
for(int j(i + 1); j < 10; j++)
if(theAthletes[i].time > theAthletes[j].time)
{
Athlete tmp = theAthletes[i];
theAthletes[i] = theAthletes[j];
theAthletes[j] = tmp;
}
// printing the first three athletes
std::cout << "the first three athelets:\n\n";
std::cout << theAthletes[0].name << " : " << theAthletes[0].time << std::endl;
std::cout << theAthletes[1].name << " : " << theAthletes[1].time << std::endl;
std::cout << theAthletes[2].name << " : " << theAthletes[2].time << std::endl;
return 0;
}
I hope this will give u the expected output. But i suggest u to use some sorting alogirthms like bubble sort,quick sort etc.
#include <iostream>
#include<string>
using namespace std;
int main() {
int times[10] = { 0 };
int num[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int min1 = 0, min2 = 0, min3 = 0,m;
string names[10] ;
cout << "\n\n\tCrawl";
for (int i = 0; i < 10; i++)
{
cout << "\n\n\tPlease enter the name of contestant number " << num[i] << ": ";
cin >> names[i];
cout << names[i];
cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
cin >> times[i];
cout<<times[i];
while (!cin)
{
cout << "\n\tError! Please enter a valid time: ";
cin.clear();
cin.ignore();
cin >> times[i];
}
if(times[i]==times[min1]){
if(times[min1]==times[min2]){
min3=i;
}else{min2 =i;}
}else if(times[i]==times[min2]){
min3=i;
}
if (times[i] < times[min1]){
min1 = i;
cout <<i;
}
int j=0;
while(j<i){
if((times[j]>times[min1])&&(times[j]<times[min2])){
min2 =j;
j++;
}
j++;
}
m=0;
while(m<i){
if((times[m]>times[min2])&&(times[m]<times[min3])){
min3 =m;
m++;
}
m++;
}
cout << "\n\n\t----------------------------------------------------------------------";
}
cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
cout << "\n\n\t1st Place - " << names[min1];
cout << "\n\n\t2nd Place - " << names[min2];
cout << "\n\n\t3rd Place - " << names[min3];
return 0;
}
There is actually an algorithm in the standard library that does exactly what you need: std::partial_sort. Like others have pointed out before, to use it you need to put all the participant data into a single struct, though.
So start by defining a struct that contains all relevant data. Since it seems to me that you only use the number of the contestants in order to be able to later find the name to the swimmer with the fastest time, I'd get rid of it. Of course you could also add it back in if you like.
struct Swimmer {
int time;
std::string name;
};
Since you know that there always will be exactly 10 participants in a race, you can also go ahead and replace the C-style array by a std::array.
The code to read in the users then could look like this:
std::array<Swimmer, 10> participants;
for (auto& participant : participants) {
std::cout << "\n\n\tPlease enter the name of the next contestant: ";
std::cin >> participant.name;
std::cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
while(true) {
if (std::cin >> participant.time) {
break;
}
std::cout << "\n\tError! Please enter a valid time: ";
std::cin.clear();
std::cin.ignore();
}
std::cout << "\n\n\t----------------------------------------------------------------------";
}
Partial sorting is now essentially a one-liner:
std::partial_sort(std::begin(participants),
std::begin(participants) + 3,
std::end(participants),
[] (auto const& p1, auto const& p2) { return p1.time < p2.time; });
Finally you can simply output the names of the first three participants in the array:
std::cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
std::cout << "\n\n\t1st Place - " << participants[0].name;
std::cout << "\n\n\t2nd Place - " << participants[1].name;
std::cout << "\n\n\t3rd Place - " << participants[2].name << std::endl;
The full working code can be found on coliru.
This is not a full solution to your problem, but just meant to point you into the right direction...
#include <iostream>
#include <limits>
#include <algorithm>
using namespace std;
template <int N>
struct RememberNsmallest {
int a[N];
RememberNsmallest() { std::fill_n(a,N,std::numeric_limits<int>::max()); }
void operator()(int x){
int smallerThan = -1;
for (int i=0;i<N;i++){
if (x < a[i]) { smallerThan = i; break;}
}
if (smallerThan == -1) return;
for (int i=N-1;i>smallerThan;i--){ a[i] = a[i-1]; }
a[smallerThan] = x;
}
};
int main() {
int a[] = { 3, 5, 123, 0 ,-123, 1000};
RememberNsmallest<3> rns;
rns = std::for_each(a,a+6,rns);
std::cout << rns.a[0] << " " << rns.a[1] << " " << rns.a[2] << std::endl;
// your code goes here
return 0;
}
This will print
-123 0 3
As you need to know also the names for the best times, you should use a
struct TimeAndName {
int time;
std::string name;
}
And change the above functor to take a TimeAndName instead of the int and make it also remember the names... or come up with a different solution ;), but in any case you should use a struct similar to TimeAndName.
As your array is rather small, you could even consider to use a std::vector<TimeAndName> and sort it via std::sort by using your custom TimeAndName::operator<.