0
0
Javaprogramming~15 mins

Why arrays are needed in Java - See It in Action

Choose your learning style8 modes available
folder_codeWhy arrays are needed
📖 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
💡 Need a 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
💡 Need a 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
💡 Need a 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
💡 Need a hint?

Use System.out.println(totalPrice); to print the result.