Beginner C# Array Practice for HNDIT Learners

Beginner C# Array Practice for HNDIT Learners

Exercise 1: Declaring and Initializing Arrays

Write the code to:

  1. Declare an array of strings called fruits and initialize it with the following values: "Apple", "Banana", "Cherry", "Mango".

  2. Print the second element in the array to the console.


Exercise 2: Accessing Array Elements

  1. Declare an array of integers called ages with the values {25, 30, 35, 40}.

  2. Assign the last element of the array to a new integer variable lastAge.

  3. Print the value of lastAge to the console.


Exercise 3: Array Length

  1. Create an array of strings called cities with the values: "New York", "London", "Tokyo", "Paris".

  2. Write a program to print the total number of elements in the `cities


Exercise 4: Sum of Array Elements

  1. Create an array of integers called expenses with the values {1200, 800, 500, 300, 200}.

  2. Use a loop to calculate and print the total sum of the elements in the array.


Exercise 5: Display Array Elements in a ListBox

  1. Create a Windows Form with:

    • A ListBox named listBox1.

    • A Button named btnDisplay.

  2. Declare an array of strings called fruits with the values { "Apple", "Banana", "Cherry", "Mango" }.

  3. On the button click, use the AddRange() method to display all elements of the fruits 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

  1. Drag a ListBox (listBox1) and a Button (btnDisplay) onto the form.

  2. 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);