Comp Assessed Hw2
Comp Assessed Hw2
(A)
(i) the system would throw an error because the array has places only from [0] to [5] and
numbers [6] has no value/doesn’t exist. The error is “index out of bound”.
(ii) to avoid this error, one should check whether the index called for lies within the range of the
array. The easy solution to this is using an if condition to check for the above.
(b)
# loop used so as to make sure the code works even with expanding array size.
For i in range 0 to len(NUMBERS) - 1
sum = sum + NUMBERS[i]
End loop
Avg = sum / len(NUMBERS)
Output “average of given grades = “, avg
(c)
(i)
(ii) the purpose was to swap the position of largest and smallest values of the array NUMBERS.
(d)
#Determine the position of the largest number in the array
Max = NUMBERS [0]
Index = 0
For i from 1 to len(NUMBERS) - 1
if max < NUMBERS[i]
max = NUMBERS[I]
Index = I
Output “position of the largest number is”, index
2.
(a)
false
2, 4 -1, 3
(b)
A sorted ascending array is provided. The value that we are searching for is given.
From the entire array, compare the given value with the value in the index of
(LOW+HIGH)/2
If the wanted value is larger than the MID then we should move the pointer to the right
of the array (start searching on that side).
o Else start searching on the left side
On the half of the array being searched, find the MID again and repeat the entire
process.
This helps prevent too many comparison steps and eliminates half the array from
consideration.
(C)
I=0
Input “enter the number you are searching for”, s
While NUMBERS.hasNext ( )
A = NUMBERS.getNext ( )
ArrayD [I] = A
I++
For I from 0 to len(ArrayD)-1
If ArrayD[I] == s
found = true
index = i
break
else
continue
If found = true
Output “value was found in position”, I
Else
output “value was not found”
(D)
While reading the values from the collection into the array, compare the value being read
currently to the value that was read previously (the one just before this) and check that the
previous value is smaller than the current value. If the check fails, the array is not in order and
needs to be linearly searched. Else, binary search can be used.
This will make sure the array is searched through using the right method.
3.
(a) Unit price of Product_ID[2] = 16.3
(b)
(C)
Input “enter wanted product ID”, PID
For I in range 0 to len(Product_ID) - 1
If PID == Product_ID[I]
found = true
index = i
break
else
continue
If found = true
Output “product for given ID was found in position”, I
Output “price of that product = “, Unit_Price [index]
Else
output “invalid product ID – product not found”
(D)
ArrayOne [15]
ArrayTwo [10]
(i)
Max product IDs in ArrayThree = 10 (assuming all in ArrayTwo are contained in One)
(ii)
M=0
ArrayThree = [10]
For I in range 0 to len(ArrayOne) - 1
For j in range 0 to len(ArrayTwo) -1
if ArrayOne[I] == ArrayTwo[j]
ArrayThree[m] = ArrayOne[I]
Output “common array Ids are:”, ArrayThree