0% found this document useful (0 votes)
65 views7 pages

Arrays and Loops

The document provides an overview of arrays and loops in C#, including: 1) How to declare, initialize, and access elements of arrays. Arrays allow storing multiple values of the same type. 2) Details on for, foreach, while, and do-while loops. For loops iterate a specified number of times, foreach loops iterate over collections, and while/do-while loops iterate until a condition is false. 3) An infinite loop is described, which will continuously execute without stopping unless terminated.

Uploaded by

cf8qrn9q4r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views7 pages

Arrays and Loops

The document provides an overview of arrays and loops in C#, including: 1) How to declare, initialize, and access elements of arrays. Arrays allow storing multiple values of the same type. 2) Details on for, foreach, while, and do-while loops. For loops iterate a specified number of times, foreach loops iterate over collections, and while/do-while loops iterate until a condition is false. 3) An infinite loop is described, which will continuously execute without stopping unless terminated.

Uploaded by

cf8qrn9q4r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

19.01.

2024, 7:54 PM

Cheatsheets / Learn C#

Learn C#: Arrays and Loops

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

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


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

about:srcdoc Page 1 of 7
19.01.2024, 7:54 PM

Declare and Initialize array

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.

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.
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;

// Store the first element, 3, in the


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

about:srcdoc Page 2 of 7
19.01.2024, 7:54 PM

C# Array Length

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


to get the number of elements in a particular
Console.WriteLine(someArray.Length); //
array.
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
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# For Each Loop

A C# foreach loop runs a set of instructions string[] states = { "Alabama",


once for each element in a given collection. For
"Alaska", "Arizona", "Arkansas",
example, if an array has 200 elements, then the
foreach loop’s body will execute 200 times. "California", "Colorado" };
At the start of each iteration, a variable is
initialized to the current element being
foreach (string state in states) {
processed.
A for each loop is declared with the foreach // The `state` variable takes on the
keyword. Next, in parentheses, a variable type value of an element in `states` and
and variable name followed by the in keyword updates every iteration.
and the collection to iterate over.
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 thinking of?");
instruction, terminates the loop.
Note that the loop body might not run at all,
// This loop will keep prompting the
since 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 (guess != "dog") {
while keyword followed by a boolean Console.WriteLine("Make a guess:");
condition in parentheses.
guess = Console.ReadLine();
}
Console.WriteLine("That's right!");

about:srcdoc Page 4 of 7
19.01.2024, 7:54 PM

C# Do While Loop

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


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

C# Infinite Loop

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


because its stopping condition is always
// This will loop forever unless it
false . An infinite loop can be useful if a
program consists of continuously executing one contains some terminating statement
chunk of code. But, an unintentional infinite loop such as `break`.
can cause a program to hang and become
}
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.

about:srcdoc Page 5 of 7
19.01.2024, 7:54 PM

C# Jump Statements

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


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

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

about:srcdoc Page 6 of 7
19.01.2024, 7:54 PM

about:srcdoc Page 7 of 7

You might also like