SLR1 Useful Code to learn Flashcards
What code counts the elements in an array?
[int] numberArray.Count()
[string] stringArray.Count()
What should the statement switch be used for?
Use the switch statement to select one of many code blocks to be executed.
Code for a switch:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
How does the switch statement work?
This is how it works:
- The switch expression is evaluated once
- The value of the expression is compared with the values of each case
- If there is a match, the associated block of code is executed
Why is the break needed in a switch statement?
When C# reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
default code in switch code and why its needed:
default:
Console.WriteLine(“Looking forward to the Weekend.”);
break;
default keyword is optional and specifies some code to run if there is no case match
shorthand for if else statements:
variable = (condition) ? expressionTrue : expressionFalse;
continue statement
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop
if (i == 4)
{
continue;
}
creating an array
string[] cars;
how to output the first elements of an array:
string[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
Console.WriteLine(cars[0]);
// Outputs Volvo
Changing the first element in an array to Opel
string[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
cars[0] = “Opel”;
Console.WriteLine(cars[0]);
Printing the length of the array
string[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
Console.WriteLine(cars.Length);
Declaring an array and adding new values to it (cars again)
// Declare an array
string[] cars;
// Add values, using new
cars = new string[] {“Volvo”, “BMW”, “Ford”};
Print all the elements in the array:
string[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
for (int i = 0; i < cars.Length; i++)
{
Console.WriteLine(cars[i]);
}
What type of loop is used exclusively to loop through an array?
string[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
a foreach loop
foreach (string i in cars)
{
Console.WriteLine(i);
}