Creating an Array of type String with 10 inputs

2 min read 05-10-2024
Creating an Array of type String with 10 inputs


Building an Array of Strings: 10 User Inputs Made Easy

Have you ever needed to collect a list of words from a user and store them for later use? This is a common task in programming, and arrays are the perfect tool for the job. In this article, we'll explore how to create an array of strings and populate it with 10 user inputs.

Scenario: Imagine you're building a simple application that asks users for their favorite fruits. You want to store their responses in an array so you can later display them or perform other actions with the data.

Code Example (Python):

fruits = []  # Create an empty array to store fruits
for i in range(10):  # Loop 10 times
    fruit = input(f"Enter fruit {i+1}: ")  # Get user input
    fruits.append(fruit)  # Add the input to the array

# Print the array
print("Your favorite fruits are:", fruits)

Breaking it down:

  1. fruits = []: We initialize an empty list named fruits. In Python, lists are used as arrays to store collections of data.
  2. for i in range(10): This loop runs 10 times, allowing us to collect 10 inputs.
  3. fruit = input(f"Enter fruit {i+1}: "): Inside the loop, we prompt the user to enter a fruit name using the input() function. The f before the string makes it a formatted string, which allows us to dynamically insert the loop counter (i+1) into the prompt message.
  4. fruits.append(fruit): After receiving the user input, we use the append() method to add the fruit to the end of our fruits array.
  5. print("Your favorite fruits are:", fruits): Finally, we display the collected fruits using the print() function.

Key Insights:

  • Arrays are versatile: You can use arrays to store various data types like numbers, strings, or even other arrays.
  • Loops are essential: Loops allow us to automate repetitive tasks like collecting multiple inputs from the user.
  • Flexibility: You can easily adapt this code to collect a different number of inputs by simply changing the range in the for loop.

Example:

Let's say the user inputs the following fruits:

  1. Apple
  2. Banana
  3. Orange
  4. Grape
  5. Mango
  6. Strawberry
  7. Kiwi
  8. Watermelon
  9. Pineapple
  10. Peach

The output will be:

Your favorite fruits are: ['Apple', 'Banana', 'Orange', 'Grape', 'Mango', 'Strawberry', 'Kiwi', 'Watermelon', 'Pineapple', 'Peach']

Additional Resources:

This example shows how simple it is to collect user input and store it in an array. With this foundation, you can explore more advanced data structures and algorithms in your programming journey.