Hello C# 004

"Perfecting oneself is as much unlearning as it is learning." – Edsger Dijkstra (maybe)

Looping around

Looping is about repeating a block of instructions.
Conditionals and looping allows us to express any kind of program due to the Turing thing thingy and looping is the cool brother of jumps.

Looping is really useful when reasoning about something that needs to be repeated while (or until) a condition is met.
Like summing all the prices of the items in a checkout or determining the next position of particles in an advanced physics simulation.

Syntax

while( <CONDITION> )
<EXECUTE WHILE CONDITION IS MET>

The execute block is like the on in the if case with the same readability advice.
Languages usually provide many others `whiles` with different syntax and behaviors to ease coding, but we will cover them later.

Using it

Lets sum a list of values with 5 elements:

> var m = new int[128];
> m[1] = 5; // list size
> m[2] = 87; // first
> m[3] = 99; m[4] = 12; m[5] = 213; m[6] = -123; // second, ...
> m[100] = 0; // index
> m[101] = 0; // partial sum
> while(m[100] < m[1])
{
m[101] = m[2+m[100]] + m[101]; // sum value
m[100] = m[100] + 1; // move to next element
} // after this loop m[100] == m[1] and all elements were read
> m[0] = m[101] // note that the `=` is an expression (Wikipedia is amazing)
288

You always need to be sure that the condition in the while eventually becomes false.
In case you make a mistake, Control-C is your friend to stop the REPL and reinitialize it.

[Try by yourself] Create alternatives of the previous code that averages the values, get the max and get the min value.

[Try by yourself] Try to write a program with m[0] being a value that you want to check if it exists in the array. Set m[0] to 1 in the end if you found it and to 0 otherwise.

Up Next

Stacks!


Go home.

☆Powered by Azure Blob