- (a) First, make your output as below:
Here is the array you'll be woking with: 3 2 5 2 7 4 3 5
Enter target value: 3
Target 3 occurs in the list at position: 0
Target 3 occurs in the list at position: 6
Goodbye.
or
Here is the array you'll be woking with: 3 2 5 2 7 4 3 5
Enter target value: 8
Goodbye.
- (b) Modify your solution above so that it
keeps track whether the target is found or not, in order to be able to
print a "not found" message at the end (If the target is found,
nothing changes).
Here is the array you'll be woking with: 3 2 5 2 7 4 3 5
Enter target value: 8
Target 8 is not in the list.
Goodbye.
Hint: One way to do it is to use a variable that counts the number of
times the target is found.
Another way is to use a boolean variable that keeps track whether the
target has been found or not; maintain this variable through the
search loop.
//this variable keeps track whether the target has been found or not
boolean isFound;
//initially we have not found it yet
isFound = false;
//search loop
while (..) {
//if we find target set isFound to true
}
//at the end of the loop isFound should be true if and only if
//the target has been found at least once
if (isFound == false) {
//tell the user the target is not in the list
}
- (c) Refine your solution further so that it
displays the results as below:
Here is the array you'll be woking with: 3 2 5 2 7 4 3 5
Enter target value: 3
Target 3 occurs in the list at position: 0 6
Goodbye.
or
Here is the array you'll be woking with: 3 2 5 2 7 4 3 5
Enter target value: 8
Target 8 is not in the list.
Goodbye.
Hint: use your boolean variable isFound from part (b). Based
on it you can figure out if it is the first time you find the
target, or not.
//this variable keeps track whether the target has been found or not
boolean isFound;
//initially we have not found it yet
isFound = false;
//search loop
while (..) {
//compare target to element i
//if we find target then
//if its the first time we find it then
//print "The target occurs at position: "
//set isFound to true
//print position
//increment loop counter
}
//at the end of the loop isFound should be true if and only if
//the target has been found at least once
if (isFound == false) {
//tell the user the target is not in the list
}