Ok so I had to find the smallest number in a 10-number array and I did that with this.
#include %26lt;iostream%26gt;
using namespace std;
int main()
{
const int TOTALNUMBERS = 10;
int numbers[TOTALNUMBERS];
// Read all numbers
for (int i = 0; i %26lt; TOTALNUMBERS; i++)
{
cout %26lt;%26lt; "Enter a number: ";
cin %26gt;%26gt; numbers[i];
}
// Find the smallest
int min = numbers[0];
for (int i = 1; i %26lt; TOTALNUMBERS; i++)
{
if (min %26gt; numbers[i])
min = numbers[i];
}
cout %26lt;%26lt; "The smallest number is " %26lt;%26lt; min %26lt;%26lt;endl;
return 0;
}
But now I have to find the index of the smallest number, and I have no idea of how to do that. Any tips? Thanks alot guys.
C++ Help Please!?
see for the additions i have made:
#include %26lt;iostream%26gt;
using namespace std;
int main()
{
const int TOTALNUMBERS = 10;
int numbers[TOTALNUMBERS],location;
// Read all numbers
for (int i = 0; i %26lt; TOTALNUMBERS; i++)
{
cout %26lt;%26lt; "Enter a number: ";
cin %26gt;%26gt; numbers[i];
}
// Find the smallest
int min = numbers[0];
location=0;
for (int i = 1; i %26lt; TOTALNUMBERS; i++)
{
if (min %26gt; numbers[i])
{min = numbers[i]; location=i;}
}
cout %26lt;%26lt; "The smallest number is " %26lt;%26lt; min %26lt;%26lt;" at location "%26lt;%26lt;location+1%26lt;%26lt;endl;
return 0;
}
Reply:I would set up a for loop like for(int i = 0; i %26lt; 10; i++) and a variable called "smallestIndex" = 0 which would loop through the array and test the numbers[i] with the current smallest indexand
if(numbers[i] %26lt; numbers[smallestIndex]);
smallestIndex = i;
Reply:Seeing that this is probably a homework assignment, I'll describe what you need to do:
Create an extra variable (near //Find the smallest) to hold the index.
Then, inside the loop, when you are trying to find the smallest index, not only copy the value of the smallest value (min=numbers[i]), but also its index. Store it in the variable you created.
Finally, in your cout statement, print the value of this variable.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment