Description: This problem involves a program that accepts a list of numbers and a target value. The goal is to search for the target in the list. If the target exists, the program returns the index where the target is located. If it doesn't exist, a message is printed stating that the target is not found. This problem helps in understanding searching algorithms and how to handle situations when an element is not present.
// Input: A list of numbers and a target value
procedure FindTarget(list, target)
found ← false
for i ← 0 to length of list - 1 do
if list[i] == target then
print "Target found at index: " + i
found ← true
break
end if
end for
if found == false then
print "Target not found"
end if
end procedure
def find_target(lst, target):
if target in lst:
index = lst.index(target)
print(f"Target found at index: {index}")
else:
print("Target not found")
# Example usage
find_target([1, 2, 3, 4, 5], 3)
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class FindTarget {
public static void findTarget(List<Integer> list, int target) {
if (list.contains(target)) {
System.out.println("Target found at index: " + list.indexOf(target));
} else {
System.out.println("Target not found");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
System.out.println("Enter the number of elements: ");
int n = scanner.nextInt();
System.out.println("Enter the elements: ");
for (int i = 0; i < n; i++) {
list.add(scanner.nextInt());
}
System.out.println("Enter the target value: ");
int target = scanner.nextInt();
findTarget(list, target);
}
}
#include <iostream>
#include <vector>
using namespace std;
void findTarget(const vector<int>& list, int target) {
bool found = false;
for (int i = 0; i < list.size(); i++) {
if (list[i] == target) {
cout << "Target found at index: " << i << endl;
found = true;
break;
}
}
if (!found) {
cout << "Target not found" << endl;
}
}
int main() {
int n, element, target;
vector<int> list;
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
cin >> element;
list.push_back(element);
}
cout << "Enter the target value: ";
cin >> target;
findTarget(list, target);
return 0;
}