SlideShare une entreprise Scribd logo
1  sur  23
Lecture #03:

Assignment Operator and Simple
Control Structures
Assignment Operators
Assignment operator

Sample expression

Explanation

+=
-=
*=
/=
%=

c
d
e
f
g

c
d
e
f
g

+=
-=
*=
/=
%=

7
4
5
3
2

=
=
=
=
=

c
d
e
f
g

+
*
/
%

7
4
5
3
2

count = count + 1; // these two are equivalent
count ++;
count = count – 1; // these two are equivalent
count --;

2
Precedence and Associativity
Operators

high

low

Associativity

Type

()
++ -++ -- + - (type)
* / %
+ < <= > >=
== !=
?:
= += -= *= /= %=

left to right
right to left

parentheses
unary postfix

right to left

unary prefix

left to right

multiplicative

left to right

additive

left to right

relational

left to right

equality

right to left

conditional

right to left

assignment

3
Sequential Programming Revisited
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

// Addition.cs
// An addition program.
using System;
class Addition
{
static void Main( string[] args )
{
string firstNumber, // first string entered by user
secondNumber; // second string entered by user
int number1,
number2,
sum;

// first number to add
// second number to add
// sum of number1 and number2

// prompt for and read first number from user as string
Console.Write( "Please enter the first integer: " );
firstNumber = Console.ReadLine();

17

// prompt for and read first number from user as string

18

Console.Write( "Please enter the first integer: " );

19

firstNumber = Console.ReadLine();

20
21

// read second number from user as string

22

Console.Write( "nPlease enter the second integer: " );

23

secondNumber = Console.ReadLine();

24
25

// convert numbers from type string to type int

// read second number from user as string
Console.Write( "nPlease enter the second integer: " );
secondNumber = Console.ReadLine();

26

number1 = Int32.Parse( firstNumber );

// convert numbers from type string to type int
number1 = Int32.Parse( firstNumber );
number2 = Int32.Parse( secondNumber );

27

number2 = Int32.Parse( secondNumber );

28

// add numbers
sum = number1 + number2;
// display results
Console.WriteLine( "nThe sum is {0}.", sum );
} // end method Main
} // end class Addition

29

// add numbers

30

sum = number1 + number2;

31
32

// display results

33

Console.WriteLine( "nThe sum is {0}.", sum );

4
Sequence Structure (Flowchart)

Each of these statements could be:
• a variable declaration
• an assignment statement

.
.

• a method call (e.g., Console.WriteLine(

…);

)

or more complex statements (to be covered later)

5
More Interesting: Control Statements
Selection (a.k.a., conditional statements): decide whether or not to
execute a particular statement; these are also called the selection
statements or decision statements
• if selection (one choice)
• if/else selection (two choices)
– Also: the ternary conditional operator e1?e2:e3
• switch statement (multiple choices)
Repetition (a.k.a., loop statements): repeatedly executing the same
statements (for a certain number of times or until a test condition is
satisfied).
• while structure
• do/while structure
• for structure
• foreach structure

6
Why Control Statements ?
Last few classes: a sequence of
statements
Sequential programming

Most programs need more flexibility in the
order of statement execution
The order of statement execution is called the
flow of control
7
Pseudocode & Flowcharts to
Represent Flow of Control
Pseudocode

Artificial and informal language
Helps programmers to plan an algorithm
Similar to everyday English
Not an actual programming language

Flowchart --- a graphical way of writing
pseudocode
Rectangle used to show action
Circles used as connectors
Diamonds used as decisions

8
Sequence Structure

add grade to total

total = total + grade;

add 1 to counter

counter = counter + 1;

9
C# Control Structures: Selection
switch structure
(multiple selections)
if/else structure
(double selection)
T

F

T

break

F
T

break

F

.
.
if structure
(single selection)
T

.

T

break

F

F
break

10
if Statement
if ( <test> )
<code executed if <test> is true > ;

The if statement
Causes the program to make a selection
Chooses based on conditional
• <test>: any expression that evaluates to a bool type
• True: perform an action
• False: skip the action

Single entry/exit point
No semicolon after the condition
11
if Statement (cont’d)
if ( <test> )
{
<code executed if <test> is true > ;
……
<more code executed if <test> is
true > ;
}
The body of the branch can also be a block
statement!
No semicolon after the condition
No semicolon after the block statement

12
if Statement (cont’d)

true
Grade >= 60

print “Passed”

false

if (studentGrade >= 60)
Console.WriteLine (“Passed”);

// beginning of the next statement

13
if Statement (cont’d)
true
Grade >= 60

print “Passed”

false

if (studentGrade >= 60)
{
Console.WriteLine (“Passed”);
}

// beginning of the next statement
14
if/else Statement
if ( <test> )
<code executed if <test> is true > ;
else
<code executed if <test> is false > ;

The if/else structure
Alternate courses can be taken when the
statement is false
Rather than one action there are two choices
Nested structures can test many cases
15
if/else Statement (cont’d)
if ( <test> )
{
<code executed if <test> is true > ;
……
}
else
{
<code executed if <test> is false > ;
……
}
Can use the block statement inside either branch
16
if/else Statement (cont’d)
false

true
Grade >= 60

print “Failed”

print “Passed”

if (studentGrade >= 60)
Console.WriteLine (“Passed”);
else
Console.WriteLine (“Failed”);
// beginning of the next statement

17
if/else Statement (cont’d)
false

true
Grade >= 60

print “Failed”

print “Passed”

if (studentGrade >= 60)
{
Console.WriteLine (“Passed”);
}
else
Console.WriteLine (“Failed”);
// beginning of the next statement
18
Nested if/else Statements
The statement
executed as a
result of an if
statement or else
clause could be
another if
statement
These are called
nested if /else
statements

if (studentGrade >= 90)
Console.WriteLine(“A”);
else if (studentGrade >= 80)
Console.WriteLine(“B”);
else if (studentGrade >= 70)
Console.WriteLine(“C”);
else if (studentGrade >= 60)
Console.WriteLine(“D”);
else
Console.WriteLine(“F”);

// beginning of the next statement

19
Ternary Conditional Operator (?:)
Conditional Operator (e 1 ?e 2 :e 3 )
C#’s only ternary operator
Can be used to construct expressions
Similar to an if/else structure
string result;
int numQ;
…………
result = (numQ==1) ? “Quarter” : “Quarters”;

// beginning of the next statement

20
More Complex (Compound) Boolean
Expressions: Logical Operators
Boolean expressions can also use the
following logical and conditional operators:
!
&
|
^
&&
||

Logical NOT
Logical AND
Logical OR
Logical exclusive OR (XOR)
Conditional AND
Conditional OR

They all take boolean operands and produce
boolean results
21
Comparison: Logical and Conditional Operators
Logical AND (&) and Logical OR (|)
• Always evaluate both conditions

Conditional AND (&&) and Conditional OR (||)
• Would not evaluate the second condition if the result of the first
condition would already decide the final outcome.
• Ex 1: false && (x++ > 10) --- no need to evaluate the 2nd
condition
• Ex 2:
if (count != 0 && total /count)
{

…
}

22
Switch Statement
int a=3;
switch (a)
{
case 0:
Console.Write("zero");
break;
case 1:
Console.Write("One");
break;
…….
default:
Console.Write ("False statement");
break;
}

23

Contenu connexe

Tendances

C++ control structure
C++ control structureC++ control structure
C++ control structure
bluejayjunior
 
Control Structures
Control StructuresControl Structures
Control Structures
Ghaffar Khan
 

Tendances (20)

Control statement in c
Control statement in cControl statement in c
Control statement in c
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
Flow of control ppt
Flow of control pptFlow of control ppt
Flow of control ppt
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in c
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
Control structure
Control structureControl structure
Control structure
 
Control structure in c
Control structure in cControl structure in c
Control structure in c
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
Unit 5. Control Statement
Unit 5. Control StatementUnit 5. Control Statement
Unit 5. Control Statement
 
Mesics lecture 6 control statement = if -else if__else
Mesics lecture 6   control statement = if -else if__elseMesics lecture 6   control statement = if -else if__else
Mesics lecture 6 control statement = if -else if__else
 
Control structures in c
Control structures in cControl structures in c
Control structures in c
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C Programming
 
Control Structures
Control StructuresControl Structures
Control Structures
 
Control structure of c language
Control structure of c languageControl structure of c language
Control structure of c language
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 

En vedette

Visual studio .net c# study guide
Visual studio .net c# study guideVisual studio .net c# study guide
Visual studio .net c# study guide
root12345
 
Visual programming lab
Visual programming labVisual programming lab
Visual programming lab
Soumya Behera
 
Introduction to visual basic programming
Introduction to visual basic programmingIntroduction to visual basic programming
Introduction to visual basic programming
Roger Argarin
 

En vedette (16)

Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Visula C# Programming Lecture 1
Visula C# Programming Lecture 1
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Visula C# Programming Lecture 5
Visula C# Programming Lecture 5Visula C# Programming Lecture 5
Visula C# Programming Lecture 5
 
Visual studio .net c# study guide
Visual studio .net c# study guideVisual studio .net c# study guide
Visual studio .net c# study guide
 
C# for beginners
C# for beginnersC# for beginners
C# for beginners
 
Learn C# at ASIT
Learn C# at ASITLearn C# at ASIT
Learn C# at ASIT
 
Visual programming
Visual programmingVisual programming
Visual programming
 
Visual programming lab
Visual programming labVisual programming lab
Visual programming lab
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 
Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
 
C# basics
 C# basics C# basics
C# basics
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Introduction to visual basic programming
Introduction to visual basic programmingIntroduction to visual basic programming
Introduction to visual basic programming
 
Visual Basic Controls ppt
Visual Basic Controls pptVisual Basic Controls ppt
Visual Basic Controls ppt
 

Similaire à Visula C# Programming Lecture 3

Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
alish sha
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
alish sha
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.ppt
Sanjjaayyy
 

Similaire à Visula C# Programming Lecture 3 (20)

ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Decision Making and Branching
Decision Making and BranchingDecision Making and Branching
Decision Making and Branching
 
Chapter 1 nested control structures
Chapter 1 nested control structuresChapter 1 nested control structures
Chapter 1 nested control structures
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Chapter 1 Nested Control Structures
Chapter 1 Nested Control StructuresChapter 1 Nested Control Structures
Chapter 1 Nested Control Structures
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
BLM101_2.pptx
BLM101_2.pptxBLM101_2.pptx
BLM101_2.pptx
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.ppt
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.ppt
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.ppt
 
Decision Control Structure If & Else
Decision Control Structure If & ElseDecision Control Structure If & Else
Decision Control Structure If & Else
 
C Unit-2.ppt
C Unit-2.pptC Unit-2.ppt
C Unit-2.ppt
 
Csphtp1 05
Csphtp1 05Csphtp1 05
Csphtp1 05
 
C programming
C programmingC programming
C programming
 

Dernier

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Dernier (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 

Visula C# Programming Lecture 3

  • 1. Lecture #03: Assignment Operator and Simple Control Structures
  • 2. Assignment Operators Assignment operator Sample expression Explanation += -= *= /= %= c d e f g c d e f g += -= *= /= %= 7 4 5 3 2 = = = = = c d e f g + * / % 7 4 5 3 2 count = count + 1; // these two are equivalent count ++; count = count – 1; // these two are equivalent count --; 2
  • 3. Precedence and Associativity Operators high low Associativity Type () ++ -++ -- + - (type) * / % + < <= > >= == != ?: = += -= *= /= %= left to right right to left parentheses unary postfix right to left unary prefix left to right multiplicative left to right additive left to right relational left to right equality right to left conditional right to left assignment 3
  • 4. Sequential Programming Revisited 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 // Addition.cs // An addition program. using System; class Addition { static void Main( string[] args ) { string firstNumber, // first string entered by user secondNumber; // second string entered by user int number1, number2, sum; // first number to add // second number to add // sum of number1 and number2 // prompt for and read first number from user as string Console.Write( "Please enter the first integer: " ); firstNumber = Console.ReadLine(); 17 // prompt for and read first number from user as string 18 Console.Write( "Please enter the first integer: " ); 19 firstNumber = Console.ReadLine(); 20 21 // read second number from user as string 22 Console.Write( "nPlease enter the second integer: " ); 23 secondNumber = Console.ReadLine(); 24 25 // convert numbers from type string to type int // read second number from user as string Console.Write( "nPlease enter the second integer: " ); secondNumber = Console.ReadLine(); 26 number1 = Int32.Parse( firstNumber ); // convert numbers from type string to type int number1 = Int32.Parse( firstNumber ); number2 = Int32.Parse( secondNumber ); 27 number2 = Int32.Parse( secondNumber ); 28 // add numbers sum = number1 + number2; // display results Console.WriteLine( "nThe sum is {0}.", sum ); } // end method Main } // end class Addition 29 // add numbers 30 sum = number1 + number2; 31 32 // display results 33 Console.WriteLine( "nThe sum is {0}.", sum ); 4
  • 5. Sequence Structure (Flowchart) Each of these statements could be: • a variable declaration • an assignment statement . . • a method call (e.g., Console.WriteLine( …); ) or more complex statements (to be covered later) 5
  • 6. More Interesting: Control Statements Selection (a.k.a., conditional statements): decide whether or not to execute a particular statement; these are also called the selection statements or decision statements • if selection (one choice) • if/else selection (two choices) – Also: the ternary conditional operator e1?e2:e3 • switch statement (multiple choices) Repetition (a.k.a., loop statements): repeatedly executing the same statements (for a certain number of times or until a test condition is satisfied). • while structure • do/while structure • for structure • foreach structure 6
  • 7. Why Control Statements ? Last few classes: a sequence of statements Sequential programming Most programs need more flexibility in the order of statement execution The order of statement execution is called the flow of control 7
  • 8. Pseudocode & Flowcharts to Represent Flow of Control Pseudocode Artificial and informal language Helps programmers to plan an algorithm Similar to everyday English Not an actual programming language Flowchart --- a graphical way of writing pseudocode Rectangle used to show action Circles used as connectors Diamonds used as decisions 8
  • 9. Sequence Structure add grade to total total = total + grade; add 1 to counter counter = counter + 1; 9
  • 10. C# Control Structures: Selection switch structure (multiple selections) if/else structure (double selection) T F T break F T break F . . if structure (single selection) T . T break F F break 10
  • 11. if Statement if ( <test> ) <code executed if <test> is true > ; The if statement Causes the program to make a selection Chooses based on conditional • <test>: any expression that evaluates to a bool type • True: perform an action • False: skip the action Single entry/exit point No semicolon after the condition 11
  • 12. if Statement (cont’d) if ( <test> ) { <code executed if <test> is true > ; …… <more code executed if <test> is true > ; } The body of the branch can also be a block statement! No semicolon after the condition No semicolon after the block statement 12
  • 13. if Statement (cont’d) true Grade >= 60 print “Passed” false if (studentGrade >= 60) Console.WriteLine (“Passed”); // beginning of the next statement 13
  • 14. if Statement (cont’d) true Grade >= 60 print “Passed” false if (studentGrade >= 60) { Console.WriteLine (“Passed”); } // beginning of the next statement 14
  • 15. if/else Statement if ( <test> ) <code executed if <test> is true > ; else <code executed if <test> is false > ; The if/else structure Alternate courses can be taken when the statement is false Rather than one action there are two choices Nested structures can test many cases 15
  • 16. if/else Statement (cont’d) if ( <test> ) { <code executed if <test> is true > ; …… } else { <code executed if <test> is false > ; …… } Can use the block statement inside either branch 16
  • 17. if/else Statement (cont’d) false true Grade >= 60 print “Failed” print “Passed” if (studentGrade >= 60) Console.WriteLine (“Passed”); else Console.WriteLine (“Failed”); // beginning of the next statement 17
  • 18. if/else Statement (cont’d) false true Grade >= 60 print “Failed” print “Passed” if (studentGrade >= 60) { Console.WriteLine (“Passed”); } else Console.WriteLine (“Failed”); // beginning of the next statement 18
  • 19. Nested if/else Statements The statement executed as a result of an if statement or else clause could be another if statement These are called nested if /else statements if (studentGrade >= 90) Console.WriteLine(“A”); else if (studentGrade >= 80) Console.WriteLine(“B”); else if (studentGrade >= 70) Console.WriteLine(“C”); else if (studentGrade >= 60) Console.WriteLine(“D”); else Console.WriteLine(“F”); // beginning of the next statement 19
  • 20. Ternary Conditional Operator (?:) Conditional Operator (e 1 ?e 2 :e 3 ) C#’s only ternary operator Can be used to construct expressions Similar to an if/else structure string result; int numQ; ………… result = (numQ==1) ? “Quarter” : “Quarters”; // beginning of the next statement 20
  • 21. More Complex (Compound) Boolean Expressions: Logical Operators Boolean expressions can also use the following logical and conditional operators: ! & | ^ && || Logical NOT Logical AND Logical OR Logical exclusive OR (XOR) Conditional AND Conditional OR They all take boolean operands and produce boolean results 21
  • 22. Comparison: Logical and Conditional Operators Logical AND (&) and Logical OR (|) • Always evaluate both conditions Conditional AND (&&) and Conditional OR (||) • Would not evaluate the second condition if the result of the first condition would already decide the final outcome. • Ex 1: false && (x++ > 10) --- no need to evaluate the 2nd condition • Ex 2: if (count != 0 && total /count) { … } 22
  • 23. Switch Statement int a=3; switch (a) { case 0: Console.Write("zero"); break; case 1: Console.Write("One"); break; ……. default: Console.Write ("False statement"); break; } 23