Control Structures Week 4: Control Structures Week 4: Monchai - - PowerPoint PPT Presentation
Control Structures Week 4: Control Structures Week 4: Monchai - - PowerPoint PPT Presentation
204111: Computer and 204111: Computer and Programming Programming Control Structures Week 4: Control Structures Week 4: Monchai Sopitkamon Sopitkamon, Ph.D. , Ph.D. Monchai Overview Overview Types of control structures Types of
Overview Overview
- Types of control structures
Types of control structures
- Using selection structure
Using selection structure
- Using repetition structure
Using repetition structure
Types of control structures Types of control structures
- C# provides 8 types of control structures
C# provides 8 types of control structures
- ne sequence structure
- ne sequence structure –
– statements are executed statements are executed
- ne after the other in the order they appear in the
- ne after the other in the order they appear in the
program. program.
- three selection structure
three selection structure – – statement(s statement(s) is/are ) is/are executed if a condition is true or skipped if the executed if a condition is true or skipped if the condition is false. E.g., condition is false. E.g., if if, , if/else if/else, , switch switch
- four repetition structure
four repetition structure – –statement(s statement(s) is/are ) is/are executed over and over again (loops) until or while a executed over and over again (loops) until or while a specific condition is satisfied. E.g., specific condition is satisfied. E.g., while while, , do/while do/while, , for for, , foreach foreach. .
Selection Structures Selection Structures
- if
if (single
(single-
- selection structure)
selection structure)
- if/else
if/else (double
(double-
- selection structure)
selection structure)
- switch
switch (multiple
(multiple-
- selection structure)
selection structure)
Selection Structure Selection Structure
condition False True
statement
if (condition)
statement; condition False True statement2 statement1
if (condition)
statement1;
else
statement2;
IF IF/ELSE
Selection Structure Selection Structure
- switch
switch (multiple
(multiple-
- selection structure)
selection structure)
- syntax:
syntax:
< constant-expression> must be integral or
string type.
switch (< expression> ) { case < constant-expression> :
< statements> ;
break; : default:
< statements> ;
break; }
- ptional
required
Switch statement Switch statement
- <
< expression expression> > is evaluated. is evaluated.
- Result is compared to each case, sequentially.
Result is compared to each case, sequentially.
- If a match is found, the statements after the
If a match is found, the statements after the case keyword are executed. case keyword are executed.
- If no match is found, the (optional) default case
If no match is found, the (optional) default case takes effect. takes effect.
- “
“break; break;” ” is required after each block, since C#
is required after each block, since C# does not support an explicit does not support an explicit “ “fall fall-
- through
through” ” from from
- ne case label to another. However, it is
- ne case label to another. However, it is
allowed to stack case labels to specify that allowed to stack case labels to specify that certain statements are to be executed for certain statements are to be executed for several cases. several cases.
switch (< expression> ) { case < constant-expression> :
< statements> ;
break; : default:
< statements> ;
break; }
Switch example Switch example -
- Simple Calculator
Simple Calculator
double a, b; char op; double sol=0; a = double.Parse(Console.ReadLine());
- p = char.Parse(Console.ReadLine());
b = double.Parse(Console.ReadLine()); switch(op) { case "+": sol = a+b; break; case "-": sol = a-b; break; case "*": sol = a*b; break; case "/": sol = a/b; break; } Console.WriteLine("{0} {1} {2} = {3}", a, op, b, sol);
If we want 'x' to be If we want 'x' to be another multiplicative another multiplicative
- perator as well, we can
- perator as well, we can
insert a line as follows: insert a line as follows:
case "* ": case "x": sol = a* b; break;
A “fall- through” case example
do/while Statement : Syntax do/while Statement : Syntax
do { do {
Statement; Statement; Statement; Statement; Statement; Statement;
} while } while ( ( condition
condition)
) ;
;
condition true false
Statement Statement Statement
could be boolean constant, boolean variable, or boolean expression
do/while Statement : Example do/while Statement : Example
Output: Hello World Hello World Output: 3
Do/ while statement is a conditional iteration
statements
The loop body of a do/ while statement will be
executed first before the exit condition is checked
Do/while loop is also called post-conditional because the condition is checked after the loop body A do/while statement always gets executed at least once
do/while Statement : Operation
do/while statement: do/while statement: Example1
Example1
int int n = 0; n = 0;
do { do {
Console.Write( Console.Write(“ “{ 0} { 0} “ “, n); , n); n+ + ; n+ + ;
} while } while ( ( n < 5)
n < 5); ;
(n < 5)? False True
n+ + write n
(n = 0)
Output: 0 1 2 3 4
do/while statement: do/while statement: Example2
Example2
bool bool flag = flag = true true; ; string s; string s; int int n; n;
do { do {
s= s= Console.ReadLine Console.ReadLine(); (); n= n= int.Parse(s int.Parse(s); ); if (n > 0) if (n > 0) Console.Write( Console.Write(“ “{ 0} { 0} “ “ , n); , n); else else flag = flag = false false; ;
} while } while (flag = = true);
(flag = = true);
(flag= = false)? false true read n (n > 0)? true write n false set flag = false
(flag = true)
While Statement : Syntax While Statement : Syntax
while while (condition ) (condition ) {
{
Statement; Statement; Statement; Statement; Statement; Statement;
} }
could be boolean constant, boolean variable, or boolean expression
condition
false true
Statement Statement Statement
While Statement : Example While Statement : Example
Output: Hello World Hello World Output: 3
Since the condition is checked before the execution of the loop body, a while loop is also called pre-conditional. 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 beginning.
While Statement : Operation
While Statement : Example1 While Statement : Example1
int int n = 0; n = 0;
while while (n < = 5)
(n < = 5) {
{
Console.Write( Console.Write(“ “{ 0} { 0} “ “, n); , n); n+ + ; n+ + ;
} }
(n < = 5) ?
False True
write n n+ +
(n=0)
Output: 0 1 2 3 4 5
While Statement : Example2 While Statement : Example2
bool bool flag = true; flag = true; string s; string s; int int n; n;
while while (flag= = true)
(flag= = true) {
{
s= s= Console.ReadLine Console.ReadLine(); (); n= n= int.Parse(s int.Parse(s); ); if (n > 0) if (n > 0) Console.Write(n Console.Write(n) ) else else flag = flag = false false; ;
} }
flag = = true
False
true read n (n > 0) ?
True
Write n
False
flag = false
Sentinel Sentinel-
- Controlled Loops
Controlled Loops
- Template:
Template:
Read the first value of input variable Read the first value of input variable
while while (input variable is not equal to sentinel)
(input variable is not equal to sentinel) {
{
... ... Read next value of input variable Read next value of input variable
} }
Sentinel Sentinel-
- Controlled Loops
Controlled Loops
- Example: Accumulating exam scores
Example: Accumulating exam scores
- Steps
Steps
1.Initialize 1.Initialize total to 0 to 0 2.Read the first value and assign it to 2.Read the first value and assign it to score score 3.While score is not the sentinel (e.g. 3.While score is not the sentinel (e.g. -
- 1) do
1) do 3.1 Add 3.1 Add score score to to total 3.2 Read the next value and assign it to 3.2 Read the next value and assign it to score score
Use of Sentinel
- A sentinel is a value
used to control the termination of a loop.
- E.g. User can
choose to use “–1” as the sentinel value to terminate the iteration.
int total =0, score; Convert.Write("Enter score (-1 to end): "); score=int.Parse((Console.ReadLine()); while (score != -1) { total := total + score; Convert.Write("Enter score (-1 to end): "); score=int.Parse((Console.ReadLine()); }
Sentinel Sentinel-
- Controlled Loops
Controlled Loops
Sentinel Sentinel-
- Controlled Loop: Example1
Controlled Loop: Example1
Loops Controlled by Boolean Flags Loops Controlled by Boolean Flags
- Flag:
Flag:
- A Boolean variable whose value is changed from False
A Boolean variable whose value is changed from False to True when a particular event occurs to True when a particular event occurs
- Boolean Flags Template:
Boolean Flags Template:
Initialize flag to false Initialize flag to false
while while (flag is still False)
(flag is still False) {
{
... ... Reset flag to True if event being monitored Reset flag to True if event being monitored
- ccurs
- ccurs
} }
Loops Controlled by Flags : Example Loops Controlled by Flags : Example
- A program that checks whether the input
A program that checks whether the input charater charater is a digit between 0 is a digit between 0-
- 9.
9.
DigitRead DigitRead = false; = false;
while while (!
(!DigitRead DigitRead) ) {
{
Console.Write Console.Write ( (“ “Please enter a numeric : "); Please enter a numeric : "); string string st st = = Console.ReadLine Console.ReadLine(); (); char char NextChar NextChar = = Char.Parse(st Char.Parse(st); ); DigitRead DigitRead= (('0'< = = (('0'< = NextChar NextChar)&& ( )&& (NextChar NextChar< = '9')) < = '9'))
} }
For Statement : Syntax For Statement : Syntax
for( for( [
[ initializers initializers] ] ; ; [condition] [condition] ; ; [ [ iterators iterators] ] )
) { {
statement; statement; statement; statement; statement; statement;
} }
condition false true
Statement Statement Statement
iterators
Intializers
For Statement : Syntax For Statement : Syntax
- initializers
initializers
- A comma separated list of expressions or assignment
A comma separated list of expressions or assignment statements to initialize the loop counters statements to initialize the loop counters.
.
- expression
expression
- An expression that can be implicitly converted to
An expression that can be implicitly converted to bool
bool
- r a type that contains overloading of the
- r a type that contains overloading of the true
true and and false false operators
- perators.
. The expression is used to test the
The expression is used to test the loop loop-
- termination criteria
termination criteria.
.
- iterators
iterators
- Expression statement
Expression statement(
(s
s)
) to increment or decrement
to increment or decrement the loop counters the loop counters.
.
For Statement : Operation For Statement : Operation
The The for
for statement executes the
statement executes the statement statement repeatedly as follows repeatedly as follows:
:
- First
First,
, the
the initializers initializers are evaluated are evaluated.
.
- Then
Then,
, while the
while the expression expression evaluates to evaluates to true
true, ,
the the statement statement(
(s
s)
) are executed and the
are executed and the iterators iterators are evaluated are evaluated.
.
- When the
When the expression expression becomes becomes false
false, , control is
control is transferred outside transferred outside of
- f the loop
the loop.
.
For Statement : Example1 For Statement : Example1
public class ForLoopTest public class ForLoopTest { { public static void Main public static void Main() () { { for for( (int int i i = = 1 1; ; i i <= <= 5 5; ; i i++ ++) ){ { Console Console. .WriteLine( WriteLine(“ “{0} {0}” ”, , i); i); } } } } } } Output
1 2 3 4 5
For Statement : Example2 For Statement : Example2
- Output A
Output A…
…Z alphabets on the screen using
Z alphabets on the screen using
- nly one
- nly one WriteLine
WriteLine() statement. () statement.
A A B B . . . . . . Z Z
For Statement : Example3 For Statement : Example3
- Write a program that finds a summation of a
Write a program that finds a summation of a sequence of numbers from 1 sequence of numbers from 1-
- 99 and show the
99 and show the result. result. 1+ 2+ 1+ 2+ …
…..+ 99 = 4950
..+ 99 = 4950
do/while vs. while do/while vs. while
condition
true false
Statement Statement Statement
do/while statement while statement
condition
false true
Statement Statement Statement
while vs. for while vs. for
while statement for statement
condition
false true
Statement Statement Statement
condition false true
Statement Statement Statement
iterators
Intializers
A nested loop is formed by placing an inner loop inside an outer loop. The 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 continues to execute the remaining statement(s) in the outer loop
Nested Loops
for (int outer = 1; outer <= 4; outer++) { for (int inner = 1; inner <=5; inner++) { Console.WriteLine("Outer = {0} & Inner = {1}", outer, inner); } }
Nested for loops
- Do not use the same control variable in the outer loop as in
the inner loop
Nested Loops : Example Nested Loops : Example
int outer = 1; while (outer <= 4) { int inner = 1 ; while (inner <= 5) { Console.WriteLine("Outer = {0} & Inner = {1}", outer, inner); inner = inner +1; }
- uter = outer +1;
}
Nested while loops
Nested Loops : Example Nested Loops : Example
int outer = 1; do { int inner = 1; do { Console.WriteLine("Outer = {0} & Inner = {1}", outer, inner); inner++; } while (inner < 6);
- uter++;
} while (outer < 5);
Nested Loops : Example Nested Loops : Example
Nested do/while loops
Infinite looping
No statements in the loop body can update the value of the entry condition. (E.g. omit counter = counter +1) The statement(s) in the loop body make(s) the variable become far away from the stopping condition. (E.g. counter = counter – 1)
Break Statement Break Statement
- The
The break
break statement
statement terminates terminates the the closest enclosing closest enclosing loop loop or
- r switch
switch
statement in which it appears statement in which it appears
- Control is passed to the statement that
Control is passed to the statement that follows the terminated statement follows the terminated statement
Break Statement : Example Break Statement : Example
Continue Statement Continue Statement
- The
The continue
continue statement passes control to the
statement passes control to the next iteration next iteration of the enclosing
- f the enclosing iteration