Presentation is loading. Please wait.

Presentation is loading. Please wait.

3. Controlling Program Flow Methods, parameters, and return values Boolean expressions Conditional branching Loops.

Similar presentations


Presentation on theme: "3. Controlling Program Flow Methods, parameters, and return values Boolean expressions Conditional branching Loops."— Presentation transcript:

1 3. Controlling Program Flow Methods, parameters, and return values Boolean expressions Conditional branching Loops

2 Methods, Parameters, and Return Values Methods are self-contained blocks of code that perform a given task. They constitute a form of unconditional branching - program control switches to another part of the program every time a method is invoked.

3 Methods, Parameters, and Return Values In C#, methods are declared in this format: public int AddTwoNumbers(int a, int b) { return a+b; } A and B are parameters, and are available within the method the same as other variables. The first line constitutes the method’s signature. Each method must have a unique signature within its context. The return statement returns program control to the calling code. Methods are evaluated like any other part of an expression: int Total = AddTwoNumbers(AddTwoNumbers(23, 44), 100);

4 Methods, Parameters, and Return Values Methods are also known as functions or subroutines. Method is the name usually used when a function is part of an object, as they are in C#. In some languages, a distinction is made between those functions that return no value, which are called procedures, and those that do, which are called functions. The three terms are very similar. In C#, a method that returns no value has a return type of void: public void DisplayMessage(string sMessage) { lblMessage.Text = sMessage; }

5 Methods, Parameters, and Return Values Methods usually perform a single, easily-identified task. Methods transfer control of the application into a separate block of code. Variables declared in a method are only visible within that method. The scope of a variable is the extent to which a variable is visible in different contexts. The variables declared within a method are said to be local.

6 Methods, Parameters, and Return Values Method parameters come in several different flavors. The most common is by value, which is the default in C# This means that the method has its own copy of a variable: int a = 1; MyMethod(a); MessageBox.Show(a.ToString()); public void MyMethod(int a) { a++; MessageBox.Show(a.ToString()); } In this case the program will display 2, then 1.

7 Methods, Parameters, and Return Values Parameters can also be passed by reference. This means that a reference to the variable is passed, allowing the function to change the value of the variable: int a = 1; MyMethod (ref a); MessageBox.Show(a.ToString()); public void MyMethod(ref int a); { a++; MessageBox.Show(a.ToString()); } In this case the program will display 2, then 2, because of the ref keyword in the method signature.

8 Methods, Parameters, and Return Values Methods can only have a single return value. Passing variables by reference allows methods to, in effect, return multiple values. The out keyword makes this explicit. Note there is no need to initialize out parameters. The out keyword guarantees that the variable will be initialized in the method with the out parameter(s). int a; MyFunction(out a); MessageBox.Show(a.ToString()); Public void MyMethod(out int a); { a = 1; } In this case the program will display 1, and the compiler will not complain that a is not initialized.

9 Methods, Parameters, and Return Values Methods can call themselves recursively. This often comes up when dealing with hierarchical data. public int MyRecursiveFunction(int a) { if (a < 10) return MyRecursiveFunction(a+1); else return a; } MessageBox.Show(MyRecursiveFunction(0).ToString()); This, for example, is a complicated way to count to 10.

10 Methods, Parameters, and Return Values Methods with the same name but different parameters (and thus a different signature) can be overloaded. This allows the same syntax to be used for different data types. For example: public double AddTwoNumbers(double a, double b); public int AddTwoNumbers(int a, int b); Allows us to use: AddTwoNumbers(1, 2); AddTwoNumbers(1.234, 2.234); Instead of having to use two different names for methods that do the same thing.

11 Conditional Branching Boolean variables can represent true or false. Boolean expressions are the foundation of conditional branching. The most common kind of conditional branching statement is if / then / else (in C#, “then” is implicit): if ([boolean expression]) { } else { }

12 Conditional Branching C# logical operators are AND (&&), OR (||), NOT (!) Usually used in conjunction with relational operators to construct boolean expressions. The relational operators are: Equals (==) Not equals (!=) Greater than (>) Greater than or equals (>=) Less than (<) Less than or equals (<=);

13 Conditional Branching Truth table for ! (unary NOT) operator: P!P TrueFalse True

14 Conditional Branching Truth table for && (AND) operator: PQP && Q TrueFalse True False TrueFalse

15 Conditional Branching Truth table for || (OR) operator: C# does not have a logical XOR (exclusive or) operator. PQP || Q TrueFalseTrue False True

16 If / Then Sample conditional statement: int x = 1; int y = 2; if ((((x+y) <= 5)||((x-y) < 0)) && (x == 0)) MessageBox.Show(“Expression is true”); else MessageBox.Show(“Expression is false”);

17 If / Then Complicated conditional statements are often best rewritten as methods so that the calling block of code is more readable: public bool IsTrue(int x, int y) { return ((((x+y) <= 50)||((x-y) < 0)) && (x == y-5)); } int x = 25; int y = 30; if (IsTrue(x, y)) MessageBox.Show(“Expression is true”); else MessageBox.Show(“Expression is false”);

18 If / Then Conditional expressions are evaluated left to right, and evaluation stops as soon as the result is available. This is called short-circuit evaluation: public bool MyFalseFunction() { MessageBox.Show(“I’m false”); return false; } public bool MyTrueFunction() { MessageBox.Show(“I’m true”); return true; } if (MyFalseFunction() && MyTrueFunction()) MessageBox.Show(“I’m false and true”); This program will display “I’m false” and exit.

19 If / Then If / then / else statements can also be nested: if (a < b) { a++; } else { a--; if (a > c) MessageBox.Show(a.ToString()); }

20 Switch Nested if / then / else statements can become complicated and hard to understand when there are many conditions. The switch statement is helpful in this situation: public double ConvertToFeet(double distance, int FromUnit) { double result = 0.0; switch(FromUnit) { case 0: result = distance; break; case 1: result = distance * 0.3048 ; break; default: MessageBox.Show("Invalid unit of measurement"); break; } return result; }

21 Switch The switch statement is often used in conjunction with constants, which can help explain the meaning of special numbers in the code: const int FEET = 0; const int METERS = 1; public double ConvertToFeet(double distance, int FromUnit) { double result = 0.0; switch(FromUnit) { case FEET: result = distance; break; case METERS: result = distance * 0.3048 ; break; default: MessageBox.Show("Invalid unit of measurement"); break; } return result; }

22 Switch Enumerations can be useful in switch statements, because they gather constants together, and make their meaning clearer: public enum UnitOfMeasurement { Feet = 0, Meters = 1 }; public double ConvertToFeet(double distance, UnitOfMeasurement FromUnit) { double result = 0.0; switch(FromUnit) { case UnitOfMeasurement.Feet: result = distance; break; case UnitOfMeasurement.Meters: result = distance * 0.3048 ; break; default: MessageBox.Show("Invalid unit of measurement"); break; } return result; }

23 Loops Looping is a powerful programming construct used to iterate over collections of items (more on this later). The WHILE loop has this structure: int i=0; while (i < 5 ) { MessageBox.Show(i.ToString()); i++; } This code displays the numbers 0 to 4. The FOR loop is shorthand for the same thing: for(int i=0; i<5; i++) MessageBox.Show(i.ToString());

24 Loops The DO loop is slightly different – it allows the body of the loop to execute once, regardless of whether or not the test expression is true. In this example, the code will display “500”, even though the while condition is false: int i=500; do { MessageBox.Show(i.ToString()); i++; } while (i < 5 );

25 Loops Continue stops processing within the current iteration of the loop, and goes on to the next. Break exits out of the loop. int i=0; while (true) { if (i<5) { MessageBox.Show(i.ToString()); i++; continue; } else { break; } MessageBox.Show(“This message will never be displayed.”); }


Download ppt "3. Controlling Program Flow Methods, parameters, and return values Boolean expressions Conditional branching Loops."

Similar presentations


Ads by Google