📖 Scenario: You are working on a simple program that stores the names of fruits in an array. You want to access specific fruits by their position in the array.
🎯 Goal: Build a C# program that creates an array of fruits, sets an index variable, accesses the fruit at that index, and prints it.
📋 What You'll Learn
Create an array called fruits with these exact values: "Apple", "Banana", "Cherry", "Date", "Elderberry"
Create an integer variable called index and set it to 2
Access the fruit at position index in the fruits array and store it in a variable called selectedFruit
Print the value of selectedFruit exactly
💡 Why This Matters
🌍 Real World
Arrays are used to store lists of items like names, prices, or dates. Accessing items by index helps you get or change specific data quickly.
💼 Career
Knowing how to work with arrays and access their elements is a basic skill for many programming jobs, including software development and data processing.
Progress0 / 4 steps
1
Create the fruits array
Create a string array called fruits with these exact values: "Apple", "Banana", "Cherry", "Date", "Elderberry"
C Sharp (C#)
Hint
Use string[] fruits = { ... }; to create the array with the exact fruit names.
2
Set the index variable
Create an integer variable called index and set it to 2
C Sharp (C#)
Hint
Use int index = 2; to create the index variable.
3
Access the fruit at the index
Create a string variable called selectedFruit and set it to the fruit at position index in the fruits array
C Sharp (C#)
Hint
Use string selectedFruit = fruits[index]; to get the fruit at the given index.
4
Print the selected fruit
Write a Console.WriteLine statement to print the value of selectedFruit
C Sharp (C#)
Hint
Use Console.WriteLine(selectedFruit); to print the fruit.
Practice
(1/5)
1. What is the index of the first element in a C# array int[] numbers = {10, 20, 30};?
easy
A. 0
B. 1
C. 10
D. Array length - 1
Solution
Step 1: Understand zero-based indexing in C# arrays
Arrays in C# start counting indexes from 0, so the first element is at index 0.
Step 2: Identify the first element's index
The first element 10 is at index 0, not 1 or any other number.
Final Answer:
0 -> Option A
Quick Check:
First element index = 0 [OK]
Hint: Remember: C# arrays start at zero index [OK]
Common Mistakes:
Thinking the first index is 1
Confusing element value with index
Using array length as first index
2. Which of the following is the correct way to access the third element of an array string[] fruits = {"apple", "banana", "cherry"};?
easy
A. fruits[2]
B. fruits[3]
C. fruits(2)
D. fruits{2}
Solution
Step 1: Recall C# array indexing syntax
Arrays use square brackets [] to access elements by zero-based index.
Step 2: Identify the correct index for the third element
The third element is at index 2, so fruits[2] is correct.
Final Answer:
fruits[2] -> Option A
Quick Check:
Third element index = 2 [OK]
Hint: Use square brackets and zero-based index [OK]