Array Homework
Array Homework
// CODE_RUNNER: Arrays Homework
// Exercise 1 - Array Basics
// Create an array with 5 items
let favorites = ["Strawberry", "Apple", "Watermelon", "Grape", "Orange"];
// Print the entire array
console.log("Full array:", favorites);
// Print the first element (index 0)
console.log("First item:", favorites[0]);
// Print the last element
console.log("Last item:", favorites[favorites.length - 1]);
// Print the length
console.log("Total number of items:", favorites.length);
// Exercise 2 - Arrays Manipulation
// Start with the shopping list
let shoppingList = ["milk", "eggs", "bread", "cheese"];
// Print the original array
console.log("Original shopping list:", shoppingList);
// Change the second item to “butter”
shoppingList[1] = "butter";
// Add “yogurt” to the end using push()
shoppingList.push("yogurt");
// Remove “bread” from the array
let breadIndex = shoppingList.indexOf("bread");
if (breadIndex !== -1) {
shoppingList.splice(breadIndex, 1);
}
// Print the final array
console.log("Final shopping list:", shoppingList);
// Exercise 3 - Loop Through an Array
// Create the numbers array
let numbers = [10, 25, 30, 15, 20];
// Print each number with a message
for (let i = 0; i < numbers.length; i++) {
console.log("Number:", numbers[i]);
}
// Print each number multiplied by 2
for (let i = 0; i < numbers.length; i++) {
console.log("Multiplied by 2:", numbers[i] * 2);
}
// Calculate and print the sum
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log("Sum of all numbers:", sum);