203k views
0 votes
Description Instantiate two parallel arrays, one with five names and the other with five respective ages. Write a program that allow the user to enter a name and see the person's age.

User Foreline
by
7.4k points

1 Answer

4 votes

Final answer:

To solve this problem, you can use parallel arrays to store names and respective ages. You can prompt the user for a name and then search for it in the names array. If the name is found, you can display the corresponding age.

Step-by-step explanation:

To solve this problem, we can instantiate two parallel arrays: one for names and the other for ages. In your program, you can declare an array of strings to store the names and an array of integers to store the ages. Here is an example in Java:

String[] names = {"John", "Emily", "Michael", "Sophia", "David"};
int[] ages = {25, 18, 32, 27, 40};

// Prompt the user to enter a name
String input Name = "David";

// Search for the name in the names array
int index = -1;
for (int i = 0; i < names.length; i++) {
if (names[i].equals(inputName)) {
index = i;
break;
}
}

// Display the corresponding age if the name is found
if (index != -1) {
int age = ages[index];
System.out.println("Age of " + inputName + ": " + age);
} else {
System.out.println("Name not found.");
}

The question involves creating a program with two parallel arrays for names and ages, then allowing a user to input a name to find the corresponding age.

The student's question involves creating a simple program that handles two parallel arrays, one with names and the other with corresponding ages, and allows user input to find a person's age. This is a typical programming task that helps students understand array manipulation and user interaction in a program.

Here is an example in Python:

# Instantiate two parallel arrays
names = ['Alice', 'Bob', 'Charlie', 'Diana', 'Edward']
ages = [23, 17, 35, 29, 42]

# Program to find a person's age
person _name = input('Enter a name to find the age: ')
if person _name in names:
index = names .index (person _name)
print(f'{person _name} is {ages[index]} years old.')
else:
print('Name not found.')

This program sets up two arrays with names and ages, then prompts the user to enter a name. It searches for the name in the names array and, if found, prints the corresponding age using the associated index from the ages array.

User Hlorand
by
7.4k points