You should firstly use a for loop to streamline that entry code.
1 2
for (int x = 0; x < 5; x++)
cin >> num;
You know how that works, right? You don't need an array because there is only one number to keep - the maximum.
Then, set max to the first number entered. So on the first iteration, set max to the current number.
After getting another number, check if it's higher than the current maximum. If it is, set max to the current number. If not, leave max as is.
That's it.
Of course you could put each number in an array or vector, sort the container in ascending order
and then print the last element which will be the max value.
Alternatively if you use the above method you could include a line static max=0 immediately below the for loop and another line: if ( num>max)num=max immediately after cin>>num
Then num is max so print num is max.
// Code to find the maximum number
# include<iostream>
usingnamespace std;
int main ()
{
int num(0); // semantically equal to: int num = 0;int max(0);
cout << "Please enter 5 numbers, so that i show you the maximum \n";
for (int i(0); i<5; i++)
{
cin >> num;
if ( num > max)
{
max = num;
}
}
cout << "The maxmum value is: " << max << endl ;
system ("pause");
return 0;
}
if you init max value by 0, and an user will not input positive numbers(he will input only negative) then the user will be suprised, because the biggest value is 0, but he did not enter it.
I was 'fixing up' the code posted by gnwillix88. I figured that if he can't get his code working, initializing max to the largest negative number would probably blow his mind so I left it at zero (better that than initializing to an uninitialized variable). There is also no error handling incase the user enters a letter or other erroneous input.
#include <iostream>
usingnamespace std;
int main ()
{
int a[5],i,max;
for (i=0;i<5;i++)
{
cin>>a[i];
if (i==0) max=a[i];
if (a[i]>max) max=a[i];
}
cout<<"max numb is:"<<max;
return 0;
}
Here he will have all inputs in array (if its needed for other operations) and he will have a maximum of all of them. And this works for negative numbers also.
Here is code for finding max of 2 numbers without using if/else, while for or anything like that
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int main ()
{
int a,b;
cout<<"a:"; cin>>a;
cout<<"b:"; cin>>b;
cout<< ( (a+b) + abs(a-b) ) / 2; //for maximum
cout<< ( (a+b) - abs(a-b) ) / 2; //for minimum
return 0;
}