#include<iostream>
#include<conio.h>
#include<vector>
usingnamespace std;
int findmax(vector<int>);
int main()
{
vector <int> v1(5);
cout << " Enter 10 numbers to find the max number :\n " ;
for(int i=0;i<v1.size();i++)
cin>>v1[i];
cout << " the max number is : " <<findmax(v1);
getch();
return 0;
}
int findmax(vector<int>){
int max=0;
vector<int>v1;
for(int i=0;i<v1.size();i++)
if(max<v1[i])
max=v1[i];
return max;
}
#include<iostream>
#include<vector>
usingnamespace std;
int findmax(vector<int>);
int main()
{
vector <int> v;
v.push_back(5);
v.push_back(17);
v.push_back(2);
v.push_back(3);
cout << "The max number is : " << findmax(v);
return 0;
}
int findmax(vector<int> x)
{
vector<int>::iterator it = x.begin();
int max = *it;
for (it = x.begin() ; it != x.end(); ++it)
{
if ( *it > max )
max = *it;
}
return max;
}
The max number is : 17
Exit code: 0 (normal program termination)
#include<iostream>
// #include<conio.h> // *** non-standard; avoid
#include <vector>
#include <limits> // *** added
// using namespace std; // also avoid
// int findmax(vector<int>);
int find_max( std::vector<int> ) ; // passed by value
int main()
{
// vector <int> v1(5);
std::vector<int> v1(10) ;
// cout << " Enter 10 numbers to find the max number :\n " ;
std::cout << "Enter " << v1.size() << " numbers to find the max number :\n" ;
// for(int i=0;i<v1.size();i++)
// cin>>v1[i];
// favour writing the non-compound statements (ones without {} around it) in the same line
for( std::size_t i = 0; i < v1.size(); ++i ) std::cin >> v1[i] ;
std::cout << "the max number is : " << find_max(v1) << '\n' ;
//getch(); // non-standard
std::cin.ignore( 1000, '\n' ) ; // throw away everything in the current line in the input buffer (including the new line)
std::cout << "press enter to end program\n" ;
std::cin.get() ; // wait for the user to press enter
// return 0; // implicit
}
// int findmax(vector<int>){
int find_max( std::vector<int> v1 ) // v1 is the vector passed to the function
{ // use a consistent indent style
// int max=0;
// we need to check if the vector is empty before we try to access any value in it
if( v1.empty() ) return std::numeric_limits<int>::min() ; // may want to throw an error instead
int max = v1.front() ; // the element at the front is the one at position zero ie. v1[0]
// vector<int>v1; // *** vector v1 is passed to the function, use that
for( std::size_t i = 1; i < v1.size(); ++i ) if( max < v1[i] ) max = v1[i];
return max;
}