The way of the program

The goal of these notes is to help you to think like a computer scientist. This way of thinking combines some of the best features of mathematics, engineering, natural science, philosophy and art. If you like any of those, you might find that you like Computer Science, too. Most of all, Computer Science is challenging and fun, and a good computer scientist is always surprised that people are willing to pay him or her to work on interesting problems and have fun all day!

The single most important skill for a new computer scientist is problem-solving. Problem-solving means the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately. As it turns out, the process of learning to program is an excellent opportunity to practice problem-solving skills. Programming is the process of translating problem-solving into a language that the computer can understand. That’s why these notes are called “The way of the program”.

Important

These notes are incomplete! They do not cover some important topics which are better to discuss in class than to put down as notes. Therefore, the notes are not a substitute for attending the lectures.

What is a program?

A program is a sequence of instructions that tells the computer what to do. These instructions are given in the form of a programming language, and are sometimes called code. After writing a program, you can tell the computer to check whether the instructions make sense (this is called compiling a program; the computer uses a compiler to compile a program) and, if they make sense, you can ask the computer to follow the instructions (this is called executing or running the program). We also say that instructions are executed.

The programming language you will be learning is called C#.

Programming languages such as C# are extremely unforgiving. If a single letter or punctuation-mark of the program is out-of-place or missing, the program will not compile. Many programming languages are so strict that they don’t even allow you to alter the case of a letter – so if you type If instead of if, your program will probably fail to compile! Beginning programmers make many simple mistakes because they aren’t precise enough. With practice and caution, you will make fewer and fewer of these simple mistakes, until you eventually make no simple mistakes whatsoever.

Basic C# programming theory

Types

Before you can write your first program, there is some theory that you must know. The first thing to know is that according to C#, everything has a type. For example, 2 is an integer. We can say that the type of 2 is integer. It is important to understand that the type of something is not the same as the thing itself: 2 is an integer, but all integers are not 2.

C# knows about five primitive types, described below:

int
This is any whole number between approximately -2,000,000,000 and 2,000,000,000.
bool
This is either true or false.
double
This is any number with a dot in it.
char
This is any single character, digit, or punctuation mark. In C#, a char is always enclosed in single-quotation ( ‘ ) marks.
string
This is zero or more characters, digits, and/or punctuation marks. In C#, a string is always enclosed in quotation ( ” ) marks.

Important

We will be referring to these five types very often, and using one or more of them in every single program that we write! Therefore, become very familiar with them. When you hear the word string or bool, for example, you should immediately understand the Computer Science meaning of that term; and whenever you see any data, you should immediately understand what its type is.

Type Examples
int
  • 576
  • -873
  • 0
bool
  • true
  • false
double
  • 7.51954
  • 985.0
  • -33.614
char
  • ‘8’
  • ‘z’
  • ‘,’
  • ‘ ‘
string
  • “Pi, as an irrational number, cannot be represented accurately by any simple fraction.”
  • “z”
  • “”
  • ” “

Exercises

What is the type of:

  1. 89.9 ______________________________________
  2. false ______________________________________
  3. ‘p’ ______________________________________
  4. -0.0 ______________________________________
  5. 11 ______________________________________
  6. ‘0’ ______________________________________
  7. 0 ______________________________________
  8. “0” ______________________________________
  9. true ______________________________________
  10. “z” ______________________________________
  11. “775.21” ______________________________________

Which type would you use to represent:

  1. Your name? ______________________________________
  2. Your age in years? ______________________________________
  3. Whether you are alive? ______________________________________
  4. Your grade (A, B, C, D, or E) for an assignment? ______________________________________
  5. The length of this line ——— in centimeters? ______________________________________
  6. The number of pages in a book? ______________________________________
  7. The exact price of a bottle of milk? ______________________________________
  8. Whether you have eaten anything in the last 6 hours? ______________________________________
  9. The second letter of your first name? ______________________________________
  10. The number of grains of sand in a jar? ______________________________________
  11. The square root of 2? ______________________________________
  12. Your reasons for coming to Rhodes? ______________________________________
  13. The colour of your eyes? ______________________________________

Working with time

The second (and last) bit of theory to know before we begin writing programs is that programming instructions are executed sequentially [1], one after the other. This means that the order in which you write programming statements matters. If you get the order incorrect, the program will do the incorrect thing.

The order in which statements could be executed is called the control flow of the program. Control flow consists of multiple paths, each of which could be taken during program execution. One of the most important skills of a programmer is the ability to “see” the control flow of a program [2]. The best way to get better at “seeing” control flow is to read other people’s programs, try to work out what they do without executing them, and then execute them to see if your reasoning was correct (or, if your reasoning was incorrect, where and why it was incorrect).

There are many techniques and tools that programmers have created to help themselves to visualise control flow: flowcharts, trace tables, call graphs, sequence diagrams, and so on. We may cover some of these in class. If you don’t find the standard tools for visualising control flow to be useful, you must invent your own notation or visualisation for understanding control flow.

[1]This is a slight simplification. You will learn about non-sequential control flows in your second or third year.
[2]This is not strictly true for all programming languages, but it is true for the vast majority of mainstream programming languages.

A first program

With that, you are ready to begin your first program!

int a;
int b;
int c;

This simply says that an int called a exists, an int called b exists, and an int called c exists. Notice that each statement ends with a ; (semicolon) character. A shorthand, equivalent way of saying exactly the same thing is

int a, b, c;

a, b, and c are variables (or identifiers, or symbols). A variable is a name and type [3] that is associated with a value for a limited period of time. The value of a variable can be changed, but its name and type cannot. The programming instructions above are called variable declarations, since they declare that something exists. Identifiers should start with a letter and contain no spaces or punctuation.

Important

A variable in Computer Science is not the same as a variable in Statistics, or a variable in Mathematics. Understand the specific Computer Science meaning, and do not confuse it with your other subjects!

Merely saying that something exists doesn’t make for an exciting program. Let’s try this program instead:

int a, b, c;
a = 5;
b = 10;
c = a + b;

Let’s understand what it does. First, we declare the a, b, and c variables. Then we assign the value 5 to a. Then we give the value 10 to b. Lastly, we assign the value 15 to c. These statements, of the form X = Y;, are called assignment statements. Assignment statements are used to change the value of a variable. All assignment statements have a right-hand-side (on the right of the = sign) and a left-hand-side (on the left of the = sign). There is always a variable name on the left-hand-side. An assignment statement executes the right-hand-side first, and then assigns the resulting value to the variable on the left-hand-side. This is why the variable c is given the value 15, rather than the value a + b.

We can tighten this code up a bit, by combining declarations and assignment statements, and reduce it from 4 lines to 3 lines in length.

int a = 5;
int b = 10;
int c = a + b;

C# is sometimes smart enough to figure out what the type of a variable is, as long as you assign something to it. So you could also write

var a = 5;
var b = 10;
var c = a + b;

And if we’d like to, we can use the shorthand form of declarations to reduce it to a single line:

int a = 5, b = 10, c = a + b;

If we do this, though, we can’t replace the int with a var. C# isn’t smart enough to figure out what the types of a, b, and c are in that case [4].

Variables exist from the point that you create them, until the end of the block in which you create them. Right now, you’re only seeing one block; later, when you are using many blocks, this will become much more important. Variable names must be unique within a block [5]. This means that you cannot have two variables named x within the same block, for example.

Putting things together

If you’re not yet convinced that Computer Science isn’t Mathematics, think about this: in Mathematics, there are common equivalents for int, double, and bool types. There are no common equivalents for char and string types. That might be because Computer Science is a more practical and pragmatic discipline, and one of the common things that people want to be able to do is read and write text. So it makes sense for Computer Science to have char and string, and it makes sense for Mathematics to not use those types. It also makes sense for programming languages, such as C#, to use those types in a non-mathematical way. For example, if you wrote this:

string a = "super";
string b = "man";
string c = a + b;

That would be perfectly OK in C# (and c would end up with the value superman). In Computer Science, + commonly means put these things together. If you put two ints together, you get the sum of the ints. If you put two strings together, you get the combined value of both strings. This makes absolutely no sense, mathematically. But this is Computer Science – not Mathematics!

[3]In other languages, a variable is just a name associated with a value. You will learn about these kinds of variables in later years, when you will encounter dynamic, untyped, and functional languages.
[4]Other languages, which you could learn about in due course, are smart enough to do this. Most of these smarter languages use a fascinating method known as Hindley-Milner type inference.
[5]They must also be unique within blocks-within-blocks, which you’ll encounter later on in this semester.

Exercises

There is something wrong with each of these lines of code. For each line, write a sentence describing what is wrong.

  1. in a;

  1. string a b;

  1. bool a

  1. int a, string b;

  1. var a;

  1. int 3d;

  1. int a = 3.0;

  1. double a, b = 5.0, c = “6.0”;

  1. var a = 9, b = 8;

  1. char zoology = “”;

  1. char biology = “E”;

  1. bool botany = True;

  1. INT CHEMISTRY = 100;

  1. bool able, able;

  1. int articulate = 8; bool ampersand = articulate;

  1. string o’brien = “Connor”;

What is the type of x?

  1. var x = “Yes”; _______________
  2. var x = 213; _______________
  3. var x = 0.0; _______________
  4. var x = ‘y’; _______________
  5. var x = “y”; _______________
  6. var x = true; _______________
  7. var x = 5 + 3; _______________
  8. var x = “false”; _______________
  9. var x = 3.2/5.1; _______________
  10. var x = false; _______________
  11. var x = “20/5”; _______________

Basic Arithmetic

There are five arithmetic operators that are used in C#. The first four should be familiar to you from school:

  • X + Y adds X and Y
  • X - Y subtracts Y from X
  • X * Y multiplies X and Y
  • X / Y divides X by Y

The last operator is the modulus operator:

  • X % Y gives the remainder that would result from dividing X by Y

The first time you did division at school, you probably expressed your answer as “A remainder B”. For example, you would say that 7 divided by 4 was “1 remainder 3”, or that 24 divided by 6 was “4 remainder 0”. The modulus operation gives you the “remainder” part of the answer; so 7 % 4 = 3, and 24 % 6 = 0. The sign of the answer is the same as the sign of the dividend (so, for example, -7 % 4 = -3).

You can group arithmetic terms using brackets, just as you would in ordinary mathematics. The usual precedence of operations (brackets, division & multiplication, addition & subtraction) applies to arithmetic expressions in C#. When operators have the same precedence, arithmetic expressions are evaluated from left to right.

Arithmetic that is done exclusively with ints always results in integer answers. This means that 7 / 4 = 1, and not 1.75 or 2. Arithmetic that is done exclusively with doubles results in double answers. This means that 7.0 / 4.0 = 1.75. Arithmetic that mixes doubles and ints results in double answers. This means that 7.0 / 4 = 1.75, and 7 / 4.0 = 1.75.

Exercises

What is the answer to these arithmetic expressions? When the answer is a double, be sure to show a decimal point in your answer.

  1. 6 * 4 - 1 ________
  2. 6 * (4 - 1) ________
  3. 3.2 * 2.0 ________
  4. 3.2 * 2 ________
  5. (3 * (5 - 2) / 4) + 1 ________
  6. ((5 - 2) / 4 * 3) + 1 ________
  7. 1 + 1.0 ________
  8. (-(-2) + (-2 * -2 - 4 * 3 * 2)) / 2 * 3 ________
  9. (-(-2) + (-2 * -2 - 4.0 * 3 * 2)) / 2 * 3 ________
  10. 8 - -8 ________
  11. (10 * 7) % 3 ________
  12. (5 % 2) + (71553 % 2) ________
  13. (19 % 4) + (-72 % 10) ________

Debugging

Programming is a complex process, and because programs are written by human beings, they often contain errors. Some of these errors are simple, like messing up the grammar of the programming language, and the compiler can tell you there’s a problem and (usually) also tell you where it is, so you can fix it. These kinds of simple errors are called syntax errors. Syntax refers to the structure of a program and the rules about that structure. Mis-spelling a word in a programming language, or putting it in the wrong order, or not including necessary punctuation, or including too much punctuation, or not capitalising a word that should be capitalised (or vice versa!) are all examples of syntax errors.

During the first few weeks of your programming career, you will probably spend a lot of time tracking down syntax errors. As you gain experience, you will make fewer syntax errors and find them faster. After a few weeks, you won’t make any syntax errors at all! This is just like the process of learning a new spoken language. While you are learning, you will make silly errors that a native speaker wouldn’t make. But after a while, you don’t make any errors. And, just like learning a new spoken language, the more you practise, the better you’ll get ... and if you don’t practice enough, you’ll keep making mistakes. So practice: it really does make a big difference.

The more difficult errors are semantic errors, where you’ve given the computer a valid sequence of instructions, but the instructions don’t lead to the result that you think they lead to. You’ll run into plenty of these, and when you do you’ll need to understand exactly what you’re asking the computer to do, so that you can figure out where the flaw in your reasoning is.

Runtime errors, which cause a program to stop running, occur because of semantic errors. Usually, you’ve made the error of assuming something that you shouldn’t have assumed! These errors are also called exceptions because they indicate that something exceptional (and bad) has happened.

Programming errors are called bugs and the process of tracking them down and correcting them is called debugging. It is useful to distinguish between types of bugs in order to find the cause of the error and fix it more quickly. Here is how you can distinguish between types of bugs:

  1. Do you get errors when you compile the program? If so, you have a syntax error.
  2. Does the program fail to do what you expect it to do? If so, you have a semantic error.
  3. Does the program stop running before you expect it to? If so, you have a runtime error which is caused by a semantic error. You need to fix the semantic error so that the runtime error will go away.

What if ...?

For our second program, let’s make a simple password program. If you give it the right password, it will tell you some secret message. If you don’t give it the right password, it’ll tell you to go away.

string password = Password.Text;
bool passwordIsOK = password == "top sekrit";
if (passwordIsOK) {
   Result.Content = "My secret message is: Hi, how are you?";
} else {
   Result.Content = "Go away.  You don't know the password.";
}

The first line is easy: a combined declaration and assignment. The second line is where we check whether the password is correct or not. We do this using the ==, which compares two things for equality. If the things are equal, the expression is true; otherwise, the expression is false. There are a few other symbol-combinations (called operators) which are useful for comparing things, and it’s useful to know what they are when you want to make your own conditions:

X == Y true if X is equal to Y
X >= Y true if X is greater than or equal to Y
X <= Y true if X is less than or equal to Y
X != Y true if X is not equal to Y
X > Y true if X is greater than Y
X < Y true if X is less than Y

X and Y may be any expressions, as long as the expressions have the same type. Memorise these operators. They will be used in almost every program that you will write.

Then we come to an if-statement. An if-statement is a way of doing something only if some expression (which is called the condition of the if-statement) is true. In this case, if passwordIsOK is true, then Result.Content will be given the value My secret message is: Hi, how are you?. If it’s not true, then Go away. You don’t know the password. will be assigned to Result.Content.

Conditions must result in a bool value. If your condition results in a string, int, double or anything except a bool value, your program will not compile.

The else part of an if-statement is optional. This means that if you only wanted to do something when the password was correct, you could have written

if (Password.Text == "top sekrit") {
   Result.Content = "My secret message is: Hi, how are you?";
}

Important

In class, you will already have seen brackets being used to group terms, just as you would do in Mathematics. In the if-statement, brackets are used to tell C# where the condition starts and ends. Within the brackets, you can have other brackets if you want to group terms.

Exercises

What is the answer to these expressions?

  1. 5 < 3 __________
  2. 5 > 3 __________
  3. 6 <= 6 __________
  4. 6 >= 6 __________
  5. 6 < 6 __________
  6. 6 == 6 __________
  7. 6 != 6 __________
  8. 8 != 6 __________
  9. 7 >= 6 __________
  10. 5 - 3 > 2 + 1 __________
  11. 3 - 5 < 1 - 2 __________
  12. “apple” != “orange” __________
  13. “banana” <= “candy” __________
  14. 3.14 * 2 > 6 __________

There’s something wrong with each of the following pieces of code. For each piece of code, write a sentence describing what is wrong.

if 5 > 3 {
   Result.Content = "Something";
}


if (5 <> 3) {
   Result.Content = "Something";
}


if ("true") {
   Result.Content = "Something";
}


if () {
   Result.Content = "Something";
}


If (5 + 3 < 7) {
   Result.Content = "Something";
}


if (5 + 3 < 7) {
   Result.Content = "Something";


if {
   Result.Content = "Something";
}


if (5 - 7 > 3)
   Result.Content = "Something";
}


Many conditions

Let’s extend the previous program a bit. Now, instead of merely typing in the password, the person must type in a name and a password – and we will only display our secret message if both name and password are what they are supposed to be. Code for that could look like this:

string name = Name.Text;
string password = Password.Text;
bool nameIsFine = name == "Bruce Wayne";
bool passwordIsOK = password == "top sekrit";
if (nameIsFine && passwordIsOK) {
   Result.Content = "My secret message is: Hi, how are you?";
} else {
   Result.Content = "Go away.  You don't know the password.";
}

Compare this with the original program. The primary difference between that program and this one is this line:

if (nameIsFine && passwordIsOK) {

The nameIsFine && passwordIsOK expression will be true only when both nameIsFine and passwordIsOK are true. If we wanted it to be true when either (or both) of nameIsFine and passwordIsOK were true, then we could have written nameIsFine || passwordIsOK. If, for some reason, we wanted it to be true when neither nameIsFine nor passwordIsOK were true, we could have written !nameIsFine && !passwordIsOK. &&, || and ! are boolean operators, just as +, -, *, / and % are arithmetic operators. They are called boolean operators because they work with bool values. The table below explains their behaviour.

Name Usage Result
not !X true only if X is false
and X && Y true only if both X and Y are true
or X || Y true if X or Y or both are true

Just as arithmetic operators have a precedence, so do boolean operators. You can use brackets to override the default precedence, just as you do with arithmetic expressions. The precedence of boolean operators is: brackets, not, and, or. Memorise the operators and their precedence, and be able to read and write boolean expressions.

Exercises

What is the answer to these boolean expressions?

  1. 5 > 3 && “apple” < “banana” __________
  2. 6 != 5 && 3 >= -7 __________
  3. (4.3 + 2) < 5 && true __________
  4. false && 6 * 0.5 == 3 __________
  5. true || true __________
  6. true || false __________
  7. false || true __________
  8. true || true __________
  9. !true __________
  10. !false __________
  11. !true && !false __________
  12. !(true || false) __________
  13. !!true __________
  14. !(true && false) __________
  15. !false || !true __________
  16. (true && false) || (!false && true) __________
  17. true && false || false && false || true && true __________
  18. true && (false || false) && (false || true) && true __________

Arrays and iteration

Variables are useful, but there’s no good way to handle some situations with them. For example, if you want to create a program that says “hello” to all the students in a class, you might find yourself writing code like this:

string student1 = "Aaron Aaronsson", student2 = "Bertram Bjork",
   student3 = "Carrie Clump", student4 = "Daphne Dalton",
   student5 = "Edsger Extra";
Greetings.Items.Add("hello " + student1);
Greetings.Items.Add("hello " + student2);
Greetings.Items.Add("hello " + student3);
Greetings.Items.Add("hello " + student4);
Greetings.Items.Add("hello " + student5);

Or, if you don’t want to put each student’s name into a separate variable, you could write this program instead:

Greetings.Items.Add("hello Aaron Aaronsson");
Greetings.Items.Add("hello Bertram Bjork");
Greetings.Items.Add("hello Carrie Clump");
Greetings.Items.Add("hello Daphne Dalton");
Greetings.Items.Add("hello Edsger Extra");

This isn’t such a big improvement. We’ve saved one line of typing, but the amount of typing we’ll have to do stays approximately the same. For a class of 100 people, you’d end up typing Greetings.Items.Add(“hello ... 100 times. And what if we want to change the program to say “goodbye” instead? We’d have to change 100 lines.

In C#, the way to deal with many items is by using arrays and iteration. An array is a variable that holds a fixed-size list of a particular type. So, we could have an array of student names; but before we make that array, let’s look at some of the syntaxes for creating an array. Any of the following syntaxes will create the same array:

int[] xs = new int[] { 8, 7, 6 };
var xs = new int[] { 8, 7, 6 };
var xs = new [] { 8, 7, 6 };
int[] xs = { 8, 7, 6 };

Each item in an array is called an element (or just an item) of the array. .. The very first element is said to have an index of zero, the next one has an index of 1, the next has an index of 2, and so on. The length (or count) of an array is the number of items in the array. Using arrays, you could store all the student names in a single variable:

string[] students = new string[] { "Aaron Aaronsson",
   "Bertram Bjork", "Carrie Clump", "Daphne Dalton",
   "Edsger Extra" };

Once we have data in an array, we can go through it using iteration (or looping). Iteration is the ability to execute the same programming instructions over and over. The trick of iteration is to apply the same programming instruction to different data. There is a special kind of iteration (or loop) called foreach which does exactly this.

foreach (var x in students) {
   Greetings.Items.Add("hello " + x);
}

Here, we are applying the same programming instruction – Greetings.Items.Add(“hello ... – to each name in the array. Within the block, the x variable is given the value of a data item in the array. If there are 50 names in the array, the programming instructions in the block will be executed 50 times. If there are 5000, the programming instructions in the block will be executed 5000 times. Each time the block is executed, the x variable is assigned the next value in the array. Iteration is a great way to save time and avoid typing hundreds or thousands of lines.

Exercises

What is the length of each of these arrays?

char[] zs = new char[] { 'x', 'c', 'y', 'p' };

string[] p = new [] { };

var abc = new bool[] { true, true, true, true, false };

int[] woo = { 0 };

There’s something wrong with each of the following pieces of code. For each piece of code, write a sentence describing what is wrong.

var[] abc = new int[] { 5 };


int[] moo = new string[] { "hi", "lo" };


string[] moo = new int[] { 3, 9, 1 };


var prst = new [] { 3, 4.0 };


string[] artists = new string[] { "Michel", "Don", "Leo", "Raph" };
foreach (int turtle in artists) {
   Output.Items.Add(turtle);
}


string[] artists = new string[] { "Michel", "Don", "Leo", "Raph" };
foreach (turtle in artists) {
   Output.Items.Add(turtle);
}


string[] artists = new string[] { "Michel", "Don", "Leo", "Raph" };
foreach (artists) {
   Output.Items.Add(artists);
}


var artists = new int[] { 6, 5, 4, 3, 2, 1 };
foreach (var xyz in artists) {
   Output.Items.Add(turtle);
}


Conversions

Sometimes you’ll have a string, but what you really want is an int, so that you can add a number to it. Sometimes you’ll have a bool, but what you really want is a string, so it’s easier to print out. C# makes this easy by providing ways to convert from one type to another. For example, to convert from a string to an integer, you would use code like this:

int converted = Convert.ToInt32(myStringHere);

Other conversions are similar in nature; see (and consider memorising) the table below.

To convert to a... ...use code like:
int Convert.ToInt32(x)
string String.Format(“{0}”,x)
bool Convert.ToBoolean(x)
double Convert.ToDouble(x)
char Convert.ToChar(x)

Some conversions which don’t make any sense (such as converting a bool to a char) will cause an error, but other conversions that don’t seem to make any sense will succeed, such as converting an int to a bool. As a rule of thumb, if you can sensibly anticipate what the result of a conversion will be, then the conversion is likely to work. If you can’t anticipate the result, it’s not worth trying to convert between types: even if the conversion succeeds, the converted value might not make any sense to you.

Just about anything can be converted to a string, and when we print out some data, we usually also want to print out other text. For example, you might want to print out “My name is NAME and I am AGE years old” if you have a variable that contains someone’s name and another variable that contains their age. In C#, you could write

string name = Name.Text;
int age = Convert.ToInt32(Age.Text);
string s = String.Format("My name is {0} and I am {1} years old", name, age);
Result.Content = s;

If you look at the third line, you’ll see String.Format being used. We’ll go over String.Format and how it’s used in class, so be sure to ask questions and make notes!

Exercises

Study the following code:

string name = "Veronica";
int age = 25;
string s = __________________________________________;
Result.Content = s;

If you wanted to print out I’m a 25-year-old named Veronica, you would fill in the blank with

String.Format("I'm a {0}-year-old named {1}", age, name)

What would you fill in the blank with if you wanted to print out...

  1. Veronica is my name, and I’m 25


  1. Hi, I’m Veronica.


  1. Just another 25-year old here.


  1. 25 is such a nice age for Veronica.


  1. 25? Yes, 25.


  1. The name’s Veronica. Veronica Veronica.


  1. Name: Veronica. Age: 25 (or around 25).


Conditional iteration

Iteration can also be used to save time when you want to keep doing something until some condition is met. For example, you might want to keep multiplying a number by 2 until it is bigger than some other number. To do that, you could write code like

int targetNumber = 2314;
int n = 1;
while (n < targetNumber) {
   n = n * 2;
}

The first two lines are easy to understand. The third line begins a while loop; notice that it contains a condition, which could be true or false. This condition is checked before every execution of the loop block. If the condition ever becomes false, the instructions within the loop block do not execute.

As a rule of thumb, when you have something that you want to do for every element of an array, you use a foreach loop. When you have something that you want to keep doing until some condition is met, you use a while loop.

while loops can be tricky!

Consider what would happen if we wrote this code instead:

int targetNumber = 2314;
int n = 1;
while (n < targetNumber) {
}

The condition would never become false. Therefore, the loop would never end: the block would be executed forever (or until you force the program to stop, anyway). This is called an infinite loop.

Now consider what would happen if you wrote this code instead:

int targetNumber = 2314;
int n = 1;
while (n > targetNumber) {
   n = n * 2;
}

It’s almost the same as the original code – with one difference. Look carefully at the while loop condition. What would the value of n be at the end? It would always be 1, because the condition is never true – and because of that, the instructions within the loop block are never executed.

Exercises

For each piece of code, what is the value of i after the code is executed? If the loop never ends, write infinite loop.

var i = 31;
while (i < 3) {
   i = i + 1;
}

int i = 3;
while (i <= 3) {
   i = i + 1;
}

int i = 71;
while (true) {
   i = i - 1;
}

var i = 31;
while (i > 3) {
   i = i / 2;
}

int i = 0;
while (i < 10) {
   i = i + 1;
}

var i = 0;
while (i < 10) {
   i = i - 1;
}

There is something wrong with each of these pieces of code. For each piece of code, write a sentence describing what is wrong.

var i = 31;
while (i <== 3) {
   i = i + 1;
}


var i = 31;
while (i) {
   i = i + 1;
}


var i = 31;
while (var i < 3) {
   i = i + 1;
}