Expressions, Conditionals and Looping CS 3260 Version 1.0 CS 3260 Version 1.0.
-
Upload
job-phelps -
Category
Documents
-
view
235 -
download
1
Transcript of 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
OverviewOverview
• Statements• Expressions• Operators• Selection (Conditionals)• Iteration (Loop)
• Statements• Expressions• Operators• Selection (Conditionals)• Iteration (Loop)
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
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
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)
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
Exception Handling Statementschecked/unchecked Block
Exception Handling Statementschecked/unchecked Block
• try-catch-finally• checked/unchecked
• try-catch-finally• checked/unchecked
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
using Statementsusing Statements
• using <namespace>• using ( resource-acquisition )
embedded-statement
• using <namespace>• using ( resource-acquisition )
embedded-statement
Other StatementsOther Statements
• lock • yield• fixed
• lock • yield• fixed
lock Statementlock Statement
• lock ( expr ) embedded-statement• lock ( expr ) embedded-statement
yield Statementyield Statement
• yield return expr ;• yield break;
• yield return expr ;• yield break;
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");}
}
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);
}}
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]);
}}
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);}
}
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!”);}
}
checked and unchecked statements
static void () {int i = int.MaxValue;checked {Console.WriteLine(i + 1); // Exception}unchecked {Console.WriteLine(i + 1); // Overflow}
}
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");
}}
ExpressionsExpressions
• Primary• void• Arithmetic• Assignment
• Primary• void• Arithmetic• Assignment
OperatorsOperators
• Operators• Precedence• Associativy
• Operators• Precedence• Associativy
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
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 |
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
SuffixesSuffixes
real-type-suffix: one ofF f D d M m
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>
if - Selectionif - Selection
• if ( expr ) then-stmt else else-stmt• if ( expr ) then-stmt else else-stmt
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>;
while - Loopwhile - Loop
• while-statement:while ( boolean-expression )
embedded-statement
• while-statement:while ( boolean-expression )
embedded-statement
do loopdo loop
• do-body while ( expr ) ;• do-body while ( expr ) ;
for - Loopfor - Loop
• for ( for-initializer ; for-condition ; for-iterator ) embedded-statement
• for ( for-initializer ; for-condition ; for-iterator ) embedded-statement
foreach Loopforeach Loop
• foreach(<datatype> <ident> in <enumerable_collection>)
• <statement(s)>
• foreach(<datatype> <ident> in <enumerable_collection>)
• <statement(s)>
throw - returnthrow - return
• throw expr ;• return expr ; or return ;
• throw expr ;• return expr ; or return ;
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