Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

34
Expressions, Conditionals and Looping CS 3260 Version 1.0

Transcript of Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

Page 1: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

Expressions, Conditionals and

Looping

Expressions, Conditionals and

Looping

CS 3260Version 1.0

CS 3260Version 1.0

Page 2: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

OverviewOverview

• Statements• Expressions• Operators• Selection (Conditionals)• Iteration (Loop)

• Statements• Expressions• Operators• Selection (Conditionals)• Iteration (Loop)

Page 3: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

C# Statement TypesC# Statement Types

Category C# keywords

Selection statements if, else, switch, case

Iteration statements do, for, foreach, in, while

Jump statements break, continue, default, goto, return, yield

Exception handling statements throw, try-catch, try-finally, try-catch-finally

checked and unchecked checked, unchecked

fixed statement fixed

lock statement lock

Page 4: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

StatementsStatements• Declaration

– Variable– Method

• Blocks { … }• Expression• Selection (Conditional)

– if/if-else/switch/?:

• Iteration (Loop)– while/do-while/for/foreach

• Declaration– Variable– Method

• Blocks { … }• Expression• Selection (Conditional)

– if/if-else/switch/?:

• Iteration (Loop)– while/do-while/for/foreach

Page 5: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

StatementsStatements• Statement Lists { … }• ; - Empty• <label>: <statement>;• Declaration - <type> <ident> = <init>;• Expression• Selection (Conditional)• Iteration (Loop)

• Statement Lists { … }• ; - Empty• <label>: <statement>;• Declaration - <type> <ident> = <init>;• Expression• Selection (Conditional)• Iteration (Loop)

Page 6: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

Jump StatementsJump Statements

• goto <label> - jump to label• break – switch/loops• continue - loops• return – no-value/value• throw – Exception object• yield – continue/break

• goto <label> - jump to label• break – switch/loops• continue - loops• return – no-value/value• throw – Exception object• yield – continue/break

Page 7: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

Exception Handling Statementschecked/unchecked Block

Exception Handling Statementschecked/unchecked Block

• try-catch-finally• checked/unchecked

• try-catch-finally• checked/unchecked

Page 8: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

try-catch-finallytry-catch-finally

• try: try-blockcatch(...) { //catch-block-1 }...catch(...) { //catch-block-n }

• try: try-block finally: finally-block

• try: try-blockcatch(...) { //catch-block-1 }...catch(...) { //catch-block-n }

• try: try-block finally: finally-block

Page 9: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

using Statementsusing Statements

• using <namespace>• using ( resource-acquisition )

embedded-statement

• using <namespace>• using ( resource-acquisition )

embedded-statement

Page 10: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

Other StatementsOther Statements

• lock • yield• fixed

• lock • yield• fixed

Page 11: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

lock Statementlock Statement

• lock ( expr ) embedded-statement• lock ( expr ) embedded-statement

Page 12: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

yield Statementyield Statement

• yield return expr ;• yield break;

• yield return expr ;• yield break;

Page 13: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

Statement ExampleLocal variable declaration static void () {

int a; int b = 2, c = 3; a = 1;Console.WriteLine(a + b + c);

}Local constant declaration static void () {

const float pi = 3.1415927f;const int r = 25;Console.WriteLine(pi * r * r);

}Expression statement static void () {

int i;i = 123;// Expression statementConsole.WriteLine(i); // Expression statementi++; // Expression statementConsole.WriteLine(i); // Expression statement

}if statement static void (string[] args) {

if (args.Length == 0) {Console.WriteLine("No arguments");

}else {

Console.WriteLine("One or more arguments");}

}

Page 14: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

switch statement static void (string[] args) {int n = args.Length;switch (n) {

case 0:Console.WriteLine("No arguments");break;

case 1:Console.WriteLine("One argument");break;

default:Console.WriteLine("{0} arguments", n);break;

}}

while statement static void (string[] args) {int i = 0;while (i < args.Length) {

Console.WriteLine(args[i]);i++;

}}

do statement static void () {string s;do {

s = Console.ReadLine();if (s != null) Console.WriteLine(s);

} while (s != null);}

for statement static void (string[] args) {for (int i = 0; i < args.Length; i++) {

Console.WriteLine(args[i]);}

}foreach statement static void (string[] args) {

foreach (string s in args) {Console.WriteLine(s);

}}

Page 15: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

break statement

static void () {while (true) {

string s = Console.ReadLine();if (s == null) break;Console.WriteLine(s);

}}

continue statement

static void (string[] args) {for (int i = 0; i < args.Length; i++) {

if (args[i].StartsWith("/")) continue;Console.WriteLine(args[i]);

}}

Page 16: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

goto statement static void (string[] args) {int i = 0;goto check;loop:Console.WriteLine(args[i++]);check:if (i < args.Length) goto loop;

}return statement static int Add(int a, int b) {

return a + b;}

static void () {Console.WriteLine(Add(1, 2));return;

}yield statement static IEnumerable<int> Range(int from, int to) {

for (int i = from; i < to; i++) {yield return i;

}yield break;

}

static void Main() {foreach (int x in Range(-10,10)) {

Console.WriteLine(x);}

}

Page 17: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

throw and trystatements

static double Divide(double x, double y) {if (y == 0) throw new DivideByZeroException();return x / y;

}

static void (string[] args) {try {

if (args.Length != 2) {throw new Exception("Two numbers

required");}double x = double.Parse(args[0]);double y = double.Parse(args[1]);Console.WriteLine(Divide(x, y));

}catch (Exception e) {

Console.WriteLine(e.Message);}finally {

Console.WriteLine(“Good bye!”);}

}

Page 18: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

checked and unchecked statements

static void () {int i = int.MaxValue;checked {Console.WriteLine(i + 1); // Exception}unchecked {Console.WriteLine(i + 1); // Overflow}

}

Page 19: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

lock statement class Account{

decimal balance;

public void Withdraw(decimal amount) { lock (this) { if (amount > balance) {

throw new Exception("Insufficient funds"); } balance -= amount; }}

}using statement static void () {

using (TextWriter w = File.CreateText("test.txt")) {w.WriteLine("Line one");w.WriteLine("Line two");w.WriteLine("Line three");

}}

Page 20: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

ExpressionsExpressions

• Primary• void• Arithmetic• Assignment

• Primary• void• Arithmetic• Assignment

Page 21: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

OperatorsOperators

• Operators• Precedence• Associativy

• Operators• Precedence• Associativy

Page 22: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

C# operators (categories in order of precedence)

Category Operator symbol Operator name Example User-overloadablePrimary ( ) Grouping while(x) No  . Member access x.y No  -> Pointer to struct (unsafe) x->y No  ( ) Function call x( ) No  [] Array/index a[x] Via indexer  ++ Post-increment x++ Yes  -- Post-decrement x-- Yes  new Create instance new Foo( ) No  stackalloc Unsafe stack allocation stackalloc(10) No  typeof Get type from identifier typeof(int) No  checked Integral overflow check on checked(x) No  unchecked Integral overflow check off unchecked(x) NoUnary sizeof Get size of struct sizeof(int) No  + Positive value of +x Yes  - Negative value of -x Yes  ! Not !x Yes  ~ Bitwise complement ~x Yes  ++ Pre-increment ++x Yes  -- Post-decrement --x Yes  ( ) Cast (int)x No  * Value at address (unsafe) *x No  & Address of value (unsafe) &x NoMultiplicative * Multiply x * y Yes  / Divide x / y Yes  % Remainder x % y YesAdditive + Add x + y Yes  - Subtract x - y Yes

Page 23: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

Shift << Shift left x >> 1 Yes  >> Shift right x << 1 YesRelational < Less than x < y Yes  > Greater than x > y Yes  <= Less than or equal to x <= y Yes  >= Greater than or equal to x >= y Yes  is Type is or is subclass of x is y No  as Type conversion x as y NoEquality == Equals x == y Yes  != Not equals x != y YesLogical And & And x & y YesLogical Xor ^ Exclusive Or x ^ y YesLogical Or | Or x | y YesConditional And && Conditional And x && y Via &Conditional Or || Conditional Or x || y Via |

Page 24: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

Null Coalescing

?? Null Coalescing x ?? y No

Conditional ?: Conditional isTrue ? thenThisValue : elseThisValue NoAssignment = Assign x = y No  *= Multiply self by x *= 2 Via *  /= Divide self by x /= 2 Via /  += Add to self x += 2 Via +  -= Subtract from self x -= 2 Via -  <<= Shift self left by x <<= 2 Via <<  >>= Shift self right by x >>= 2 Via >>  &= And self by x &= 2 Via &  ^= Exclusive-Or self by x ^= 2 Via ^  |= Or self by x |= 2 Via |Lambda => Lambda x => x + 1 No

Page 25: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

SuffixesSuffixes

real-type-suffix: one ofF f D d M m

Page 26: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

Selection - ConditionalSelection - Conditional• if (<boolean expression>) <statement>;• if(<boolean expression>) <statement>

else <statement>;• switch(<integer expression)

{ <statements> }• <datatype> <ident> = (<expression)?

<true_value>:<false_value>

• if (<boolean expression>) <statement>;• if(<boolean expression>) <statement>

else <statement>;• switch(<integer expression)

{ <statements> }• <datatype> <ident> = (<expression)?

<true_value>:<false_value>

Page 27: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

if - Selectionif - Selection

• if ( expr ) then-stmt else else-stmt• if ( expr ) then-stmt else else-stmt

Page 28: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

Iteration - LoopIteration - Loop• while(<bool expression>) <statement>;• do <statement> while(<bool expression);• for(<init statement>; <bool expr>; <change

statement>;) <statement>;• foreach(<type> <ident> <type> in <ident>)

<statement>;

• while(<bool expression>) <statement>;• do <statement> while(<bool expression);• for(<init statement>; <bool expr>; <change

statement>;) <statement>;• foreach(<type> <ident> <type> in <ident>)

<statement>;

Page 29: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

while - Loopwhile - Loop

• while-statement:while ( boolean-expression )

embedded-statement

• while-statement:while ( boolean-expression )

embedded-statement

Page 30: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

do loopdo loop

• do-body while ( expr ) ;• do-body while ( expr ) ;

Page 31: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

for - Loopfor - Loop

• for ( for-initializer ; for-condition ; for-iterator ) embedded-statement

• for ( for-initializer ; for-condition ; for-iterator ) embedded-statement

Page 32: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

foreach Loopforeach Loop

• foreach(<datatype> <ident> in <enumerable_collection>)

• <statement(s)>

• foreach(<datatype> <ident> in <enumerable_collection>)

• <statement(s)>

Page 33: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

throw - returnthrow - return

• throw expr ;• return expr ; or return ;

• throw expr ;• return expr ; or return ;

Page 34: Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.

Executable StatementsExecutable Statements• Methods• Properties• Events• Indexers• User-defined operators• Instance constructors• Static constructors• Destructors

• Methods• Properties• Events• Indexers• User-defined operators• Instance constructors• Static constructors• Destructors