This code find the maximum element of a dynamic array
int i, n, *x, max;
cout << "eneter a number: ";
cin >> n;
x = new int[n];
max = x[0];
for (i = 0; i < n; i++)
{
if (x[i] > x[0])
{
max = x[i];
}
}
cout << max << endl;
delete []x;
Let's assume my input be :
n=4
{3, 22, 15, 17}
So the output is 22
I don't understand how if select the 22
as max
.
This is my understanding of how it works:
n=4
{3, 22, 15, 17}
x[0] = 3
first loop i=0 -> x[0]>x[0] false
x[1] = 22
second loop i=1 -> x[1]>x[0] true
x[2] = 15
third loop i=2 -> x[2]>x[0] true
x[3] = 17
forth loop i=3 -> x[3]>x[0] true
I know I'm wrong but as my assumption the 17 must be the maximun value. What am I missing here?
Aucun commentaire:
Enregistrer un commentaire