Week 4: CtlSt tControl Structures - Kasetsart University · PDF fileWeek 4: CtlSt tControl ......
Transcript of Week 4: CtlSt tControl Structures - Kasetsart University · PDF fileWeek 4: CtlSt tControl ......
204111: Computer and Programming
k C t l St tWeek 4: Control Structures
Monchai Sopitkamon Ph DMonchai Sopitkamon, Ph.D.
OverviewOverview
Types of control structures Using selection structure Using repetition structure Using repetition structure
T pes of cont ol st ct esTypes of control structures
C# provides 8 types of control structures one sequence structure statements are executed one sequence structure – statements are executed one after the other in the order they appear in the programprogram.
three selection structure – statement(s) is/are t d if diti i t ki d if thexecuted if a condition is true or skipped if the
condition is false. E.g., if, if/else, switchf i i ( ) i / four repetition structure –statement(s) is/are executed over and over again (loops) until or while a
ifi diti i ti fi d E hil d / hilspecific condition is satisfied. E.g., while, do/while, for, foreach.
Selection St ct esSelection Structures
if (single-selection structure)
if/else (double-selection structure)
switch (multiple selection structure) switch (multiple-selection structure)
Selection StructureSelection Structure
IF IF/ELSE
if (condition)
if (condition)statement1;
IF /
if (condition)statement;
elsestatement2;
conditioncondition
FalseTrueconditionFalse
True
FalseTrue
statement statement2statement1
Selection St ct eSelection Structure
switch (multiple-selection structure)
syntax: switch (<expression>){{
case <constant-expression>:<statements>;break;break;
d f lt
required
default:<statements>;break;
optional
<constant-expression> must be integral or
break;}
<constant expression> must be integral or string type.
S itch statement
switch (<expression>){
case <constant-expression>:<statements>;b kSwitch statement break;
default:<statements>;
<expression> is evaluated. Result is compared to each case sequentially
<statements>;break;
}
Result is compared to each case, sequentially. If a match is found, the statements after the
case keyword are executedcase keyword are executed. If no match is found, the (optional) default case
takes effecttakes effect. “break;” is required after each block, since C#
does not support an explicit “fall-through” fromdoes not support an explicit fall through from one case label to another. However, it is allowed to stack case labels to specify that a o ed to stac case abe s to spec y t atcertain statements are to be executed for several cases.
S it h l Si l C l l tSwitch example - Simple Calculator
double a, b;char op;double sol=0;
If we want 'x' to be another multiplicative double sol 0;
a = double.Parse(Console.ReadLine());op = char.Parse(Console.ReadLine());b d bl C l d i
poperator as well, we can insert a line as follows:
b = double.Parse(Console.ReadLine());switch(op) {case "+":
sol = a+b;;break;
case "-":sol = a-b;break;
case "*":case "x":
A “fall-through”casebreak;
case "*":sol = a*b;break;
sol = a*b;break;
case example
case "/":sol = a/b;break;
}}Console.WriteLine("{0} {1} {2} = {3}", a, op, b, sol);
do/while Statement : Syntax
do {do {Statement;
StatementStatement;Statement; Statement
State e t
Statement;} while Statement
(condition);condition
true
falsecould be boolean constant, boolean
variable or boolean expressionvariable, or boolean expression
do/while Statement : Exampledo/while Statement : Example
Output:Output: Hello WorldHello World
Output: 3
do/while Statement : Operation
Do/while statement is a conditional iteration statementsstatements
The loop body of a do/while statement will be p y /executed first before the exit condition is checked
Do/while loop is also called post conditional Do/while loop is also called post-conditionalbecause the condition is checked after the loop body
A do/while statement always gets executed atA do/while statement always gets executed at least once
do/while statement: Example1
int n 0;(n = 0)
int n = 0;do {
it
( )
Console.Write(“{0} “, n);write n
n++;
} while (n < 5);
n++
} while (n < 5);(n < 5)?
False
TrueOutput: 0 1 2 3 4
do/while statement: Example2
bool flag = true;(flag = true)
gstring s; int n;do {
read n{
s=Console.ReadLine();n=int.Parse(s);
(n > 0)? false
n int.Parse(s);if (n > 0)
Console Write(“{0} “
true
write nset flag= falseConsole.Write( {0}
, n);else
false
elseflag = false;
} while (flag true);
(flag==false)?
true} while (flag == true); true
While Statement : Syntax
could be boolean constant, boolean variable or boolean expression diti falsevariable, or boolean expression condition
true
while (condition ) {St tement
StatementStatement;Statement;
StatementStatement;Statement; Statement
}
While Statement : ExampleWhile Statement : Example
Output:Output: Hello WorldHello World
Output: 1
Whil St t t O tiWhile Statement : Operation
Since the condition is checked before the execution of the loop body, a while loop isexecution of the loop body, a while loop is also called pre-conditional.
A l th t diti i t As long as the entry condition remains true, the while loop will keep repeating.
No loop will be executed if the entry condition is false from the beginningcondition is false from the beginning.
While Statement E ample1While Statement : Example1
False
(n=0)
int n = 0;while (n <= 5) {
(n <= 5) ? False
True( ) {
Console.Write(“{0} “, n);True
write nn++;
} n++
Output: 0 1 2 3 4 5
While Statement : Example2bool flag = true;string s; int n; flag == true
Falsestring s; int n;while (flag==true) {
s=Console ReadLine();
flag == true
trueds=Console.ReadLine();
n=int.Parse(s);if ( 0)
read n
( 0) ?False
if (n > 0) Console.Write(n)
(n > 0) ?
True
False
flag falseelseflag = false;
Write n flag = false
ag a se;}
S ti l C t ll d LSentinel-Controlled Loops
Template:
Read the first value of input variableRead the first value of input variablewhile (input variable is not equal to sentinel) {
...Read next value of input variable
}
S ti l C t ll d LSentinel-Controlled Loops
Example: Accumulating exam scores Steps
1.Initialize total to 02.Read the first value and assign it to score3 While score is not the sentinel (e g -1) do3.While score is not the sentinel (e.g. 1) do
3.1 Add score to total3 2 R d th t l d i it t3.2 Read the next value and assign it to score
S ti l C t ll d LSentinel-Controlled Loops
Use of SentinelA ti l i l
int total =0, score; A sentinel is a value
used to control the termination of a
Console.Write("Enter score (-1 to end): ");
score=int.Parse((Console.ReadLine());termination of a loop.
E U
while (score != -1) {
total := total + score; E.g. User can
choose to use “–1” th ti l l
;Console.Write("Enter score (-1 to end): ");score=int.Parse((Console.ReadLine());
as the sentinel value to terminate the iteration
}
iteration.
S ti l C t ll d L E l 1Sentinel-Controlled Loop: Example1
L C t ll d b B l FlLoops Controlled by Boolean Flags
Flag:A Boolean variable whose value is changed from False A Boolean variable whose value is changed from Falseto True when a particular event occurs
B l Fl T l t Boolean Flags Template:Initialize flag to falsewhile (flag is still False) {
...Reset flag to True if event being monitored
occursoccurs}
L C t ll d b Fl E lLoops Controlled by Flags : Example
A program that checks whether the inputh t i di it b t 0 9charater is a digit between 0-9.
bool DigitRead = false;while (!DigitRead) {while (!DigitRead) {Console.Write (“Please enter a numeric : ");
t i t C l R dLi ()string st = Console.ReadLine();char NextChar = Char.Parse(st);DigitRead=(('0'<=NextChar)&& (NextChar<='9'))
}}
For Statement : SyntaxFor Statement : Syntaxfor( [initializers] ; [condition] ; [iterators] )for( [initializers] ; [condition] ; [iterators] )
{I ti li
statement;f l
Intializers
statement;statement;
condition false
true
itstatement;}
true
Statementterato}
Statemento
rs
Statement
For Statement : SyntaxFor Statement : Syntax
initializers A comma separated list of expressions or assignment A comma separated list of expressions or assignment
statements to initialize the loop counters.
expression expression An expression that can be implicitly converted to bool
or a type that contains overloading of the true andor a type that contains overloading of the true and false operators. The expression is used to test the loop-termination criteria. p
iterators Expression statement(s) to increment or decrement Expression statement(s) to increment or decrement
the loop counters.
For Statement : OperationFor Statement : Operation
The for statement executes the statement
t dl f llrepeatedly as follows:
First, the initializers are evaluated. ,
Then, while the expression evaluates to true, the statement(s) are executed and the iteratorsthe statement(s) are executed and the iteratorsare evaluated.
When the expression becomes false, control is transferred outside of the loop. p
For Statement : Example1For Statement : Example1
public class ForLoopTest
{ Output{
public static void Main()
{
Output
1
{
for(int i = 1; i <= 5; i++){ 2
3Console.WriteLine(“{0}”,
i); 4
5}
}
5
}
For Statement : Example2For Statement : Example2
Output A…Z alphabets on the screen using only one WriteLine() statementonly one WriteLine() statement.
AB...ZZ
For Statement : Example3For Statement : Example3
Write a program that finds a summation of a sequence of numbers from 1 99 and show thesequence of numbers from 1-99 and show the result. 1+2+…..+99 = 4950
do/while vs whiledo/while vs. whiled / hil t t t hil t t tdo/while statement while statement
Statementcondition false
Statement
Statementtrue
Statement
StatementStatement
Statement
conditiontrue
Statement
Statement
false
Statement
while vs forwhile vs. forhil t t t f t t twhile statement for statement
condition false
false
Intializers
true conditionfalse
true
it
Statement
St t t
true
Statement
terato
Statement
StatementStatement
ors
StatementStatement
Nested Loops
A nested loop is formed by placing an inner loop inside an outer loop.
The outer loop is executed firstThe outer loop is executed first.
If the inner loop is reached, the outer loop is suspended and the inner loop is executed.
After the inner loop is terminated the program After the inner loop is terminated, the program continues to execute the remaining statement(s) in the outer loopthe outer loop
Nested Loops : ExampleNested for loops
Nested Loops : ExampleNested for loops
Do not use the same control variable in the outer loop as in the inner loop
for (int outer = 1; outer <= 4; outer++) {
for (int inner = 1; inner <=5; inner++) {
Console.WriteLine("Outer = {0} & Inner = {1}", outer, inner);
}
}
Nested Loops : ExampleNested while loops
Nested Loops : Example
int outer = 1;
Nested while loops
int outer 1;
while (outer <= 4) {
int inner = 1 ;int inner 1 ;
while (inner <= 5) {
Console.WriteLine("Outer = {0} & Inner = {1}", outer, inner);Console.WriteLine( Outer {0} & Inner {1} , outer, inner);
inner = inner +1;
}}
outer = outer +1;
}}
Nested Loops : ExampleNested Loops : ExampleNested do/while loops
int outer = 1;
Nested do/while loops
int outer 1;
do {
int inner = 1;int inner 1;
do {
Console.WriteLine("Outer = {0} & Inner = {1}", outer, inner);Console.WriteLine( Outer {0} & Inner {1} , outer, inner);
inner++;
} while (inner < 6);} while (inner 6);
outer++;
} while (outer < 5);} while (outer 5);
Infinite looping
No statements in the loop body can update the value of the entry condition.
(E g omit counter = counter +1)(E.g. omit counter counter +1)
The statement(s) in the loop body make(s) the variable become far away from the stoppingvariable become far away from the stopping condition.
(E.g. counter = counter – 1)
Break StatementBreak Statement
The break statement terminates the l t l i l it hclosest enclosing loop or switch
statement in which it appears pp
Control is passed to the statement that f ll th t i t d t t tfollows the terminated statement
Break Statement : ExampleBreak Statement : Exampleclass Program {
public static void Main(string[] args){{
int sum=0, num=1, count=1;while (num > 0) 1 1while (num > 0) {
sum += num;
1 12 33 6;
if (count > 5)break;
4 105 15
Console.WriteLine(num+"\t"+sum);num++;count++;count++;
}}}
}
Continue StatementContinue Statement
The continue statement passes control to the next iteration of the enclosing iterationnext iteration of the enclosing iterationstatement in which it appears.
Continue Statement : ExampleContinue Statement : Exampleclass Program {
public static void Main(string[] args){{
int sum=0, i=0;dodo {
i++;
1 13 45 9;
if ((i%2) == 0)continue;
5 97 169 25
sum += i;Console.WriteLine(i+"\t"+sum);
}}while (i < 10);}}
}
Continue Statement : ExampleContinue Statement : Example
1 13 45 95 97 169 25