Working with Arrays in C#

0.0(0)
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/4

flashcard set

Earn XP

Description and Tags

Arrays, Multidimensional Arrays, Looping through arrays, accessing elements in arrays

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

5 Terms

1
New cards

Define “Array”

Single variable used to store multiple values (instead of declaring separate variables for each value).

2
New cards

How To: Create an Array

To declare (create) an array:

  • variable type immediately followed by empty square brackets

  • space

  • variable name

  • assignment operator

  • array literal (comma separated list, enclosed in curly brackets)

Syntax:

varType[] varName = {item, item, item}

3
New cards

Demonstrate how to…

  • Create an array called “myFavMakeup” with the items being your favourite makeup products.

  • Print this array out to console.

using System; 

class Program
{
    static void Main(string[] args)
    {
        string[] myFavMakeup = {"lipgloss", "blush", "concealer", "setting spray"}; // Declared array myFavMakeup
        Console.WriteLine(string.Join(", ", myFavMakeup)); // Printing array out to console as a string
    }
}

4
New cards
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine($"These are my favourite cars:"{cars}")

Sarah intends to print the array ‘cars’ as output to the console. However, instead of the array printing out, something else prints out instead.

(a) What is printed as output to the console?

(b) What error did Sarah make in her code? How can this be fixed?

(a) What is printed as output to the console?

System.String[] 

This would be the output printed in the console.

This is the array’s type (i.e. string)

(b) What error did Sarah make in her code? How can this be fixed?

Console.WriteLine(${array_name}) //cannot be used to print out the contents of an array

//Instead use a loop or a method like string.Join 

//Example: Sarah's code using a loop to print out array
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < cars.Length; i++)
{
    Console.WriteLine(cars[i]);
}

//Example: Sarah's code using string.Join method print out array
using System; 

class Program 
{
	static void Main(string[] args)
	{
		string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

5
New cards