Arrays and Loops
Arrays and Loops
2024, 7:54 PM
Cheatsheets / Learn C#
C# Arrays
In C#, an array is a structure representing a fixed // `numbers` array that stores integers
length ordered collection of values or objects
int[] numbers = { 3, 14, 59 };
with the same type.
Arrays make it easier to organize and operate on
large amounts of data. For example, rather than // 'characters' array that stores
creating 100 integer variables, you can just
strings
create one array that stores all those integers!
string[] characters = new string[] {
"Huey", "Dewey", "Louie" };
Declaring Arrays
about:srcdoc Page 1 of 7
19.01.2024, 7:54 PM
In C#, one way an array can be declared and // `numbers` and `animals` are both
initialized at the same time is by assigning the
declared and initialized with values.
newly declared array to a comma separated list
of the values surrounded by curly braces ( {} ). int[] numbers = { 1, 3, -10, 5, 8 };
Note how we can omit the type signature and string[] animals = { "shark", "bear",
new keyword on the right side of the
"dog", "raccoon" };
assignment using this syntax. This is only
possible during the array’s declaration.
In C#, the elements of an array are labeled // Initialize an array with 6 values.
incrementally, starting at 0 for the first element.
int[] numbers = { 3, 14, 59, 26, 53, 0
For example, the 3rd element of an array would
be indexed at 2, and the 6th element of an array };
would be indexed at 5.
A specific element can be accessed by using the
// Assign the last element, the 6th
square bracket operator, surrounding the index
with square brackets. Once accessed, the number in the array (currently 0), to
element can be used in an expression, or 58.
modified like a regular variable.
numbers[5] = 58;
about:srcdoc Page 2 of 7
19.01.2024, 7:54 PM
C# Array Length
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
looping once i is greater than 10, and
provided 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 for (int i = 1; i <= 10; i++) {
the start of the loop, usually used to
Console.WriteLine(i);
initialize the 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 come!");
update the iterator variable.
about:srcdoc Page 3 of 7
19.01.2024, 7:54 PM
C# While Loop
about:srcdoc Page 4 of 7
19.01.2024, 7:54 PM
C# Do While Loop
C# Infinite Loop
about:srcdoc Page 5 of 7
19.01.2024, 7:54 PM
C# Jump Statements
Print Share
about:srcdoc Page 6 of 7
19.01.2024, 7:54 PM
about:srcdoc Page 7 of 7