1

I want to find the max number in an array. But my code show me unexpected answer.

is there any wrong in my code?

Here's my code:

#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter array size: ";
cin>>n;
int a[n];
int maximum = 0;
maximum=a[0];
for(int i=0; i<n; i++)
{
    cin>>a[i];
    if(maximum<a[i])
    {
        maximum=a[i];
    }

}

cout<<"Maximum number: "<<maximum;
return 0;
}

  Here my input: 
  Enter array size: 3
  4 5 6

  Output:
  16

  My expected output must be 6

is there any wrong in my code?

  • 1
    Well. Have a look into your code what you assigned to `a[0]` before you do this: `maximum=a[0];`. – Scheff's Cat Jan 20 '21 at 06:32
  • Your first comparison of `maximum < a[i]` accesses `a[0]` which is not initialized – costaparas Jan 20 '21 at 06:33
  • Have you tried running your code line by line in a debugger while monitoring the values of all variables, in order to determine at which point your program stops behaving as intended? If you did not try this, then you probably want to read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) You may also want to read this: [How to debug small programs?](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Andreas Wenzel Jan 20 '21 at 06:50

2 Answers2

5

You have initialized maximum with the value of a[0] before ever initializing that value. This gives undefined behavior, since it can be anything. In your example, it ended up getting the value 16 which is larger than any of the values you subsequently input. As a result, you never set maximum to an actual value input by the user.

A quick fix would be to do this in the loop:

if (i == 0 || maximum < a[i])

There is actually no reason to store the inputs in an array in your case, unless you plan do do something else with them. You could perform this task without ever creating an array.

Also please be aware that variable-length arrays (VLAs) are non-standard. They are also prone to problems. Consider what might happen if the user inputs a negative array size or a large number. This will overflow your program's stack and cause undefined behavior. Better to use std::vector.

paddy
  • 60,864
  • 6
  • 61
  • 103
0

You have set maximum to a[0] which is uninitialized. Initialize maximum with cin >> maximum and intialize i to 1 or initialize maximum INT_MIN for the lowest possible int value.

#include <climits>

...

int maximum = INT_MIN;

or

int maximum = 0;
cin >> maximum;
for(int i = 1; i < n; i++)
{

Output:

Enter array size: 5
1 
2
3
4
5
Maximum number: 5
ComputerFido
  • 327
  • 3
  • 12