Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

c++ arrays finding the largest values

Status
Not open for further replies.

karmafree

Programmer
May 10, 2001
107
GB
problem: the user inputs 12 numbers into an array. The program will output the larget value in the array that the user entered. BUT if there are more then one elements with the largest value then the program will output that position too.


i.e.
enter number01:23
enter number02:10
enter number03:23
enter number04:21

the largest number(s)are number01 and number02

thanks
Ravi
 
Hi

Brute force method:
1. Scan Array for Maximum Value and store max. value
2. Re-Scan array and output value equal to max. found in first scan

HTH

Thierry

 
Hi

The following program will do it. Its not the most effecient way of doing it but it does work. Its output is a bit different to what you asked for. If you want the output to be just what you asked for you will need to add a couple of extra if and for statements, if you need help with that just reply to this message.

The alignment looks odd because of the tab setting. That should be fixed when you cut and paste it.

#include <iostream.h>

void main()
{
int number[12];
int largest;
int i; // loop control variable

// input the numbers
for(i=0; i < 12; i++)
{
cout << &quot;Input number &quot; << i << &quot;: &quot;;
cin >> number;
}

// find the largest value
largest = number[0];
for(i=1; i < 12; i++)
{
if(number > largest)
largest = number;
}

// output the position of all largest numbers
cout << &quot;The largest number is: &quot; << largest << '\n';
cout << &quot;It is in the following positions: \n&quot;;
for(i=0; i < 12; i++)
{
if(number == largest)
cout << i << '\n';
}
}

Hope that helps.
 
If you wanted to be more effecient you could look at the bubble sort and quicksort algorithms. This would only be neccessary on large lists though.
 
You could also eliminate the loop to determine the largest value by evaluating it as the user enters numbers.

for (iNdx = 0; iNdx < 12; iNdx++)
{
//user enters number
if (iMaxValue < iUserValue[iNdx])
iMaxValue = iUserValue[iNdx];
}

Then you would only need to run through all the values one time to determine if they are equal to the max value and then display them.

for (iNdx = 0; iNdx < 12; iNdx++)
{
if (iMaxValue = iUserValue[iNdx])
cout << &quot;Largest Number &quot; << iMaxValue << &quot; at position &quot; << iNdx;
}

HTH,
JC
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top