SlideShare a Scribd company logo
1 of 31
Control 
Statements (1) 
Lecture 3 
Dr. Hakem Beitollahi 
Computer Engineering Department 
Soran University
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
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 work 
1. 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
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
Control Statements 
Control Statements— 5
Control Statements 
 Three control structures 
 Sequence structure 
o Programs executed sequentially by default 
 Selection structures 
o if, if…else, switch 
 Repetition structures 
o while, do…while, for 
Control Statements— 6
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
if Selection Statement (II) 
 Example: 
if ( grade >= 60 ) 
Console.WriteLine("Passed“); 
grade >= 60 
False 
True 
Console.WriteLine (“passed” 
8/31
Good Programming Practice 1 
 Indent both body statements of an if/else 
structure. 
Control Statements— 9
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
if…else Double-Selection Statement (II) 
 If-else flowchart 
Expression 
true false 
Action1 Action2 
11/31
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(studentGr 
ade >= 60) 
Value if true 
Console.writeline 
(“passed”) 
Value if false 
Console.writel 
ine(“faild”) 
12/31
If…else (example) 
// Control Statement example via random generation 
using 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
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 
 Example 
o 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
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");
Good Programming Practice 2 
A 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
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 as 
o if ( x > 5 ) 
if ( y > 5 ) 
Console.WriteLine("x and y are > 5“); 
else 
Console.WriteLine("x is <= 5“); 
17/31
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
if…else double-selection 
statement (VIII) 
 Compound statement 
 Also called a block 
o Set of statements within a pair of braces 
o 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
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
Switch Statement 
Control Statements— 21
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 is 
switch (expression) { 
case constant1: 
statement sequence 
break; 
case constant2: 
statement sequence 
break; 
case constant3: 
statement sequence 
break; 
default 
statement sequence 
break; 
} 22/31
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
Switch statement (III) 
// switch statement example 
using 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
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) 
Incorrect 
 Switch works only for character and integer numbers. 
It does not work for floating and double 
o E.g., case (A=2.23) 
Incorrect 
 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. 
25/31
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
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
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
List of keywords in C# 
Control Statements— 29
List of keywords in C# (I) 
Control Statements— 30
List of keywords in C# (II) 
Control Statements— 31

More Related Content

What's hot

03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
C programming decision making
C programming decision makingC programming decision making
C programming decision makingSENA
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C ProgrammingKamal Acharya
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJTANUJ ⠀
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in CRAJ KUMAR
 
Control structures i
Control structures i Control structures i
Control structures i Ahmad Idrees
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1Jomel Penalba
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONvikram mahendra
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
C language control statements
C language  control statementsC language  control statements
C language control statementssuman Aggarwal
 
Conditional statement
Conditional statementConditional statement
Conditional statementMaxie Santos
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programmingPriyansh Thakar
 
Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual BasicTushar Jain
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)Prashant Sharma
 

What's hot (20)

03a control structures
03a   control structures03a   control structures
03a control structures
 
C programming decision making
C programming decision makingC programming decision making
C programming decision making
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C Programming
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in C
 
Control structures i
Control structures i Control structures i
Control structures i
 
Controls & Loops in C
Controls & Loops in C Controls & Loops in C
Controls & Loops in C
 
Control statement-Selective
Control statement-SelectiveControl statement-Selective
Control statement-Selective
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1
 
Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
C# conditional branching statement
C# conditional branching statementC# conditional branching statement
C# conditional branching statement
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
C language control statements
C language  control statementsC language  control statements
C language control statements
 
Conditional statement
Conditional statementConditional statement
Conditional statement
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programming
 
Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual Basic
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 

Viewers also liked (20)

C++ Programming Club-Lecture 1
C++ Programming Club-Lecture 1C++ Programming Club-Lecture 1
C++ Programming Club-Lecture 1
 
Data structures-sample-programs
Data structures-sample-programsData structures-sample-programs
Data structures-sample-programs
 
The pseudocode
The pseudocodeThe pseudocode
The pseudocode
 
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
 
C if else
C if elseC if else
C if else
 
C++ loop
C++ loop C++ loop
C++ loop
 
Loops in C Programming
Loops in C ProgrammingLoops in C Programming
Loops in C Programming
 
FMS Spring Appeal 2014
FMS Spring Appeal 2014FMS Spring Appeal 2014
FMS Spring Appeal 2014
 
Math Project for Mr. Medina's Class
Math Project for Mr. Medina's ClassMath Project for Mr. Medina's Class
Math Project for Mr. Medina's Class
 
Slide11 icc2015
Slide11 icc2015Slide11 icc2015
Slide11 icc2015
 
Alberto Rocha - Key Core Competencies
Alberto Rocha - Key Core CompetenciesAlberto Rocha - Key Core Competencies
Alberto Rocha - Key Core Competencies
 
Asthma
AsthmaAsthma
Asthma
 
Korovai or wedding bread
Korovai or wedding breadKorovai or wedding bread
Korovai or wedding bread
 
Presentation1
Presentation1Presentation1
Presentation1
 
Pengukuran aliran c.(positiv displacement)
Pengukuran aliran c.(positiv displacement)Pengukuran aliran c.(positiv displacement)
Pengukuran aliran c.(positiv displacement)
 
Training- Classroom Vs Online
Training- Classroom Vs OnlineTraining- Classroom Vs Online
Training- Classroom Vs Online
 
Appilicious
AppiliciousAppilicious
Appilicious
 
Tugas css 1210651191
Tugas css 1210651191Tugas css 1210651191
Tugas css 1210651191
 
огюст роден
огюст роденогюст роден
огюст роден
 
CLI, Inc. Contract Manager Roles and Responsibilities
CLI, Inc. Contract Manager Roles and ResponsibilitiesCLI, Inc. Contract Manager Roles and Responsibilities
CLI, Inc. Contract Manager Roles and Responsibilities
 

Similar to Lecture 3

Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Abou Bakr Ashraf
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c languagechintupro9
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional StatementsIntro C# Book
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programmingnmahi96
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Neeru Mittal
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 
Decision statements in c laguage
Decision statements in c laguageDecision statements in c laguage
Decision statements in c laguageTanmay Modi
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)Jyoti Bhardwaj
 
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_selectionalish 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_selectionalish sha
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
Chapter 8 - Conditional Statement
Chapter 8 - Conditional StatementChapter 8 - Conditional Statement
Chapter 8 - Conditional StatementDeepak Singh
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptxssuserfb3c3e
 

Similar to Lecture 3 (20)

Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
 
selection structures
selection structuresselection structures
selection structures
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
 
CH-4 (1).pptx
CH-4 (1).pptxCH-4 (1).pptx
CH-4 (1).pptx
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
Decision statements in c laguage
Decision statements in c laguageDecision statements in c laguage
Decision statements in c laguage
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)
 
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
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
Branching
BranchingBranching
Branching
 
Chapter 8 - Conditional Statement
Chapter 8 - Conditional StatementChapter 8 - Conditional Statement
Chapter 8 - Conditional Statement
 
Chapter 1 nested control structures
Chapter 1 nested control structuresChapter 1 nested control structures
Chapter 1 nested control structures
 
Lecture 9- Control Structures 1
Lecture 9- Control Structures 1Lecture 9- Control Structures 1
Lecture 9- Control Structures 1
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
 

More from Soran University (8)

Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Administrative
AdministrativeAdministrative
Administrative
 

Recently uploaded

An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxPurva Nikam
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 

Recently uploaded (20)

An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptx
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 

Lecture 3

  • 1. Control Statements (1) Lecture 3 Dr. Hakem Beitollahi Computer Engineering Department Soran University
  • 2. 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
  • 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 work 1. 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
  • 4. 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
  • 5. Control Statements Control Statements— 5
  • 6. Control Statements  Three control structures  Sequence structure o Programs executed sequentially by default  Selection structures o if, if…else, switch  Repetition structures o while, do…while, for Control Statements— 6
  • 7. 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
  • 8. if Selection Statement (II)  Example: if ( grade >= 60 ) Console.WriteLine("Passed“); grade >= 60 False True Console.WriteLine (“passed” 8/31
  • 9. Good Programming Practice 1  Indent both body statements of an if/else structure. Control Statements— 9
  • 10. 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
  • 11. if…else Double-Selection Statement (II)  If-else flowchart Expression true false Action1 Action2 11/31
  • 12. 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(studentGr ade >= 60) Value if true Console.writeline (“passed”) Value if false Console.writel ine(“faild”) 12/31
  • 13. If…else (example) // Control Statement example via random generation using 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
  • 14. 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  Example o 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
  • 15. 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");
  • 16. Good Programming Practice 2 A 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
  • 17. 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 as o if ( x > 5 ) if ( y > 5 ) Console.WriteLine("x and y are > 5“); else Console.WriteLine("x is <= 5“); 17/31
  • 18. 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
  • 19. if…else double-selection statement (VIII)  Compound statement  Also called a block o Set of statements within a pair of braces o 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
  • 20. 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
  • 21. Switch Statement Control Statements— 21
  • 22. 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 is switch (expression) { case constant1: statement sequence break; case constant2: statement sequence break; case constant3: statement sequence break; default statement sequence break; } 22/31
  • 23. 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
  • 24. Switch statement (III) // switch statement example using 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
  • 25. 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) Incorrect  Switch works only for character and integer numbers. It does not work for floating and double o E.g., case (A=2.23) Incorrect  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. 25/31
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. List of keywords in C# Control Statements— 29
  • 30. List of keywords in C# (I) Control Statements— 30
  • 31. List of keywords in C# (II) Control Statements— 31