1/4
Arrays, Multidimensional Arrays, Looping through arrays, accessing elements in arrays
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Define “Array”
Single variable used to store multiple values (instead of declaring separate variables for each value).
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}
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
}
}
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"};