# Algorithm To Find The Maximum Value

Here is a basic algorithm coded in C++ for finding the highest value of a number in a data set.

```//Full Working Program
#include <iostream>

using namespace std;

int main()
{
int k,max; //delcare a variable 'k' that holds integer values
int my_array ;//an array that will hold 10 integers

for (k=0; k<10; k++)
{
cout<<"Enter an integer"<<endl;
cin>>my_array[k];//user will input ten values

}

max=my_array;//assign max a value to avoid garbage

for (k=0; k<10; k++)
{
//if 'max' is less than my_array[k] then assign it that value
if (max < my_array[k])
{
max=my_array[k];
}
}

cout<<"The highest value is "<<max<<endl;

return 0;
}
```

## -HOW IT WORKS-

The first loop is strictly just to recieve data from the user.

```for (k=0; k<10; k++)
{
cout<<"Enter an integer"<<endl;
cin>>my_array[k];//user will input ten values
}
```

When the loop first starts 'k' is 0 so when the cin statement executes it's like coding "cin>>ages>>endl;" 'k' then increments by one and 'k' now equals 1 so now the cin statement looks like this "cin>>ages>>endl;"...etc

```max=my_array;//assign max a value to avoid garbage

```

Here is a part that seems weird at first but it's absolutely necessary! Our variable that is going to hold the highest value is 'max', in this specific loop it is going to be compared to 10 values to check whether or not they are higher than 'max' well if we don't assign max a value it will hold garbage. Remember garbage can be any number typically a ridiculous one. So say we didn't assign 'max' a value and allowed it to hold garbage and say in this case the garbage value was 5,250. Now say that when the user is finished inputing all 10 values that the highest value they entered in 'my_array' is 1,200. When the if condition checks to see if 'max' is less than 'my_array[k]' it will never happen. The highest value in 'my_array' is 1,200 but 'max' has the value of 5,250, in what world is 5,250 less than 1,200? Not this one. So if we assign 'max' the value of the first array 'my_array' like we did above, we are ensuring that 'max' will never be higher than the highest value inside the data set in this case 'my_array'.

```for (k=0; k<10; k++)
{
//if 'max' is less than my_array[k] then assign it that value
if (max < my_array[k])
{
max=my_array[k];
}
}
```

The next for loop is what actually cotains the algorithm used with an if condition. In this case it will run 10 times each loop checking to see if 'max' is less than 'my_array[k]' if it is less than, then 'max' will be assigned the value of 'my_array[k]' if it is not then nothing will happen. After the loop has ran 10 times and checked all 10 values 'max' is left with the maximum value of the data set.