0% found this document useful (0 votes)
2 views

Learn C#_ Learn C#_ Arrays and Loops Cheatsheet _ Codecademy

This document is a cheatsheet for learning C# arrays and loops, covering key concepts such as array declaration, initialization, element access, and various types of loops including for, foreach, while, and do while. It also explains the use of infinite loops and jump statements like break and continue for controlling program flow. The content is structured with code examples to illustrate the concepts effectively.

Uploaded by

Michael Okocha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Learn C#_ Learn C#_ Arrays and Loops Cheatsheet _ Codecademy

This document is a cheatsheet for learning C# arrays and loops, covering key concepts such as array declaration, initialization, element access, and various types of loops including for, foreach, while, and do while. It also explains the use of infinite loops and jump statements like break and continue for controlling program flow. The content is structured with code examples to illustrate the concepts effectively.

Uploaded by

Michael Okocha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

10-02-2024 16:03 Learn C#: Learn C#: Arrays and Loops Cheatsheet | Codecademy

Cheatsheets / Learn C#

Learn C#: Arrays and Loops

C# Arrays

In C#, an array is a structure representing a fixed length // `numbers` array that stores integers
ordered collection of values or objects with the same
int[] numbers = { 3, 14, 59 };
type.
Arrays make it easier to organize and operate on large
amounts of data. For example, rather than creating 100 // 'characters' array that stores strings
integer variables, you can just create one array that
string[] characters = new string[] {
stores all those integers!
"Huey", "Dewey", "Louie" };

Declaring Arrays

A C# array variable is declared similarly to a non-array // Declare an array of length 8 without


variable, with the addition of square brackets ( [] ) after
setting the values.
the type specifier to denote it as an array.
The new keyword is needed when instantiating a new string[] stringArray = new string[8];
array to assign to the variable, as well as the array
length in the square brackets. The array can also be
// Declare array and set its values to 3,
instantiated with values using curly braces ( {} ). In this
case the array length is not necessary. 4, 5.
int[] intArray = new int[] { 3, 4, 5 };

Declare and Initialize array

In C#, one way an array can be declared and initialized // `numbers` and `animals` are both
at the same time is by assigning the newly declared
declared and initialized with values.
array to a comma separated list of the values
surrounded by curly braces ( {} ). Note how we can int[] numbers = { 1, 3, -10, 5, 8 };
omit the type signature and new keyword on the right string[] animals = { "shark", "bear",
side of the assignment using this syntax. This is only
"dog", "raccoon" };
possible during the array’s declaration.

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-arrays-and-loops/cheatsheet 1/5
10-02-2024 16:03 Learn C#: Learn C#: Arrays and Loops Cheatsheet | Codecademy

Array Element Access

In C#, the elements of an array are labeled // Initialize an array with 6 values.
incrementally, starting at 0 for the first element. For
int[] numbers = { 3, 14, 59, 26, 53, 0 };
example, the 3rd element of an array would be indexed
at 2, and the 6th element of an array would be indexed
at 5. // Assign the last element, the 6th
A specific element can be accessed by using the square
number in the array (currently 0), to 58.
bracket operator, surrounding the index with square
brackets. Once accessed, the element can be used in numbers[5] = 58;
an expression, or modified like a regular variable.

// Store the first element, 3, in the


variable `first`.
int first = numbers[0];

C# Array Length

The Length property of a C# array can be used to get int[] someArray = { 3, 4, 1, 6 };


the number of elements in a particular array.
Console.WriteLine(someArray.Length); //
Prints 4

string[] otherArray = { "foo", "bar",


"baz" };
Console.WriteLine(otherArray.Length); //
Prints 3

C# For Loops

A C# for loop executes a set of instructions for a // This loop initializes i to 1, stops
specified number of times, based on three provided
looping once i is greater than 10, and
expressions. The three expressions are separated by
semicolons, and in order they are: increases i by 1 after each loop.
Initialization: This is run exactly once at the for (int i = 1; i <= 10; i++) {
start of the loop, usually used to initialize the
Console.WriteLine(i);
loop’s iterator variable.
Stopping condition: This boolean expression is }
checked before each iteration to see if it should
run.
Console.WriteLine("Ready or not, here I
Iteration statement: This is executed after each
iteration of the loop, usually used to update the come!");
iterator variable.

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-arrays-and-loops/cheatsheet 2/5
10-02-2024 16:03 Learn C#: Learn C#: Arrays and Loops Cheatsheet | Codecademy

C# For Each Loop

A C# foreach loop runs a set of instructions once for string[] states = { "Alabama", "Alaska",
each element in a given collection. For example, if an
"Arizona", "Arkansas", "California",
array has 200 elements, then the foreach loop’s body
will execute 200 times. At the start of each iteration, a "Colorado" };
variable is initialized to the current element being
processed.
foreach (string state in states) {
A for each loop is declared with the foreach keyword.
Next, in parentheses, a variable type and variable name // The `state` variable takes on the
followed by the in keyword and the collection to value of an element in `states` and
iterate over. updates every iteration.
Console.WriteLine(state);
}
// Will print each element of `states` in
the order they appear in the array.

C# While Loop

In C#, a while loop executes a set of instructions string guess = "";


continuously while the given boolean expression
Console.WriteLine("What animal am I
evaluates to true or one of the instructions inside the
loop body, such as the break instruction, terminates thinking of?");
the loop.
Note that the loop body might not run at all, since the
// This loop will keep prompting the
boolean condition is evaluated before the very first
iteration of the while loop. user, until they type in "dog".
The syntax to declare a while loop is simply the while while (guess != "dog") {
keyword followed by a boolean condition in
Console.WriteLine("Make a guess:");
parentheses.
guess = Console.ReadLine();
}
Console.WriteLine("That's right!");

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-arrays-and-loops/cheatsheet 3/5
10-02-2024 16:03 Learn C#: Learn C#: Arrays and Loops Cheatsheet | Codecademy

C# Do While Loop

In C#, a do while loop runs a set of instructions once do {


and then continues running as long as the given
DoStuff();
boolean condition is true . Notice how this behavior is
nearly identical to a while loop, with the distinction that } while(boolCondition);
a do while runs one or more times, and a while loop
runs zero or more times.
// This do-while is equivalent to the
The syntax to declare a do while is the do keyword,
followed by the code block, then the while keyword following while loop.
with the boolean condition in parentheses. Note that a
semi-colon is necessary to end a do while loop.
DoStuff();
while (boolCondition) {
DoStuff();
}

C# Infinite Loop

An infinite loop is a loop that never terminates because while (true) {


its stopping condition is always false . An infinite loop
// This will loop forever unless it
can be useful if a program consists of continuously
executing one chunk of code. But, an unintentional contains some terminating statement such
infinite loop can cause a program to hang and become as `break`.
unresponsive due to being stuck in the loop.
}
A program running in a shell or terminal stuck in an
infinite loop can be ended by terminating the process.

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-arrays-and-loops/cheatsheet 4/5
10-02-2024 16:03 Learn C#: Learn C#: Arrays and Loops Cheatsheet | Codecademy

C# Jump Statements

Jump statements are tools used to give the while (true) {


programmer additional control over the program’s
Console.WriteLine("This prints once.");
control flow. They are very commonly used in the
context of loops to exit from the loop or to skip parts of // A `break` statement immediately
the loop. terminates the loop that contains it.
Control flow keywords include break , continue , and
break;
return . The given code snippets provide examples of
their usage. }

for (int i = 1; i <= 10; i++) {


// This prints every number from 1 to
10 except for 7.
if (i == 7) {
// A `continue` statement skips the
rest of the loop and starts another
iteration from the start.
continue;
}
Console.WriteLine(i);
}

static int WeirdReturnOne() {


while (true) {
// Since `return` exits the method,
the loop is also terminated. Control
returns to the method's caller.
return 1;
}
}

Print Share

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-arrays-and-loops/cheatsheet 5/5

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy