Finding the maximum number using array


I want to find the maximum number using array

this is my code
I don't know what's wrong with it


[/#include <iostream>
using namespace std;
int main()
{
int N ,num[50],i,max;

cout<<"Enter the number of integers :";
cin>>N;
cout<<"Enter the integers: ";
cin>>num[0];
max=num[0];

for(int i=1;i<N-1;i++)
{cin>>num[i];}

for(int i=0;i<N;i++)
{
if(num[i]>max)
max=num[i];}

cout<<max;

return 0;
}]
Replace your line
for(int i=1;i<N-1;i++)
with
for(int i=1;i<N;i++)
Because you are otherwise not editing the value of the last value in the array. This means that this (possibly very large) number is throwing off your calculations.

Alternately, just use std::max_element: http://www.cplusplus.com/reference/algorithm/max_element/
What error/problem do you get?

Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

int max(int array[], int elements)
{
    int max_num = 0;
    for(int i = 0; i < elements; i++)
    {
        if(array[i] > max_num)
        {
            max_num = array[i];
        }
    }
    return max_num;
}

int main()
{
    int N;
    int input;
    int maximum;
    int myarray[50];
    std::cout << "Enter no. of elements (not greater than 50): ";
    std::cin >> N;
    
    std::cout << "Enter the integers:" << std::endl;
    for(int i = 0; i<N; i++)
    {
        std::cin >> input;
        myarray[i] = input;
    }
    
    maximum = max(myarray, N);
    
    std::cout << "The maximum is: " << maximum << std::endl;
    
    return 0;
    
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
int main()
{
int N ,num[50],max=0;

cout<<"Enter the number of integers :";
cin>>N;
cout<<"Enter the integers: ";
//cin>>num[0];
//max=num[0];

for(int i=0;i<N;i++)
{cin>>num[i];//}

//for(int i=0;i<N;i++)
//{
if(num[i]>max)
max=num[i];}

cout<<max;

return 0;
}
Topic archived. No new replies allowed.