lecture 3

31
Control Statements (1) Dr. Hakem Beitollahi Computer Engineering Department Soran University Lecture 3

Upload: soran-university

Post on 29-Jun-2015

30 views

Category:

Engineering


0 download

DESCRIPTION

OOP with C# by Dr.hakim

TRANSCRIPT

Page 1: Lecture 3

Control Statements (1)

Dr. Hakem Beitollahi

Computer Engineering DepartmentSoran University

Lecture 3

Page 2: Lecture 3

Objectives of this lecture

In this chapter you will learn: Algorithms Pseudocode Control Structures

if Selection Structure

if/else Selection Structure switch statement List of keywords in C#

Control Statements— 2

Page 3: Lecture 3

Algorithms Any computing problem can be solved by

executing a series of actions in a specific order. Two important items:

The actions to be executed and The order in which these actions are to be executed.

Example: rise-and-shine algorithm One junior executive for getting out of bed and going to

work1. get out of bed

2. take off pajamas

3. take a shower

4. get dressed

5. eat breakfast

6. carpool to work

Control Statements— 3

Page 4: Lecture 3

Pseudocode Pseudocode is an artificial and informal

language that helps programmers develop algorithms.

Pseudocode is similar to everyday English; it is convenient and user-friendly

it is not an actual computer programming language

Pseudocode is not executed on computers. pseudocode helps the programmer “think out” a

program before attempting to write it in a programming language

Control Statements— 4

Page 5: Lecture 3

Control Statements

Control Statements— 5

Page 6: Lecture 3

Control Statements Three control structures

Sequence structureo Programs executed sequentially by default

Selection structureso if, if…else, switch

Repetition structureso while, do…while, for

Control Statements— 6

Page 7: Lecture 3

if Selection Statement (I)

Selection statements Choose among alternative courses of action Pseudocode example

o If (student’s grade is greater than or equal to 60)Print “Passed” If the condition is true

Print statement executes, program continues to next statement

If the condition is false Print statement ignored, program continues

Indenting makes programs easier to read C# ignores white-space characters

7/31

Page 8: Lecture 3

if Selection Statement (II)

Example: if ( grade >= 60 )

Console.WriteLine("Passed“);

grade >= 60

False

True

Console.WriteLine (“passed”

8/31

Page 9: Lecture 3

Good Programming Practice 1

Indent both body statements of an if/else structure.

Control Statements— 9

Page 10: Lecture 3

if…else Double-Selection Statement (I)

if Performs action if condition true

if…else Performs one action if condition is true, a different action if it is

false C# code

if ( grade >= 60 ) Console.WriteLine("Passed“);else Console.WriteLine("Failed“);

10/31

Page 11: Lecture 3

if…else Double-Selection Statement (II)

If-else flowchart

Expression

Action1 Action2

true false

11/31

Page 12: Lecture 3

if…else Double-Selection Statement (III)

Ternary conditional operator (?:) Three arguments (condition, value if true,

value if false)Code could be written:

Console.WriteLine(studentGrade >= 60 ? "Passed" : "Failed");

Condition

If(studentGrade >= 60)

Value if true

Console.writeline(“passed”)

Value if false

Console.writeline(“faild”)

12/31

Page 13: Lecture 3

If…else (example)// Control Statement example via random generationusing System;class Conditional_logical {  static void Main( string[] args ) { int magic; /* magic number */ string guess_str; /* user's guess string*/ int guess; /* user's guess */  Random randomObject = new Random(); magic = randomObject.Next(100); //this code generates a magic number between 0 to 100 */  Console.Write("Guess the magic number: "); guess_str = Console.ReadLine(); guess = Int32.Parse(guess_str);  Console.WriteLine("Computer's guess is: " + magic);  if (guess == magic) Console.WriteLine("** Right **"); else Console.WriteLine("** Wrong **"); }// end method Main} // end class

13/31

Define a randomObject

Next method: generate a random number between 0 to 100

if-else statement

Page 14: Lecture 3

if…else Double-Selection Statement (IV)

Nested if…else statements One inside another, test for multiple cases Once a condition met, other statements are skipped

Exampleo if ( Grade >= 90 ) Console.Write(“A“);else if (Grade >= 80 ) Console.Write("B“); else if (Grade >= 70 ) Console.Write("C“); else if ( Grade >= 60 ) Console.Write("D“); else Console.Write("F“);

14/31

Page 15: Lecture 3

if…else Double-Selection Statement (V)

Previous example can be written as follows as well

15/31

if (Grade >= 90) Console.WriteLine("A"); else if (Grade >= 80) Console.WriteLine("B"); else if (Grade >= 70) Console.WriteLine("C"); else if (Grade >= 60) Console.WriteLine("D"); else Console.WriteLine("F");

Page 16: Lecture 3

Good Programming Practice 2A nested if...else statement can perform much faster than a series of single-selection if statements because of the possibility of early exit after one of the conditions is satisfied.

In a nested if... else statement, test the conditions that are more likely to be true at the beginning of the nested if...else statement. This will enable the nested if...else statement to run faster and exit earlier than testing infrequently occurring cases first.

16/31

Page 17: Lecture 3

if…else double-selection statement (VI)

Dangling-else problem Compiler associates else with the immediately

preceding if Example

o if ( x > 5 ) if ( y > 5 ) Console.WriteLine("x and y are > 5“);else Console.WriteLine("x is <= 5“);

Compiler interprets aso if ( x > 5 ) if ( y > 5 ) Console.WriteLine("x and y are > 5“); else Console.WriteLine("x is <= 5“);

17/31

Page 18: Lecture 3

if…else double-selection statement (VII)

Dangling-else problem (Cont.) Rewrite with braces ({})

o if ( x > 5 ){ if ( y > 5 ) Console.WriteLine ("x and y are > 5“);}else Console.WriteLine ("x is <= 5“);

Braces indicate that the second if statement is in the body of the first and the else is associated with the first if statement

18/31

Page 19: Lecture 3

if…else double-selection statement (VIII)

Compound statement Also called a block

o Set of statements within a pair of braceso Used to include multiple statements in an if

body Example

o if ( Grade >= 60 ) Console.WriteLine ("Passed.“);else { Console.WriteLine ("Failed.“); Console.WriteLine ("You must take this course again.“);}

Without braces, Console.WriteLine ("You must take this course again.)";

always executes

19/31

Page 20: Lecture 3

Good Programming Practice 3

Always putting the braces in an if...else statement (or any control statement) helps prevent their accidental omission, especially when adding statements to an if or else clause at a later time. To avoid omitting one or both of the braces, some programmers prefer to type the beginning and ending braces of blocks even before typing the individual statements within the braces.

Control Statements— 20

Page 21: Lecture 3

Switch Statement

Control Statements— 21

Page 22: Lecture 3

Switch statement (I) C/C++/C# has a built-in multiple-branch selection statement, called

switch, which successively tests the value of an expression against a list of integer or character constants.

When a match is found, the statements associated with that constant are executed

The general form of the switch statement isswitch (expression) { case constant1: statement sequence break; case constant2: statement sequence break; case constant3: statement sequence break; default statement sequence break;} 22/31

Page 23: Lecture 3

Switch statement (II) The expression must evaluate to a character or integer

value Floating-point expressions, for example, are not

allowed. When a match is found, the statement sequence

associated with that case is executed until the break statement or the end of the switch statement is reached

The default statement is executed if no matches are found.

The default is optional and, if it is not present, no action takes place if all matches fail.

23/31

Page 24: Lecture 3

Switch statement (III)

// switch statement exampleusing System; class Conditional_logical {  static void Main( string[] args ) { int num; Console.Write("Enter a number between 0 to 4: "); num = Int32.Parse(Console.ReadLine());  switch(num) { case 1: Console.WriteLine("You enterd number 1"); break; case 2: Console.WriteLine("You entered number 2"); break; case 3: Console.WriteLine("You enterd number 3"); break; default: Console.WriteLine("Either your number is less than 1 or bigger than 3"); break; }  }// end method Main} // end class

24/31

Prompt user

Read user’s number and convert it to int

Switch based on num

You must have break after each case

Page 25: Lecture 3

Switch statement (IV)

There are three important things to know about the switch statement: The switch differs from the if in that switch can only

test for equality, whereas if can evaluate any type of relational or logical expression.

o E.g., case (A>10) Switch works only for character and integer numbers.

It does not work for floating and doubleo E.g., case (A=2.23)

No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch may have case constants that are the same.

Incorrect

Incorrect

25/31

Page 26: Lecture 3

Common Programming Error 1

Not including a break statement at the end of each case in a switch is a syntax error. The exception to this rule is the empty case.

Control Statements— 26

Page 27: Lecture 3

Common Programming Error 2

Specifying an expression including variables (e.g., a + b) in a switch statement’s case label is a syntax error.

Control Statements— 27

Page 28: Lecture 3

Common Programming Error 3

Providing identical case labels in a switch statement is a compilation error. Providing case labels containing different expressions that evaluate to the same value also is a compilation error. For example, placing case 4 + 1: and case 3 + 2: in the same switch statement is a compilation error, because these are both equivalent to case 5:.

Control Statements— 28

Page 29: Lecture 3

List of keywords in C#

Control Statements— 29

Page 30: Lecture 3

List of keywords in C# (I)

Control Statements— 30

Page 31: Lecture 3

List of keywords in C# (II)

Control Statements— 31