Not too sure what the code is trying to accomplish, since it has no comments, no indentation, and no explanation to what it is suppose to do. but I'm guessing its trying to find the largest multiple of 5 in a randomly generated Vector of 20 elements and return it as well as its index.
To simplify that, you could completely remove the function biggest() and change the name of the function index to biggest. Then using its return value, in the main function look up the largest value using the index with a regular v[index] call or v.at(index).
Garbage values left in RAM by what he wrote. If anything he should write a control statement that checks if the index is valid. The best way to do that is to set index within the function to -1. If it never gets overwritten by a valid array index it will be returned to main().
Then write a control statement to handle the -1 return such as displaying an error message.
can you write the code of what you said please? i could not understand clearly what you mean in >>setting index within the function to -1<< or here >>Then write a control statement to handle the -1 return such as displaying an error message. <<... i have an examine after two days and i don't want to fail = ((
#include <iostream>
#include <fstream>
#include <vector>
// Prototypes
int biggest(const std::vector<int> &);
//int index(const std::vector<int> &);
// Constant Maximum Values
constint K = 20;
int main()
{
std::ofstream fout("answer.out");
std::vector<int> vc(K); // Vector 'vc' with K elements of type integer
for (int i = 0; i < K; ++i)
v.push_back(rand() % 71 + 30);
biggestIndex = biggest(vc);
if (biggestIndex == -1)
fout << "There was no multiple of 5 within the array.\n";
else
fout << "Largest integer is" << vc.at(biggestIndex) << "at index = " << biggestIndex;
}
int biggest(const std::vector<int> &vc)
{
int max = -32768, index = -1; // index set to -1
for (int i = 0; i < vc.size(); ++i)
if (( (vc[i] % 5) == 0) && (vc[i] > max) ) // What if this never executes?
{
index = i;
max = vc[i];
}
return index; // Returns index or -1 if none found
}
In function biggest I initialize index to -1.
If the loop never finds a multiple of 5, index will never change and will remain -1.
Then back in main, I simply handle this case with a control statement, outputting an error to the file.
Simple.