📖 Scenario: Imagine you run a small store and want to keep track of the prices of 5 different fruits you sell. You want to store these prices so you can easily find and update them later.
🎯 Goal: You will create a simple Java program that uses an array to store the prices of 5 fruits. Then, you will calculate the total price of all fruits combined.
📋 What You'll Learn
Create an array to hold 5 fruit prices
Create a variable to hold the total price
Use a for loop to add all prices in the array
Print the total price
💡 Why This Matters
🌍 Real World
Stores often need to keep track of many items like prices, quantities, or names. Arrays help organize this data neatly.
💼 Career
Understanding arrays is essential for programming jobs because they are used everywhere to handle lists of data efficiently.
Progress0 / 4 steps
1
Create an array of fruit prices
Create an array called fruitPrices of type double with these exact values: 1.5, 2.0, 0.75, 3.0, 2.5.
Java
Hint
Use double[] fruitPrices = { ... }; to create the array with the given values.
2
Create a variable to hold the total price
Add a variable called totalPrice of type double and set it to 0.
Java
Hint
Use double totalPrice = 0; to create the variable.
3
Add all fruit prices using a for loop
Use a for loop with variable i from 0 to fruitPrices.length - 1 to add each price in fruitPrices[i] to totalPrice.
Java
Hint
Use a for loop to go through each index and add the value to totalPrice.
4
Print the total price
Write System.out.println(totalPrice); to display the total price of all fruits.
Java
Hint
Use System.out.println(totalPrice); to print the result.
Practice
(1/5)
1. Why do we need arrays in Java?
easy
A. To store only one value at a time
B. To store multiple values of the same type together
C. To perform mathematical calculations automatically
D. To create graphical user interfaces
Solution
Step 1: Understand the purpose of arrays
Arrays group many values of the same type in one place for easy handling.
Step 2: Compare options with array purpose
Only To store multiple values of the same type together correctly describes storing multiple values together.
Final Answer:
To store multiple values of the same type together -> Option B
Quick Check:
Arrays store many values [OK]
Hint: Arrays hold many same-type values together [OK]