Download •1 Outline Hello World in C# Vs Java Decision ... and more Slides Decision Making in PDF only on Docsity!
C# Programming Fundamentals: Control Flow
COMPSCI 280 S2 2016
Enterprise Software Development
Outline
COMPSCI 280
^2
Learn to use the C# language for controlling program flow ^
Decision-making statements:^
if, if-else, nested if-else, if-else-if, switch
^
Loops^
while, do-while, for,
^
Nested Loops
^
Others^
break, continue, goto
return, using
Hello World in C# Vs Java
Java
C# (Console application template)
C# Vs Java^
Main not main
Doesn’t need parameters to Main
Different methods for IO
COMPSCI 280
public class Hello {
public static void main(String[] args) {
System.out.println("Hello world.");
} public class Hello {
public static void Main() {
System.Console.WriteLine("Hello World.");
Decision-Making Statements
Decision-Making statements evaluate conditions and executestatements based on that evaluation
C# includes two decision-making statements:
If statement^
Evaluates an expression
Executes one or more statements if expression is true
Can execute another statement or group of statements if expression is false
Switch statement^
Evaluates a variable for multiple values
Executes a statement or group of statements, depending on contents of thevariable being evaluated
COMPSCI 280
Condition
Conditional
Code True
False
Flow chart of atypical decision
structure
if
& if-else
COMPSCI 280
The if statement
The block governed by it is executed if a condition is true
The Boolean_Expression must be enclosed in parentheses
The statement_when_true branch of an if can be a made up of a single statement or acompound statement^
Note:^
A compound statement is made up of a list of statements and must always be enclosed in a pair of braces ({ })
The If-else statement
It is two-way selection.
The else block is executed if the if part is false.
Again, the statements_when_true or statements_when_false can be a made of a singlestatement or many statements.
if (boolean_expression)
statement_when_true;
etc.
true
if
if (boolean_expression) {
statementS_when_true;... }
if (boolean_expression)
statement_when_true; else
statement_when_false;
if (boolean_expression){
statements_when_true;... } else {
statements_when_false;... }
etc.
true
false
if-else
Nested if-else
COMPSCI 280
Nested if-else^
If-else or if statement can be used as a subpart of another if-else or ifstatement.
The else clause matches the most recent if clause in the same block.
Nested statement can be tricky to code (or read)
Indentation can improve readability
To force the else clause to match the first if clause, you must add a pair ofbraces:
if (i > j)
if (i > k)
Console.WriteLine("A");
else
Console.WriteLine("B");
if (i > j)
if (i > k)
Console.WriteLine("A"); else
Console.WriteLine("B");
Incorrect indentation
if (i > j) {
if (i > k)
Console.WriteLine("A");
} else
Console.WriteLine("B");
Note: Ctrl+K, Ctrl+F appliesautoformatting according tothe settings in Tools/Optionsfor the Text Editor settings ofC#’s Formatting pane
Multiway if-else
COMPSCI 280
The multiway if-else statement is simply a normal if-else statement that nestsanother if-else statement at every else branch
The Boolean_Expressions are evaluated in order until one that evaluates totrue is found. If none of them are true then the else block is executed.
The final else is optional
Note:
It is indented differently from other nested statements.
All of the
if (Boolean_Expression) Boolean_Expressions are aligned with one another.
Statement_1;
else if (Boolean_Expression)
Statement_2;
else if (Boolean_Expression_n)
Statement_n;
else
Statement;
if (Boolean_Expression) {
Statements_1;... } else if (Boolean_Expression) {
Statements_n;... } else {
Statements;... }
Switch
COMPSCI 280
Switch^
Acts like a multiple-way if statement
^
Transfers control to one of several statements, depending on the value of an expression
^
No two case statements can have the same value.
^
Value must be an integer or a string
^
Execution of the statement body begins at the selected statement and proceeds until the break
statement transfers control out of the case body
^
Implicit fall through from one case to another if a case statement has no code.
^
The default statement is optional
C
1 C 2 C 3
Statement(s)
1
True
Statement(s)
2
True
Statement(s)
3
True
False False False
switch (n) {
case value1:
statement1;break; case value2:case value3:
statement2;break;
...
default:
statementn;break;
if (Boolean_Expression)
Statement_1; else if (Boolean_Expression_n)
Statement_n; else
Statement;
Implicit fall
through
Counters
COMPSCI 280
Variables called
counters
are frequently used to control loops
Counters are initialized before the loop begins (can be just at the beginning with the for loop)
They are also usually modified within the body of the loop
The counter in the body of the loop must eventually make the test expression false^
Otherwise, the loop will continuously loop forever - called an infinite loop (case 5)
If you declare the control variable in the for loop, the scope of that variable will only be insidethe loop block (case 4)
When to use…
while^
Use the while loop when you wish the loop to repeat as long as the test expression is true (case 1 & 2)
for^
The for loop is primarily used when the number of required iterations is known (case 4)
The post-test loop (do-while) is ideal when you want the loop to always iterate at least once(case 3 v case 2)
//case 1int i = 1;while (i < 3) {
i = i + 1; }
//case 2int i = 20;while (i < 3) {
i = i + 1; }
//case 3int i = 20;do {
i = i + 1; } while (i < 3);
//case 4for (int i = 1; i < 3; i++) System.Console.WriteLine(
" i=
//case 5int i = 1;while (i < 3) {} +i);
Infinite loop!
Nested Loops
Loop can be nested^
When nested, the inner loop iterates from beginning to theend for each single iteration of the outer loop
^
There is no limit in how many levels you can nest loops. It isusually not more than three levels.
Examples^
Multiplication table^
row =3, col = 4
COMPSCI 280
for( int i = 1; i <= row; i ++) { 14
for (int j = 1; j <= col; j++) {
Console.Write( (i * j)
*+i j : "
" + i * j);
}Console.WriteLine();
// Print blank line
for( int i = 0; i < row; i ++) {
for (int j = 0; j < row; j++) {
Console.Write(""); }Console.WriteLine();*
for( int i = 0; i < row; i ++) {
for (int j = 0; j <= i; j++) {
Console.Write(""); }Console.WriteLine();*
3 spaces if <10 else 2
break & continue
COMPSCI 280
The break statement terminates the closest enclosing loop or switch statement in which it 15
appears.
Control is passed to the statement that follows the terminated loop (or switch), if any.
The continue statement passes control to the next iteration of the enclosing iterationstatement in which it appears.
It must be enclosed by a while, do, for, or foreach statement
It applies only to the innermost statement in nested iteration statements
for( int i = 0; i < row; i ++) {
for (int j = 0; j < row; j++) {
if ( i+j >= row )
break; Console.Write("");*
}Console.WriteLine(); }
i = 1i = 3
for (int i= 1; i <= row; i++ ) {
if( i % 2 == 0)
continue;
// Go back to for
Console.WriteLine("i = " +
i );
For row=
goto
COMPSCI 280
The goto statement transfers the program control directly to alabeled statement.^
Used in a switch statement
Get out of deeply nested loops
switch (x) {case 1:
Console.WriteLine("Case 1");goto case 2; case 2:
Console.WriteLine("Case 2");break; }
Case 1Case 2
int[,] array = { { 1, 2, 3 }, { 4, 5, 6 } };for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
if (array[i, j]==x)
goto Found;
Console.WriteLine("The number {0} was not found.", x);goto Finish;Found:
Console.WriteLine("The number {0} is found.", x); Finish:
Console.WriteLine("End of search.");
Output for int x=
Each set of cases has to
have a break or goto Note parameter output
formatting
return & using
return
The return statement terminates execution of the method in which itappears and returns control to the calling method.^
It can also return a value (in keeping with the type of the method it’s in).
If the method is a void type, the return statement at the end can be omitted.
using
Defines a scope, outside of which an object or objects will be disposed of.^
It is usually best to release limited resources such as file handles and networkconnections as quickly as possible.
i^
Loop test
outcome
1
1<=
Prints i=
2
2<=
Returns
COMPSCI 280
public static void returnMethod(int row) {
for (int i = 1; i <= row; i++) {
if (i % 2 == 0)
return; Console.WriteLine("i = " + i); } }
using (Font font1 = new Font("Arial", 10.0f)) {}
using directive
COMPSCI 280
The using directive has two uses:^
You can reference types in the library without fully qualifying the type name
To create an alias for a namespace.
using System;namespace B {
public class Program1 {
static void Main(string[] args){
Console.WriteLine("Hello"); } } }
namespace B {
public class Program2 {
static void Main(string[] args){
System.Console.WriteLine("Hello"); } } }
using C = System.Console;namespace B {
public class Program3 {
static void Main(string[] args){
C.WriteLine("Hello"); } } }
With usingdirective
using alias
Fully qualifying
Conclusion
We’ve learned some ways to control program flow in C#
And in the journey seen some other aspects of the language,too
Next time – we’ll focus on some of the interesting data typesin C#
Handout 02
COMPSCI 280