array

i just want to know, the way of computer see this, i mean how the computer read this to display the highest number from this array,



double value[] = {0,45,6,2,3,4,5,6,7,8};
double highest = 0;

for(int i=0; i < 10; i++)
{
double number = value[i];

if(highest > number)
{
highest = number;
}
}

cout<<highest<<endl;
OK... The above code possess a logical error if it has to find the greatest number. However, considering the corrections made, it will observe the following mechanism.

value [] = {0, 45, 6, 2, 3, 4, 5, 6, 7, 8}

Which actually means:

value[0] = 0
value[1] = 45
value[2] = 6
value[3] = 2
value[4] = 3
value[5] = 4
value[6] = 5
value[7] = 6
value[8] = 7
value[9] = 8

For the first iteration (int i=0) the variable (double highest) is set to 0. The compiler will jump into the loop & look for the value that is greater than the value in highest (which equals 0 for now).

Now's where the actual show begins....

The comparison will only assign a value to the highest when the result is true.

i, assignment, comparison, result, assignment

i, number = value[i], highest<number, true/false, highest = number

i = 0, number = value[0], 0 < 0, false, highest = 0
i = 1, number = value[1], 0 < 45, true, highest = 45
i = 2, number = value[2], 45 < 6, false, highest = 45
i = 3, number = value[3], 45 < 2, false, highest = 45
i = 4, number = value[4], 45 < 3, false, highest = 45
i = 5, number = value[5], 45 < 4, false, highest = 45
i = 6, number = value[6], 45 < 5, false, highest = 45
i = 7, number = value[7], 45 < 6, false, highest = 45
i = 8, number = value[8], 45 < 7, false, highest = 45
i = 9, number = value[9], 45 < 8, false, highest = 45

In this way our output would be 45, the greatest number.

Hope it helps :)

Btw here's a simpler (correction made ie; comparison operator) version of your program. It excludes an extra variable (ie; double number) and set all data types to int.

1
2
3
4
5
6
7
8
9
10
11
12
int value[] = {0,45,6,2,3,4,5,6,7,8};
int highest = 0;

for(int i=0; i < 10; i++)
{
if(highest < value[i])
{
highest = value[i];
}
}

cout<<highest<<endl;
Last edited on
thank very much wahaj :)
Topic archived. No new replies allowed.