VARIABLES AND NESTED STATEMENTS - Home -...

22
GHI Electronics, LLC - Where Hardware Meets Software C# VARIABLES AND NESTED STATEMENTS

Transcript of VARIABLES AND NESTED STATEMENTS - Home -...

Page 1: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

GHI Electronics, LLC - Where Hardware Meets Software

C#

VARIABLES AND NESTED STATEMENTS

Page 2: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 1 of 21

Contents

Introduction ......................................................................................................................... 2

Overview .......................................................................................................................... 2

Guidelines ......................................................................................................................... 2

Arguments ........................................................................................................................... 3

Exercise ............................................................................................................................. 3

Integer Variables .................................................................................................................. 4

Changing Tones ................................................................................................................ 6

The if-statement with Variables ....................................................................................... 7

Exercise ............................................................................................................................. 7

Inspecting Variables ............................................................................................................. 8

Exercise ............................................................................................................................. 9

Double Variable ................................................................................................................. 10

Returned Values ............................................................................................................. 12

Exercise ........................................................................................................................... 12

Strings ................................................................................................................................ 13

ToString() ........................................................................................................................ 14

Exercise ........................................................................................................................... 15

Finite while loops ............................................................................................................... 16

Exercise ........................................................................................................................... 18

Nesting ............................................................................................................................... 19

Exercise ........................................................................................................................... 20

Page 3: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 2 of 21

Introduction

The BrainPad circuit board is designed as a powerful educational tool that can be used

to teach everyone from kids, to college students and professionals. Kids will start to

learn programming using Visual Studio, one of the most widely used professional tools.

College students and professionals that already know programming can use the

BrainPad circuit board to learn about digital electronics and the connection between

computing and the physical world.

Overview

Students will learn about variables, strings, while loops and nested statements.

Guidelines

Prerequisites: CS101

Ages 12 and up

PC setup with Visual Studio, .NET Micro Framework and GHI Electronics’

software.

Supplies: BrainPad

Page 4: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 3 of 21

Arguments

Arguments are values passed to methods. The following examples list the different ways

arguments can be used.

BrainPad.Buzzer.PlayFrequency(3000);

Example 1 – To play a sound with the buzzer, we pass an argument of 3,000 that represents

the frequency to use.

BrainPad.Wait.Seconds(0.2);

Example 2 – Here we tell the program to wait for 0.2 seconds before continuing execution.

BrainPad.Button.IsPressed(BrainPad.Button.DPad.Down)

Example 3 – The argument here uses an enumeration. The DPad.Down enumerator contains

named values that represent buttons. This allows us to easily identify things by a descriptive

name rather than using numbers. In this case we check if the Down button on the directional

pad is pressed.

Exercise

Use the wrong argument types and build the project to observe the error messages.

Page 5: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 4 of 21

Integer Variables

A variable is a location in memory that is reserved for us to use. Instead having to know

where the memory is, the system gives us access to that memory using a name we

choose as shown in Example 4.

int count;

Example 4 – Use we create an integer named count in the system memory.

The above line instructs the system to reserve a variable that is named count and the

variable type is an Integer, or int when coding.

A variable name can use any letters and numbers but it cannot start with a number or

contain spaces. Using the underscore symbol is allowed.

The following are examples of valid and invalid names.

int count123; int count_me_in; int count2var;

Example 5 – These are variable names that are valid.

int count me; int count#; int 2count;

Example 6 – These variable names are invalid.

Variables in small programs can use any names. It could even be just “x”. However,

using a meaningful name is very important when writing programs, as there maybe

hundreds of variables in a large program.

Page 6: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 5 of 21

Variables can be used to store numbers as shown in Example 7.

int count; count = 10; … count = 123;

Example 7 – This variable is storing an integer.

Example 8 shows math can be used as well.

count = 5 + result;

Example 8 – This shows a variable storing the result of an equation.

Note that the variable can be used in the equation (Figure 9) as well.

count = count + 2;

Example 9 – Variables can also store values from equations that contain themselves.

The above code will add 2 to the current value of count.

After selecting an appropriate name, an appropriate type is needed. The type tells the

system how much memory to reserve for that one variable. The most widely used

variable is an Integer, which is 4 bytes and can hold large numbers and negative

numbers. For now, we suggest using Integers for everything, except when fractions are

needed (more on that later).

Page 7: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 6 of 21

Changing Tones

We will start a new project and name it “BrainPad_Project” then use the code shown in

Example 10.

public class Program { int frequency; int increment; public void BrainPadSetup() { frequency = 0; increment = 0; } public void BrainPadLoop() { if (BrainPad.Button.IsUpPressed()) { increment = 100; } if (BrainPad.Button.IsDownPressed()) { increment = -100; } if (increment != 0) { frequency = frequency + increment; increment = 0; BrainPad.Buzzer.PlayFrequency(frequency); BrainPad.WriteDebugMessage(frequency); BrainPad.Wait.Seconds(0.2); BrainPad.Buzzer.Stop(); } } }

Example 10 – This code uses the variables frequency and increment to control the frequency of

the pitch made by the buzzer. The frequency increases when up is pressed and decreases

when down is pressed. Each press plays the new frequency for one-fifth of a second.

As we use the up and down buttons to change the frequency, the value held by the

frequency variable is printed in the Output Window. Using Example 10, can we determine

the highest frequency a person can hear?

Page 8: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 7 of 21

The if-statement with Variables

The same way the if statement was used to check if a button was pressed, it can be

used with variables. If the frequency is larger than 6,000 turn the red light on, otherwise

turn it off. Add the code shown in Example 11 to the while loop in Example 10, right

above the BrainPad.Wait.Seconds(0.2) line.

if (frequency > 6000) { BrainPad.TrafficLight.TurnRedLightOn(); } else { BrainPad.TrafficLight.TurnRedLightOff(); }

Example 11 – This code turns the red light on if the frequency is greater than 6,000, otherwise

it turns it off.

Pressing the up button will increase the frequency. Once the frequency is greater than

6,000 the red light will turn on.

Exercise

Add a variable that starts at 0 and increments by 1 every loop. Once the variable

reaches 1,000 turn the yellow light on. Print the variable value in the Output Window to

make sure it’s incrementing. Verify the yellow light comes on when the variable goes

over 1,000.

Page 9: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 8 of 21

Inspecting Variables

Printing the variable value worked well for small programs with a single variable. It is

not practical to continuously print every variable out when it comes to larger programs.

Instead, we can use the debugger feature to pause the code and inspect variables.

public class Program { int count; public void BrainPadSetup() { count = 0; } public void BrainPadLoop() { count = count + 1; BrainPad.WriteDebugMessage(count); BrainPad.Wait.Seconds(0.2); } }

Example 12 – This code loops indefinitely, incrementing the count by one each loop and

printing its value in the Output Window.

Add a breakpoint to the loop in Example 12 and step through the code. Move the mouse

over the count variable and wait a second. A pop up window will come up showing the

value of the count variable as shown in Figure 1.

Figure 1 – Adding a breakpoint and placing your cursor over a variable will pop up a window

showing its value.

The Watch Window can also be used with important variables that need to be inspected

regularly. Locate the Watch Window and type the variable name in the left cell. This will

show the variable value and type.

Page 10: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 9 of 21

Figure 2 – In the Watch Window we can add variables like count to see their value and type

as the program runs.

Exercise

Run Example 12 for a few loops, then pause the program, or add a breakpoint. Inspect

the value on the Watch Window. It should be above zero. Change the value manually to

zero and then re-run the program and observe how the Output Window shows the

variable going back to counting from zero.

Page 11: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 10 of 21

Double Variable

While an Integer can hold large numbers, it can’t hold fractions. For example, there is no

way to set an integer to 0.5 or 123.8. The variable type double should be used whenever

fractions are needed. If a double can hold large numbers and fractions, why not just use

it for everything? You certainly can but double type variables require more memory and

processing. Fractions are not always desirable in the programming world as shown in

Example 13.

public class Program { double frequency; int increment; public void BrainPadSetup() { frequency = 0; increment = 0; } public void BrainPadLoop() { if (BrainPad.Button.IsUpPressed()) { increment = 100; } if (BrainPad.Button.IsDownPressed()) { increment = -100; } if (increment != 0) { frequency = frequency + increment; increment = 0; BrainPad.Buzzer.PlayFrequency((int)frequency); BrainPad.WriteDebugMessage(frequency); BrainPad.Wait.Seconds(0.2); BrainPad.Buzzer.Stop(); } } }

Example 13 – This code shows how a double isn’t always the best variable type choice. Instead

of simply passing an integer into PlayFrequency we have to cast it as an integer first. This is

done by placing (int) before the variable, which requires additional un-needed processing.

Page 12: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 11 of 21

Time to go back to our favorite green light! In Example 14, we will turn the green light

on and off for a specified amount of time, set by a variable called delay. The up and

down buttons control the delay variable, causing the light to be on and off longer or

shorter. The variable is also printed out using WriteDebugMessage(delay).

public class Program { double delay; public void BrainPadSetup() { delay = 0.20; } public void BrainPadLoop() { if (BrainPad.Button.IsPressed(BrainPad.Button.DPad.Up)) { delay = delay + 0.10; } if (BrainPad.Button.IsPressed(BrainPad.Button.DPad.Down)) { delay = delay - 0.10; if (delay < 0) delay = 0; } BrainPad.WriteDebugMessage(delay); BrainPad.TrafficLight.TurnGreenLightOn(); BrainPad.Wait.Seconds(delay); BrainPad.TrafficLight.TurnGreenLightOff(); BrainPad.Wait.Seconds(delay); } }

Example 14 – This code flashes the green light on and off. A variable named delay controls

how long the green light stays on and off.

Page 13: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 12 of 21

Returned Values

Some methods return a value, like when reading the light sensor. This value can be

placed into a variable and this variable can be used with if statements. We have

lightbulb and light sensor on the BrainPad. Let’s turn the light on when it’s dark as

shown in Example 15.

public class Program { double level; public void BrainPadSetup() { level = 0; } public void BrainPadLoop() { level = BrainPad.LightSensor.ReadLightLevel(); BrainPad.WriteDebugMessage(level); if (level < 0.5) { BrainPad.LightBulb.TurnOn(); } else { BrainPad.LightBulb.TurnOff(); } } }

Example 15 – When the level of light drops below 0.5 we turn the lightbulb on.

How can we determine what threshold to use to turn the lightbulb on? This is a perfect

example of when inspecting variables is needed. Run the program and test it by placing

a finger over the light sensor to block the light. You may need to adjust the threshold

from 0.5 to something else. Take a look at the Output Window to see the light levels to

determine what value works best for you.

Exercise

Modify Example 15 so the up button sets the threshold.

Hint: The threshold was a constant before but now it is going to be a variable that is set

to whatever the light sensor returns when the button is pressed. Name the variable

threshold and make sure it’s a double.

Page 14: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 13 of 21

Strings

A string is a type of variable that holds text as shown in Example 16.

BrainPad.WriteDebugMessage("Hello World!");

Example 16 – The text "Hello World!" is considered a string.

It’s important to remember that the value 2 and the string "2" are not the same thing.

They may be the same to us but internally in the system they are very different.

x = 2 + 2;

Example 17 – When x is an integer, adding 2 + 2 means x equals 4 as you would expect.

Let’s assume str is a string variable (Example 18), what is the value of str?

str = "2" + "2";

Example 18 – The plus sign symbol means something different when dealing with strings.

Using the plus sign to connect strings is called concatenation. Which means a series of

interconnected things.

When concatenating strings in Example 18, the result is "22". This will make more sense

if you try Example 19.

str = "Hello number " + "2";

Example 19

The result is "Hello number 2". Note how even a space makes a difference.

Page 15: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 14 of 21

ToString()

One of the important built-in methods for variables is the ToString() method. This

method will take the value from count and convert it to a string as shown in Example 20.

public class Program { double count; public void BrainPadSetup() { count = 0; } public void BrainPadLoop() { count = count + 1; BrainPad.WriteDebugMessage("Count: " + count.ToString()); } }

Example 20 – Cotinousely increase te count and display it as a string.

Example 20 uses an integer that starts at zero and increments by one in every loop. It

also prints the variable’s value in the Output Window (Figure 3). The text "Count: " is

concatenated before the value to give us these results.

Figure 3 – The Output Window shows the program from Example 20 counting up.

Page 16: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 15 of 21

C# is smart when it comes to concatenation. Try changing line 16 from count.ToString()

to just count. C# knows to automatically call the ToString() method internally as shown in

Example 21.

BrainPad.WriteDebugMessage("Count: " + count);

Example 21 – Concatenating numbers and other objects with strings will automatically call

the ToString() method.

Exercise

Show something like this (Figure 4) in the Output Window.

Figure 4 – Here we see the light sensor’s level printed in the Output Window.

Page 17: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 16 of 21

Finite while loops

Loops have been used extensively in every example. The while loop was always looping

infinitely using BrainPad.Looping. This was used to simplify things but BrainPad.Looping is

just a true value internally. In other words, the while loop will run while something is

true and since we have passed it the value true then it will loop forever.

Is the statement in Example 22 true?

1 = 1

Example 22 – This statement asks if 1 equals 1 and the answer is yes, so it’s true.

Now we can make a while loop, loop forever using this statement (Example 23).

public class Program { public void BrainPadSetup() { int count = 0; while (1 == 1) { count = count + 1; BrainPad.WriteDebugMessage("Count: " + count); BrainPad.Wait.Seconds(0.2); } } public void BrainPadLoop() { // Declared but not used } }

Example 23 – Here we use the statement 1 == 1 to keep the while loop running forever.

It should be noted clearly that we used == and not = in the while statement. The single =

is used to set a value (Example 24), not compare them (Example 25).

int count = 10;

Example 24 – This code sets count to 10.

Page 18: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 17 of 21

if (count == 10)

Example 25 – This code compares count with 10 to see if it’s equal.

The Boolean type true can be used as well as shown in Example 26.

public class Program { public void BrainPadSetup() { int count = 0; while (true) { count = count + 1; BrainPad.WriteDebugMessage("Count: " + count); BrainPad.Wait.Seconds(0.2); } } public void BrainPadLoop() { // Declared but not used } }

Example 26 – This code uses true in the while loop statement to keep it running forever.

A while loop can also be finite (Example 27), meaning it will stop looping at some point.

public class Program { public void BrainPadSetup() { int count = 0; while (count < 10) { count = count + 1; BrainPad.WriteDebugMessage("Count: " + count); BrainPad.Wait.Seconds(0.2); } } public void BrainPadLoop() { // Declared but not used } }

Page 19: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 18 of 21

Example 27 – This code will count up to 10 before the while loop stops.

What did Example 27 do? It printed the count from one to 10. However, the count

started at zero, not one. Shouldn’t it print count zero? Looks like it’s time to start

debugging. Start by setting a breakpoint at count = 0 and then step in the code to see

what the value of count is (use Watch Window) and then see why the value zero was

never printed. Think about a fix before looking at the next example.

The fix is easy as shown in Example 28.

public class Program { public void BrainPadSetup() { int count = 0; while (count < 10) { BrainPad.WriteDebugMessage("Count: " + count); count = count + 1; BrainPad.Wait.Seconds(0.2); } } public void BrainPadLoop() { // Declared but not used } }

Example 28 – This code counts, printing zero to nine in the Output Window.

What about the 10? Shouldn’t the program print “Count: 10”? The answer is in the while

loop. In plain English, it says: run the following code as long as count is less than 10.

Since 10 is not less than 10, then 10 will not be printed. The while loop can be easily

modified so 10 is printed too (Example 29).

while (count <= 10)

Example 29 – This statement checks if count is less than or equal to 10.

Exercise

Write a program that prints all even numbers between six and 66.

Page 20: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 19 of 21

Nesting

Any reasonably sized program will have loops inside loops, or if statements inside

loops, maybe even inside other if statements and loops! This is called nesting. While

programmers should try to keep this simple to understand, nesting is sometimes

required.

How do we write a program that prints one to 10 repeatedly forever? This is

accomplished by having two nested while loops. One that counts one to 10, which goes

inside another loop that loops indefinitely as shown in Example 30.

public class Program { public void BrainPadSetup() { int count = 0; while (true) { while (count <= 10) { BrainPad.WriteDebugMessage("Count: " + count); count = count + 1; BrainPad.Wait.Seconds(0.2); } } } public void BrainPadLoop() { // Declared but not used } }

Example 30 – This code prints one to 10 once while looping forever.

The above program will not work. It will print one to 10 once. Then the program will not

end and it will not print anything after. Time to debug the code to determine what the

issue is. Run the program and determine the cause of the error. The fix is simple but try

to find it before peeking at the fixed code in Example 31.

Page 21: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 20 of 21

public class Program { public void BrainPadSetup() { int count; while (true) { count = 0; while (count <= 10) { BrainPad.WriteDebugMessage("Count: " + count); count = count + 1; BrainPad.Wait.Seconds(0.2); } } } public void BrainPadLoop() { // Declared but not used } }

Example 31 – This code prints one to 10 forever.

Exercise

Write a program that prints zero to 10 repeatedly when the light level is high and the up

button is not pressed. If it is dark then the button doesn’t do anything.

Do not use &&, instead nest with if statements.

Page 22: VARIABLES AND NESTED STATEMENTS - Home - …old.ghielectronics.com/downloads/BrainPad/BrainPad_CS...BrainPad – C# – Variables and Nested Statements Page 1 of 21 Contents Introduction

BrainPad – C# – Variables and Nested Statements

Page 21 of 21

GHIElectronics.com/support/brainpad