Exercise 1: Declaring and Initializing Arrays
Write the code to:
Declare an array of strings called
fruits
and initialize it with the following values:"Apple"
,"Banana"
,"Cherry"
,"Mango"
.Print the second element in the array to the console.
Exercise 2: Accessing Array Elements
Declare an array of integers called
ages
with the values{25, 30, 35, 40}
.Assign the last element of the array to a new integer variable
lastAge
.Print the value of
lastAge
to the console.
Exercise 3: Array Length
Create an array of strings called
cities
with the values:"New York"
,"London"
,"Tokyo"
,"Paris"
.Write a program to print the total number of elements in the `cities
Exercise 4: Sum of Array Elements
Create an array of integers called
expenses
with the values{1200, 800, 500, 300, 200}
.Use a loop to calculate and print the total sum of the elements in the array.
Exercise 5: Display Array Elements in a ListBox
Create a Windows Form with:
A
ListBox
namedlistBox1
.A
Button
namedbtnDisplay
.
Declare an array of strings called
fruits
with the values{ "Apple", "Banana", "Cherry", "Mango" }
.On the button click, use the
AddRange()
method to display all elements of thefruits
array in the ListBox.
ANSWERS
Exercise 1: Declaring and Initializing Arrays
csharpCopy code// Declare and initialize the array
string[] fruits = { "Apple", "Banana", "Cherry", "Mango" };
// Print the second element to the console
Console.WriteLine(fruits[1]);
Exercise 2: Accessing Array Elements
csharpCopy code// Declare and initialize the array
int[] ages = { 25, 30, 35, 40 };
// Assign the last element to a new variable
int lastAge = ages[ages.Length - 1];
// Print the value of lastAge to the console
Console.WriteLine(lastAge);
Exercise 3: Array Length
csharpCopy code// Declare and initialize the array
string[] cities = { "New York", "London", "Tokyo", "Paris" };
// Print the total number of elements in the array
Console.WriteLine("Total number of cities: " + cities.Length);
Exercise 4: Sum of Array Elements
csharpCopy code// Declare and initialize the array
int[] expenses = { 1200, 800, 500, 300, 200 };
// Calculate the total sum
int total = 0;
foreach (int expense in expenses)
{
total += expense;
}
// Print the total sum
Console.WriteLine("Total expenses: " + total);
Exercise 5: Display Array Elements in a ListBox
Windows Forms Code
Drag a
ListBox
(listBox1
) and aButton
(btnDisplay
) onto the form.-
Add the following code to the button's click event:
csharpCopy code// Declare and initialize the array
string[] fruits = { "Apple", "Banana", "Cherry", "Mango" };
// Add the array elements to the ListBox
listBox1.Items.AddRange(fruits);