SlideShare a Scribd company logo
if-else, switch, while, for, do-while Control Statements
Conditional Statements So far statements of our programs execute sequentially one after another. What happens when we want to execute a statement depending on a condition? e.g. If there is enough money in the bank account, give the money we want to execute one statement when a condition holds and another statement when a condition does not hold? e.g. If dollar is high, sell dollar. Otherwise, buy dollar. we want to select from many statements according to one or more criteria ( selection ). e .g.  If dollar is high and euro is low, sell dollar and buy euro. If dollar is low and euro is high, sell euro and buy dollar. If both of them are high, sell both and buy YTL. You achieve conditional execution with  if-else   statements
Syntax if ( < condition > )  { <s tatement_true_1> ; ... < statement_true_N> ; } else { <s tatement_false_1> ; ... < statement_false_N> ; } If  condition  is TRUE then  s tatement_true_1 …  s tatement_true_N   are executed,  if  condition  is FALSE  statement_false_1 …  s tatement_false_N  are executed. if ( < condition > )  { <s tatement_true_1> ; ... < statement_true_N> ; } else and  statement_false’s  are optional if condition is FALSE then nothing will be executed and execution continues with the next statement in the program <condition>  must be in brackets
Another Syntax (without { }) if (< condition >) <s tatement_true> ; else <s tatement_false> ; if (< condition >)  <s tatement_true> ; Can be used when there is only one statement Not suggested (we will see why)
Flow diagram of if-else test condition true statements true next statement false false statements
if-else  example Write a program that inputs two integer numbers and displays the maximum one. Two solutions using if and else together  (Maximum1.cs) using only if (no else)  (Maximum2.cs)
Boolean type and expressions The condition in an if statement must be a Boolean expression (named for George Boole) Values are true or false bool  is a built-in value type like int, double int  degrees; bool  isHot = false; Console.WriteLine(&quot;enter temperature: “); degrees = Convert.ToInt32(Console.ReadLine()); if (degrees > 35) {    isHot = true; }
The  conditional operator  ( ?: ) can be used in place of an  if…else  statement. Console.WriteLine( grade  >= 60  ?  &quot;Passed&quot;  :  &quot;Failed&quot; ); The first operand is a  boolean  expression that evaluates to  true or  false . The second operand is the value if the expression is true The third operand is the value if the expression is false.  Conditional operator  ( ?: )
Relational Operators Relational operators are used to compare values:  They take two operands operands can be literals, variables or expressions Used for many types numeric comparisons string comparisons (alphabetical) < less than number < 5 <= less than or equal number <= 0 > greater than num1 > num2 >= greater than or equal num1 >= num2 == equality check num1 == 0 != inequality check num1 != num2
Logical operators Boolean expressions can be combined using logical operators: AND, OR, NOT In C# we use  &&  ||  !  respectively A B A || B A && B true true true true true false true false false true true false false false false false A !  A true false false true
Example Range check: between 0 and 100 (includes 0 and 100), or not?   If so, display a message saying that the number is in the range.  If not, the message should say “out of the range”. Solution 1: using logical AND operator if (num >= 0 && num <= 100) Console.Write(&quot;number is in the range&quot;); else   Console.Write(&quot;number is out of range&quot;); Solution 2: using logical AND and NOT operators if ( ! (num >= 0 && num <= 100) )   Console.Write(&quot;number is out of range&quot;); else   Console.Write(&quot;number is in the range&quot;); Solution 3: using logical OR operator if (num < 0 || num > 100) Console.Write(&quot;number is out of range&quot;); else Console.Write(&quot;number is in the range&quot;);
De Morgan’s Rules Compare solution 2 and 3 two conditions are equivalent ( ! (num >= 0 && num <= 100) ) ( num < 0 || num > 100 ) De Morgan’s Rules  (assume a and b are two boolean expressions) ! (a  &&  b)  =  !a  ||  !b ! (a  ||  b)  =  !a  &&  !b De Morgan’a Rules can be generalized to several expressions (e.g. 4 boolean expressions case) ! (a && b  && c && d ) =  !a  ||  !b   ||  !c  ||  !d ! (a || b  || c || d ) =  !a  &&  !b   &&  !c  &&  !d
Operator Precedence - Revisited Upper operator groups have precedence Operator Explanation Associativity +  -  ! plus and minus signs, logical NOT right-to-left *  /  % multiplication, division and modulus left-to-right +  - addition, subtraction left-to-right <  <=  >  >= i nequality  comparison operators left-to-right ==  != equal,  not equal  comparison left-to-right && logical and left-to-right || logical or left-to-right =  +=  -=  *=  /=  %= assignment operators right-to-left
Nested if statements if/else statements are inside other if/else statements Method to select from multiple choices Example: input a numeric grade and convert to letter grade 90 .. 100 A 80 .. 89 B 70 .. 79 C 60 .. 69 D 0  .. 59    F otherwise  F
This may be written in C# as if  ( grade >=  90  )   Console.WriteLine(  &quot;A&quot;  ); else     if  ( grade >=  80  )   Console.WriteLine(  &quot;B&quot;  );   else     if  ( grade >=  70  )   Console.WriteLine(  &quot;C&quot;  );   else     if  ( grade >=  60  )   Console.WriteLine(  &quot;D&quot;  );   else   Console.WriteLine(  &quot;F&quot;  );  Nested if statements
Most C# programmers prefer to use else if:  if  ( grade >=  90  )   Console.WriteLine(  &quot;A&quot;  ); else if  ( grade >=  80  )   Console.WriteLine(  &quot;B&quot;  ); else if  ( grade >=  70  )   Console.WriteLine(  &quot;C&quot;  ); else if  ( grade >=  60  )   Console.WriteLine(  &quot;D&quot;  ); else   Console.WriteLine(  &quot;F&quot;  );  Nested if statements (Cont.)
Short-circuit Evaluation Some subexpressions in Boolean expressions are not evaluated if the entire expression’s value is already known using the subexpression evaluated so far. Rule : Evaluate the first (leftmost) boolean subexpression. If its value is enough to judge about the value of the entire expression, then stop there. Otherwise continue evaluation towards right. if (count != 0 && scores/count < 60) {    Console.WriteLine(&quot;low average&quot;); } In this example, if the value of count is zero, then first subexpression becomes false and the second one is not evaluated.  In this way, we avoid “division by zero” error (that would cause to stop the execution of the program) Alternative method to avoid division by zero without using short-circuit evaluation: if (count != 0) {    if (scores/count < 60) {    Console.WriteLine(&quot;low average&quot;); } }
Dangling Else Problem if ( x % 2  == 0)    if ( x < 0 )  Console.WriteLine( &quot; {0}  is an  even, negative number “ , x);  else    Console.WriteLine( &quot; {0}  is an  odd number “ , x);  What does it display for x=4? The problem is that it displays “odd number” message for positive even numbers and zero. Reason is that, although indentation says the reverse, else belongs to second (inner) if else belongs to the most recent if Solution: use braces (see next slide)
Solution to Dangling Else Problem  if ( x % 2  == 0)  {   if ( x < 0 )      Console.WriteLine( &quot; {0}  is an  even, negative number “ , x);  } else  {   Console.WriteLine( &quot; {0}  is an  odd number “ , x);  } Now else belongs to the first if if – else matching rule Each else belongs to the nearest if for which there is no else and in the same compound block
switch  statement The  switch multiple-selection  statement performs different actions based on the value of an expression. Each action is associated with the value of a  constant integral expression  or a  constant string expression  that the expression may assume. Let’s see an example:  GradeBookswitch.cs
private void IncrementLetterGradeCounter( int grade ) { switch ( grade / 10 ) { case 9:  // grade was in the 90s case 10:  // grade was 100  ++aCount;  break;  // necessary to exit switch case 8:  // grade was between 80 and 89 ++bCount; break;  // exit switch case 7:  // grade was between 70 and 79 ++cCount;  break;  // exit switch case 6:  // grade was between 60 and 69 ++dCount;  break;  // exit switch default:  // grade was less than 60 ++fCount;  break;  // exit switch } } // end method IncrementLetterGradeCounter
Flow diagram of  switch
The expression after each  case  can be only a constant integral expression or a constant string expression. You can also use  null  and  character constants  which represent the integer values of characters.  The expression also can be a  constant  that contains a value which does not change for the entire application.   switch  statement
From Selection to Repetition The if statement and if/else statement allow a  block  of statements to be executed selectively: based on a condition Console.WriteLine(&quot;Please enter a non-negative number&quot;); inputnumber = Convert.ToInt32(Console.ReadLine());  if  (inputnumber < 0) { Console.WriteLine(inputnumber + &quot; is negative. Wrong Input&quot;); }  This piece of code does not ask another input number if the number is negative. The while statement repeatedly executes a block of statements while the condition is true Console.WriteLine(&quot;Please enter a non-negative number&quot;); inputnumber = Convert.ToInt32(Console.ReadLine());  while  (inputnumber < 0) { Console.WriteLine(inputnumber + &quot; is negative! Try again&quot;);   inputnumber = Convert.ToInt32(Console.ReadLine()); }
Flow diagram of while loop if (test)  while (test) {  { statement list ;  statement list ; }  } test Statement list Next statement true false test Statement list Next statement true false
Sum Example: why we need loops? We want to find the sum of 10 positive values We can write: int num1, num2, num3, num4, num5; int sum; cin >> num1 >> num2 >> num3 >> num4 >> num5; sum = num1 + num2 + num3 + num4 + num5; cin >> num1 >> num2 >> num3 >> num4 >> num5; sum += num1 + num2 + num3 + num4 + num5;
Sum Example (not in book) What if we want to compute the sum of  100 values  an undetermined number of values What we need is a program to be able to read as many values as we want and then compute the sum This is possible with  loops Good solution is to use loops. Code is developed on board. See  sum10nums.cs This type of loops are called  counting  loops number of iterations is known
Another simple example Calculate the sum of the integer numbers between 1 and 10 int sum = 0;  // this program piece int i = 1;  // calculates the sum of  while (i <= 10)  // integers between and {  // including 1 and 10 sum = sum + i; i += 1;  }
Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) {   sum = sum + i;   i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true Console.Write(sum); false 1 i sum 0 2 1
Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) {   sum = sum + i;   i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true false 2 i sum 1 3 3 Console.Write(sum);
Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) {   sum = sum + i;   i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true cout<<sum; false 3 i sum 3 4 6 Console.Write(sum);
Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) {   sum = sum + i;   i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true cout<<sum; false 10 i sum 45 11 55 Console.Write(sum);
while  loop syntax < initialization >   while (< test >)  { <s tatement1> ; ... < statementN> ; < update > }
while  loop sum example Sum of numbers from 1..10 int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } Console.Write(sum); initialization body statements update test
Counter-controlled  loop example Consider the following problem statement: A class of 10 students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz. The algorithm must input each grade, keep track of the total of all grades input, perform the averaging calculation and display the result.
Another  Counter-controlled  loop algorithm set total to zero set grade counter to one while grade counter is less than or equal to 10   prompt the user to enter the next grade   input the next grade   add the grade into the total   add one to the grade counter set the class average to the total divided by 10 display the class average
Counter-controlled  loop code ( Counting_While.sln ) // initializatio n total = 0;  // initialize the total gradeCounter = 1;  // initialize the loop counter while (  gradeCounter <= 10  )  // test { Console.Write( &quot;Enter grade: &quot; );    // prompt the user grade = Convert.ToInt32( Console.ReadLine() ); // read grade total = total + grade;  // add the grade to total gradeCounter = gradeCounter + 1;  // update } // termination phase average = total / 10; // integer division yields integer result
Sentinel-controlled  loop example Consider the following problem: Develop a class-averaging application that processes grades for an arbitrary number of students each time it is run. In this example, no indication is given of how many grades the user will enter during the application’s execution.
Sentinel-controlled  algorithm initialize total to zero initialize counter to zero prompt the user to enter the first grade input the first grade (possibly the sentinel) while the user has not yet entered the sentinel   add this grade into the running total   add one to the grade counter   prompt the user to enter the next grade   input the next grade (possibly the sentinel) if the counter is not equal to zero   set the average to the total divided by the counter   display the average else   display “No grades were entered”
Let’s see  Sentinel_While.sln // initialization phase total = 0;  // initialize total gradeCounter = 0;  // initialize loop counter // prompt for and read a grade from the user Console.Write(&quot;Enter grade or -1 to quit: &quot;); grade = Convert.ToInt32(Console.ReadLine()); // loop until sentinel value is read from the user while ( grade != -1 ) {   total = total + grade;  // add grade to total   gradeCounter = gradeCounter + 1; // increment counter   // prompt for and read the next grade from the user   Console.Write(&quot;Enter grade or -1 to quit: &quot;); grade = Convert.ToInt32(Console.ReadLine()); }
for  loop syntax compared with  while < initialization >   while (< test >)  { <s tatement1> ; ... < statementN> ; < update > } for (< initialization > ;    < test >;    < update >  )  { <s tatement1> ; ...    < statementN> ; }
Example Calculate the sum of the integer numbers between 1 and 10 int sum = 0;  // this program piece int i = 1;  // calculates the sum of  while (i <= 10)  // integers between and {  // including 1 and 10 sum = sum + i; i = i + 1;  }
Same example with  for  loop int sum = 0; int i = 1; while ( i <= 10 ) {   sum = sum + i;   i = i + 1; } int sum = 0; for ( int i=1 ;  i <= 10 ;  i=i+1 ) {   sum = sum + i; }
Scope of the counter variable in  for for ( int i=1 ;  i <= 10 ;  i=i+1 ) If the  initialization  expression declares the control variable, the control variable will not exist outside the for statement. This restriction is known as the variable’s  scope . Similarly, a local variable can be used only in the method that declares the variable and only from the point of declaration. int i; for ( i=1 ;  i <= 10 ;  i=i+1 )
for  loop syntax Comma-separated lists that enable you to use multiple initialization expressions or multiple increment expressions: for  (  int  i =  2 ; i <=  20 ; total += i ,  i +=  2  )   ;  // empty statement
Increment and Decrement Operators C# provides operators for adding or subtracting 1 from a numeric variable The unary  increment   operator ,  ++ The unary  decrement   operator ,  -- .
Bad loops for (int i = 10;  i < 5 ; i=i+1)  { Console.WriteLine(&quot;How many times do I print?&quot;); } for (int i = 10;  i >= 1 ; i=i+1)  {   Console.WriteLine(&quot;How many times do I print?&quot;); } int i = 1; while (i < 20)  {   Console.WriteLine(&quot;How many times do I print?&quot;); }
What is the problem with the code below? cannot say infinite loop for sure, depends on input number f or example,  if num is an odd number, then the loop is infinite     int num = Convert.ToInt32(Console.ReadLine()); int start = 0; while (start != num) {    start += 2;   Console.WriteLine( start); } How to fix?  You can check whether num is even before starting the loop. if (num % 2 == 0) {  while (start != num) {  start += 2;   Console.WriteLine(start); } } Infinite loops
Other Common Problems Easy to iterate one more or one less times Test each loop with the inputs that cause: zero iterations of the loop body one iteration of the loop body maximum number of iterations one less than the maximum number of iterations Use the debugger  and watch the variables.
Developing Loops Some loops are easy to develop, others are not Sometimes the proper loop test and body are hard to design Practice helps, but remember : Good design comes from experience, experience comes from bad design
Factorial n! = 1 x 2 x … x n is “n factorial” ;  used  in math, statistics  long factorial(long n) // pre: 0 <= n // post: returns n! (1 x 2 x … x n) Similar to sum, but this time we will calculate a product within the loop. At the end we will return the final product.  The loop will iterate n times, multiplying by 1, 2, …, n Suppose we use a variable called  product  to hold the  result , then  product   is n! when the loop terminates. Then we will return it at the end.
Factorial long Factorial(int num) { long product = 1; int count = 0; while (count < num)  {  count += 1; product *= count; } return product; } Issues Why did we use long? What happens if we use int instead? What happens if we initialize count to 1? See  factorial.cpp
Downward-counting loop Calculate n to the power of m: n m =nxnx…xn Example: 2 5 =2x2x2x2x2=32 int power = 1; int n, m; for (int i = m; i <= 1;  i-- ) {   power = power * n; }
Exercise: Determining if a number is Prime 1 is NOT prime, 2 is prime, 3 is prime, 5 is prime, 17 is prime, … 137, 193? W e do not need to check even numbers other than 2 (2 is a special case) To check  193 , divide it by 3, 5, 7, 9, 11, 13 Note that 14x14 = 196, so 13 largest potential factor? We can use modulus operator to check divisibility Check odd numbers as potential divisors Watch out for 2, it is a special case How far should we go to check potential divisors? up to and including  Math.Sqrt(number) + 1 If there was a bigger factor, a smaller factor would exist. And this smaller one must have been checked before. So we do not need to go beyond this limit. +1 is there to make sure that there will be no problems with precision  Write code as exercise at home
Nested loops – Example Write a function to display a perpendicular isosceles triangle of stars (perpendicular side length is parameter) e.g. if side length is 6 , the output should look like * ** *** **** ***** ****** See  drawtriangle .cs Exercise: write the same loops downward-counting this time.
Exercise: Multiplication Table On i th  line print, i*1, i*2, i*3, ... , i*i Total number of lines is an input. Display lines starting with 1. Please enter the number of lines in the multiplication table: 9 1 2  4 3  6  9 4  8  12  16 5  10  15  20  25 6  12  18  24  30  36 7  14  21  28  35  42  49 8  16  24  32  40  48  56  64 9  18  27  36  45  54  63  72  81
The  do-while  loop Similar to while loop, but the test is after the execution of the loop body The while loop may never execute, do-while loop executes  at least once < initialization > do  {   <s tatement1> ;    ...   < statementN> ;   < update > } while (< condition >); Example: Prompt for a number between 0 and 100, loop until  such a number is  entered ( user should enter at least one number) do {    Console.WriteLine(&quot;enter number in range [0..100]&quot;);   num = Convert.ToInt32(Console.ReadLine()); } while (num < 0 || num  >  100 ); Don’t forget
foreach Good with arrays or collections, we will revisit
The  break  statement causes immediate exit from a statement. When  count  is  5 , the  break  statement terminates the  for  statement. break
break  and  continue The  continue statement  skips the remaining statements in the loop body and tests whether to proceed with the next iteration of the loop. In a for statement, the increment expression executes, then the application evaluates the loop-continuation test.  Software Engineering Some programmers feel that break and continue statements violate structured programming, since the same effects are achievable with structured programming techniques.
Skipping to the next iteration when  count  is  5 .  Console.Write  skips  5  because of the  continue  statement. continue

More Related Content

PPT
Chapter 04
DOCX
C Control Statements.docx
PPT
Vb.Net 01 To 03 Summary Upload
PPT
Lecture 3
PPT
Decision Making and Branching in C
PPT
Cprogrammingprogramcontrols
PPT
Savitch Ch 03
PPT
Control structure
Chapter 04
C Control Statements.docx
Vb.Net 01 To 03 Summary Upload
Lecture 3
Decision Making and Branching in C
Cprogrammingprogramcontrols
Savitch Ch 03
Control structure

What's hot (19)

PPTX
Selection Statements in C Programming
PPTX
Conditional statements
PDF
ICP - Lecture 7 and 8
PDF
C programming decision making
PDF
Introduction
PPTX
FLOW OF CONTROL-INTRO PYTHON
PPTX
Selection statements
PDF
[C++][a] tutorial 2
PPTX
Control structure of c
PDF
Loops and conditional statements
PPTX
Decision making and branching in c programming
PPT
Control Structures
PPT
Control structures in C++ Programming Language
PPTX
C decision making and looping.
PPT
Decision making and branching
PPT
The Three Basic Selection Structures in C++ Programming Concepts
PPT
C language UPTU Unit3 Slides
PPT
Java căn bản - Chapter5
Selection Statements in C Programming
Conditional statements
ICP - Lecture 7 and 8
C programming decision making
Introduction
FLOW OF CONTROL-INTRO PYTHON
Selection statements
[C++][a] tutorial 2
Control structure of c
Loops and conditional statements
Decision making and branching in c programming
Control Structures
Control structures in C++ Programming Language
C decision making and looping.
Decision making and branching
The Three Basic Selection Structures in C++ Programming Concepts
C language UPTU Unit3 Slides
Java căn bản - Chapter5
Ad

Similar to Control All (20)

PDF
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
PPT
M C6java5
PDF
OIT 116 LOOPS AND CONDITION STATEMENTS.pdf
PPT
Lecture 3
PPT
C statements.ppt presentation in c language
PPT
Savitch ch 03
PPTX
Dti2143 chap 4 control structures aka_selection
PPTX
Dti2143 chap 4 control structures aka_selection
PPTX
Basics of Control Statement in C Languages
PPT
Decision making in C(2020-2021) statements
PPT
Savitch Ch 03
PPTX
Ch5 Selection Statements
PDF
Control statements-Computer programming
PPTX
chapter 3enejngewngjnjnfjndnennwnnefwf.pptx
PPTX
Control Structures in C
PPT
CHAPTER-3a.ppt
PDF
CIS 1403 lab 4 selection
DOC
C operators
PPT
Java Programmin: Selections
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
M C6java5
OIT 116 LOOPS AND CONDITION STATEMENTS.pdf
Lecture 3
C statements.ppt presentation in c language
Savitch ch 03
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
Basics of Control Statement in C Languages
Decision making in C(2020-2021) statements
Savitch Ch 03
Ch5 Selection Statements
Control statements-Computer programming
chapter 3enejngewngjnjnfjndnennwnnefwf.pptx
Control Structures in C
CHAPTER-3a.ppt
CIS 1403 lab 4 selection
C operators
Java Programmin: Selections
Ad

More from phanleson (20)

PDF
Learning spark ch01 - Introduction to Data Analysis with Spark
PPT
Firewall - Network Defense in Depth Firewalls
PPT
Mobile Security - Wireless hacking
PPT
Authentication in wireless - Security in Wireless Protocols
PPT
E-Commerce Security - Application attacks - Server Attacks
PPT
Hacking web applications
PPTX
HBase In Action - Chapter 04: HBase table design
PPT
HBase In Action - Chapter 10 - Operations
PPT
Hbase in action - Chapter 09: Deploying HBase
PPTX
Learning spark ch11 - Machine Learning with MLlib
PPTX
Learning spark ch10 - Spark Streaming
PPTX
Learning spark ch09 - Spark SQL
PPT
Learning spark ch07 - Running on a Cluster
PPTX
Learning spark ch06 - Advanced Spark Programming
PPTX
Learning spark ch05 - Loading and Saving Your Data
PPTX
Learning spark ch04 - Working with Key/Value Pairs
PPTX
Learning spark ch01 - Introduction to Data Analysis with Spark
PPT
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
PPT
Lecture 1 - Getting to know XML
PPTX
Lecture 4 - Adding XTHML for the Web
Learning spark ch01 - Introduction to Data Analysis with Spark
Firewall - Network Defense in Depth Firewalls
Mobile Security - Wireless hacking
Authentication in wireless - Security in Wireless Protocols
E-Commerce Security - Application attacks - Server Attacks
Hacking web applications
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 10 - Operations
Hbase in action - Chapter 09: Deploying HBase
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch10 - Spark Streaming
Learning spark ch09 - Spark SQL
Learning spark ch07 - Running on a Cluster
Learning spark ch06 - Advanced Spark Programming
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch01 - Introduction to Data Analysis with Spark
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Lecture 1 - Getting to know XML
Lecture 4 - Adding XTHML for the Web

Recently uploaded (20)

PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Electronic commerce courselecture one. Pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Spectroscopy.pptx food analysis technology
PPTX
1. Introduction to Computer Programming.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
cuic standard and advanced reporting.pdf
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Dropbox Q2 2025 Financial Results & Investor Presentation
Electronic commerce courselecture one. Pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Encapsulation_ Review paper, used for researhc scholars
Spectroscopy.pptx food analysis technology
1. Introduction to Computer Programming.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
SOPHOS-XG Firewall Administrator PPT.pptx
Programs and apps: productivity, graphics, security and other tools
Group 1 Presentation -Planning and Decision Making .pptx
Spectral efficient network and resource selection model in 5G networks
MIND Revenue Release Quarter 2 2025 Press Release
cuic standard and advanced reporting.pdf
Accuracy of neural networks in brain wave diagnosis of schizophrenia

Control All

  • 1. if-else, switch, while, for, do-while Control Statements
  • 2. Conditional Statements So far statements of our programs execute sequentially one after another. What happens when we want to execute a statement depending on a condition? e.g. If there is enough money in the bank account, give the money we want to execute one statement when a condition holds and another statement when a condition does not hold? e.g. If dollar is high, sell dollar. Otherwise, buy dollar. we want to select from many statements according to one or more criteria ( selection ). e .g. If dollar is high and euro is low, sell dollar and buy euro. If dollar is low and euro is high, sell euro and buy dollar. If both of them are high, sell both and buy YTL. You achieve conditional execution with if-else statements
  • 3. Syntax if ( < condition > ) { <s tatement_true_1> ; ... < statement_true_N> ; } else { <s tatement_false_1> ; ... < statement_false_N> ; } If condition is TRUE then s tatement_true_1 … s tatement_true_N are executed, if condition is FALSE statement_false_1 … s tatement_false_N are executed. if ( < condition > ) { <s tatement_true_1> ; ... < statement_true_N> ; } else and statement_false’s are optional if condition is FALSE then nothing will be executed and execution continues with the next statement in the program <condition> must be in brackets
  • 4. Another Syntax (without { }) if (< condition >) <s tatement_true> ; else <s tatement_false> ; if (< condition >) <s tatement_true> ; Can be used when there is only one statement Not suggested (we will see why)
  • 5. Flow diagram of if-else test condition true statements true next statement false false statements
  • 6. if-else example Write a program that inputs two integer numbers and displays the maximum one. Two solutions using if and else together (Maximum1.cs) using only if (no else) (Maximum2.cs)
  • 7. Boolean type and expressions The condition in an if statement must be a Boolean expression (named for George Boole) Values are true or false bool is a built-in value type like int, double int degrees; bool isHot = false; Console.WriteLine(&quot;enter temperature: “); degrees = Convert.ToInt32(Console.ReadLine()); if (degrees > 35) { isHot = true; }
  • 8. The conditional operator ( ?: ) can be used in place of an if…else statement. Console.WriteLine( grade >= 60 ? &quot;Passed&quot; : &quot;Failed&quot; ); The first operand is a boolean expression that evaluates to true or false . The second operand is the value if the expression is true The third operand is the value if the expression is false. Conditional operator ( ?: )
  • 9. Relational Operators Relational operators are used to compare values: They take two operands operands can be literals, variables or expressions Used for many types numeric comparisons string comparisons (alphabetical) < less than number < 5 <= less than or equal number <= 0 > greater than num1 > num2 >= greater than or equal num1 >= num2 == equality check num1 == 0 != inequality check num1 != num2
  • 10. Logical operators Boolean expressions can be combined using logical operators: AND, OR, NOT In C# we use && || ! respectively A B A || B A && B true true true true true false true false false true true false false false false false A ! A true false false true
  • 11. Example Range check: between 0 and 100 (includes 0 and 100), or not? If so, display a message saying that the number is in the range. If not, the message should say “out of the range”. Solution 1: using logical AND operator if (num >= 0 && num <= 100) Console.Write(&quot;number is in the range&quot;); else Console.Write(&quot;number is out of range&quot;); Solution 2: using logical AND and NOT operators if ( ! (num >= 0 && num <= 100) ) Console.Write(&quot;number is out of range&quot;); else Console.Write(&quot;number is in the range&quot;); Solution 3: using logical OR operator if (num < 0 || num > 100) Console.Write(&quot;number is out of range&quot;); else Console.Write(&quot;number is in the range&quot;);
  • 12. De Morgan’s Rules Compare solution 2 and 3 two conditions are equivalent ( ! (num >= 0 && num <= 100) ) ( num < 0 || num > 100 ) De Morgan’s Rules (assume a and b are two boolean expressions) ! (a && b) = !a || !b ! (a || b) = !a && !b De Morgan’a Rules can be generalized to several expressions (e.g. 4 boolean expressions case) ! (a && b && c && d ) = !a || !b || !c || !d ! (a || b || c || d ) = !a && !b && !c && !d
  • 13. Operator Precedence - Revisited Upper operator groups have precedence Operator Explanation Associativity + - ! plus and minus signs, logical NOT right-to-left * / % multiplication, division and modulus left-to-right + - addition, subtraction left-to-right < <= > >= i nequality comparison operators left-to-right == != equal, not equal comparison left-to-right && logical and left-to-right || logical or left-to-right = += -= *= /= %= assignment operators right-to-left
  • 14. Nested if statements if/else statements are inside other if/else statements Method to select from multiple choices Example: input a numeric grade and convert to letter grade 90 .. 100 A 80 .. 89 B 70 .. 79 C 60 .. 69 D 0 .. 59 F otherwise F
  • 15. This may be written in C# as if ( grade >= 90 ) Console.WriteLine( &quot;A&quot; ); else if ( grade >= 80 ) Console.WriteLine( &quot;B&quot; ); else if ( grade >= 70 ) Console.WriteLine( &quot;C&quot; ); else if ( grade >= 60 ) Console.WriteLine( &quot;D&quot; ); else Console.WriteLine( &quot;F&quot; ); Nested if statements
  • 16. Most C# programmers prefer to use else if: if ( grade >= 90 ) Console.WriteLine( &quot;A&quot; ); else if ( grade >= 80 ) Console.WriteLine( &quot;B&quot; ); else if ( grade >= 70 ) Console.WriteLine( &quot;C&quot; ); else if ( grade >= 60 ) Console.WriteLine( &quot;D&quot; ); else Console.WriteLine( &quot;F&quot; ); Nested if statements (Cont.)
  • 17. Short-circuit Evaluation Some subexpressions in Boolean expressions are not evaluated if the entire expression’s value is already known using the subexpression evaluated so far. Rule : Evaluate the first (leftmost) boolean subexpression. If its value is enough to judge about the value of the entire expression, then stop there. Otherwise continue evaluation towards right. if (count != 0 && scores/count < 60) { Console.WriteLine(&quot;low average&quot;); } In this example, if the value of count is zero, then first subexpression becomes false and the second one is not evaluated. In this way, we avoid “division by zero” error (that would cause to stop the execution of the program) Alternative method to avoid division by zero without using short-circuit evaluation: if (count != 0) { if (scores/count < 60) { Console.WriteLine(&quot;low average&quot;); } }
  • 18. Dangling Else Problem if ( x % 2 == 0) if ( x < 0 ) Console.WriteLine( &quot; {0} is an even, negative number “ , x); else Console.WriteLine( &quot; {0} is an odd number “ , x); What does it display for x=4? The problem is that it displays “odd number” message for positive even numbers and zero. Reason is that, although indentation says the reverse, else belongs to second (inner) if else belongs to the most recent if Solution: use braces (see next slide)
  • 19. Solution to Dangling Else Problem if ( x % 2 == 0) { if ( x < 0 ) Console.WriteLine( &quot; {0} is an even, negative number “ , x); } else { Console.WriteLine( &quot; {0} is an odd number “ , x); } Now else belongs to the first if if – else matching rule Each else belongs to the nearest if for which there is no else and in the same compound block
  • 20. switch statement The switch multiple-selection statement performs different actions based on the value of an expression. Each action is associated with the value of a constant integral expression or a constant string expression that the expression may assume. Let’s see an example: GradeBookswitch.cs
  • 21. private void IncrementLetterGradeCounter( int grade ) { switch ( grade / 10 ) { case 9: // grade was in the 90s case 10: // grade was 100 ++aCount; break; // necessary to exit switch case 8: // grade was between 80 and 89 ++bCount; break; // exit switch case 7: // grade was between 70 and 79 ++cCount; break; // exit switch case 6: // grade was between 60 and 69 ++dCount; break; // exit switch default: // grade was less than 60 ++fCount; break; // exit switch } } // end method IncrementLetterGradeCounter
  • 22. Flow diagram of switch
  • 23. The expression after each case can be only a constant integral expression or a constant string expression. You can also use null and character constants which represent the integer values of characters. The expression also can be a constant that contains a value which does not change for the entire application. switch statement
  • 24. From Selection to Repetition The if statement and if/else statement allow a block of statements to be executed selectively: based on a condition Console.WriteLine(&quot;Please enter a non-negative number&quot;); inputnumber = Convert.ToInt32(Console.ReadLine()); if (inputnumber < 0) { Console.WriteLine(inputnumber + &quot; is negative. Wrong Input&quot;); } This piece of code does not ask another input number if the number is negative. The while statement repeatedly executes a block of statements while the condition is true Console.WriteLine(&quot;Please enter a non-negative number&quot;); inputnumber = Convert.ToInt32(Console.ReadLine()); while (inputnumber < 0) { Console.WriteLine(inputnumber + &quot; is negative! Try again&quot;); inputnumber = Convert.ToInt32(Console.ReadLine()); }
  • 25. Flow diagram of while loop if (test) while (test) { { statement list ; statement list ; } } test Statement list Next statement true false test Statement list Next statement true false
  • 26. Sum Example: why we need loops? We want to find the sum of 10 positive values We can write: int num1, num2, num3, num4, num5; int sum; cin >> num1 >> num2 >> num3 >> num4 >> num5; sum = num1 + num2 + num3 + num4 + num5; cin >> num1 >> num2 >> num3 >> num4 >> num5; sum += num1 + num2 + num3 + num4 + num5;
  • 27. Sum Example (not in book) What if we want to compute the sum of 100 values an undetermined number of values What we need is a program to be able to read as many values as we want and then compute the sum This is possible with loops Good solution is to use loops. Code is developed on board. See sum10nums.cs This type of loops are called counting loops number of iterations is known
  • 28. Another simple example Calculate the sum of the integer numbers between 1 and 10 int sum = 0; // this program piece int i = 1; // calculates the sum of while (i <= 10) // integers between and { // including 1 and 10 sum = sum + i; i += 1; }
  • 29. Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true Console.Write(sum); false 1 i sum 0 2 1
  • 30. Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true false 2 i sum 1 3 3 Console.Write(sum);
  • 31. Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true cout<<sum; false 3 i sum 3 4 6 Console.Write(sum);
  • 32. Walkthrough of the example int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } Console.Write(sum); i<=10 sum=sum+i; i=i+1; true cout<<sum; false 10 i sum 45 11 55 Console.Write(sum);
  • 33. while loop syntax < initialization > while (< test >) { <s tatement1> ; ... < statementN> ; < update > }
  • 34. while loop sum example Sum of numbers from 1..10 int sum = 0; int i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } Console.Write(sum); initialization body statements update test
  • 35. Counter-controlled loop example Consider the following problem statement: A class of 10 students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz. The algorithm must input each grade, keep track of the total of all grades input, perform the averaging calculation and display the result.
  • 36. Another Counter-controlled loop algorithm set total to zero set grade counter to one while grade counter is less than or equal to 10 prompt the user to enter the next grade input the next grade add the grade into the total add one to the grade counter set the class average to the total divided by 10 display the class average
  • 37. Counter-controlled loop code ( Counting_While.sln ) // initializatio n total = 0; // initialize the total gradeCounter = 1; // initialize the loop counter while ( gradeCounter <= 10 ) // test { Console.Write( &quot;Enter grade: &quot; ); // prompt the user grade = Convert.ToInt32( Console.ReadLine() ); // read grade total = total + grade; // add the grade to total gradeCounter = gradeCounter + 1; // update } // termination phase average = total / 10; // integer division yields integer result
  • 38. Sentinel-controlled loop example Consider the following problem: Develop a class-averaging application that processes grades for an arbitrary number of students each time it is run. In this example, no indication is given of how many grades the user will enter during the application’s execution.
  • 39. Sentinel-controlled algorithm initialize total to zero initialize counter to zero prompt the user to enter the first grade input the first grade (possibly the sentinel) while the user has not yet entered the sentinel add this grade into the running total add one to the grade counter prompt the user to enter the next grade input the next grade (possibly the sentinel) if the counter is not equal to zero set the average to the total divided by the counter display the average else display “No grades were entered”
  • 40. Let’s see Sentinel_While.sln // initialization phase total = 0; // initialize total gradeCounter = 0; // initialize loop counter // prompt for and read a grade from the user Console.Write(&quot;Enter grade or -1 to quit: &quot;); grade = Convert.ToInt32(Console.ReadLine()); // loop until sentinel value is read from the user while ( grade != -1 ) { total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter // prompt for and read the next grade from the user Console.Write(&quot;Enter grade or -1 to quit: &quot;); grade = Convert.ToInt32(Console.ReadLine()); }
  • 41. for loop syntax compared with while < initialization > while (< test >) { <s tatement1> ; ... < statementN> ; < update > } for (< initialization > ; < test >; < update > ) { <s tatement1> ; ...    < statementN> ; }
  • 42. Example Calculate the sum of the integer numbers between 1 and 10 int sum = 0; // this program piece int i = 1; // calculates the sum of while (i <= 10) // integers between and { // including 1 and 10 sum = sum + i; i = i + 1; }
  • 43. Same example with for loop int sum = 0; int i = 1; while ( i <= 10 ) { sum = sum + i; i = i + 1; } int sum = 0; for ( int i=1 ; i <= 10 ; i=i+1 ) { sum = sum + i; }
  • 44. Scope of the counter variable in for for ( int i=1 ; i <= 10 ; i=i+1 ) If the initialization expression declares the control variable, the control variable will not exist outside the for statement. This restriction is known as the variable’s scope . Similarly, a local variable can be used only in the method that declares the variable and only from the point of declaration. int i; for ( i=1 ; i <= 10 ; i=i+1 )
  • 45. for loop syntax Comma-separated lists that enable you to use multiple initialization expressions or multiple increment expressions: for ( int i = 2 ; i <= 20 ; total += i , i += 2 ) ; // empty statement
  • 46. Increment and Decrement Operators C# provides operators for adding or subtracting 1 from a numeric variable The unary increment operator , ++ The unary decrement operator , -- .
  • 47. Bad loops for (int i = 10; i < 5 ; i=i+1) { Console.WriteLine(&quot;How many times do I print?&quot;); } for (int i = 10; i >= 1 ; i=i+1) { Console.WriteLine(&quot;How many times do I print?&quot;); } int i = 1; while (i < 20) { Console.WriteLine(&quot;How many times do I print?&quot;); }
  • 48. What is the problem with the code below? cannot say infinite loop for sure, depends on input number f or example, if num is an odd number, then the loop is infinite int num = Convert.ToInt32(Console.ReadLine()); int start = 0; while (start != num) { start += 2; Console.WriteLine( start); } How to fix? You can check whether num is even before starting the loop. if (num % 2 == 0) { while (start != num) { start += 2; Console.WriteLine(start); } } Infinite loops
  • 49. Other Common Problems Easy to iterate one more or one less times Test each loop with the inputs that cause: zero iterations of the loop body one iteration of the loop body maximum number of iterations one less than the maximum number of iterations Use the debugger and watch the variables.
  • 50. Developing Loops Some loops are easy to develop, others are not Sometimes the proper loop test and body are hard to design Practice helps, but remember : Good design comes from experience, experience comes from bad design
  • 51. Factorial n! = 1 x 2 x … x n is “n factorial” ; used in math, statistics long factorial(long n) // pre: 0 <= n // post: returns n! (1 x 2 x … x n) Similar to sum, but this time we will calculate a product within the loop. At the end we will return the final product. The loop will iterate n times, multiplying by 1, 2, …, n Suppose we use a variable called product to hold the result , then product is n! when the loop terminates. Then we will return it at the end.
  • 52. Factorial long Factorial(int num) { long product = 1; int count = 0; while (count < num) { count += 1; product *= count; } return product; } Issues Why did we use long? What happens if we use int instead? What happens if we initialize count to 1? See factorial.cpp
  • 53. Downward-counting loop Calculate n to the power of m: n m =nxnx…xn Example: 2 5 =2x2x2x2x2=32 int power = 1; int n, m; for (int i = m; i <= 1; i-- ) { power = power * n; }
  • 54. Exercise: Determining if a number is Prime 1 is NOT prime, 2 is prime, 3 is prime, 5 is prime, 17 is prime, … 137, 193? W e do not need to check even numbers other than 2 (2 is a special case) To check 193 , divide it by 3, 5, 7, 9, 11, 13 Note that 14x14 = 196, so 13 largest potential factor? We can use modulus operator to check divisibility Check odd numbers as potential divisors Watch out for 2, it is a special case How far should we go to check potential divisors? up to and including Math.Sqrt(number) + 1 If there was a bigger factor, a smaller factor would exist. And this smaller one must have been checked before. So we do not need to go beyond this limit. +1 is there to make sure that there will be no problems with precision Write code as exercise at home
  • 55. Nested loops – Example Write a function to display a perpendicular isosceles triangle of stars (perpendicular side length is parameter) e.g. if side length is 6 , the output should look like * ** *** **** ***** ****** See drawtriangle .cs Exercise: write the same loops downward-counting this time.
  • 56. Exercise: Multiplication Table On i th line print, i*1, i*2, i*3, ... , i*i Total number of lines is an input. Display lines starting with 1. Please enter the number of lines in the multiplication table: 9 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49 8 16 24 32 40 48 56 64 9 18 27 36 45 54 63 72 81
  • 57. The do-while loop Similar to while loop, but the test is after the execution of the loop body The while loop may never execute, do-while loop executes at least once < initialization > do { <s tatement1> ;    ...   < statementN> ; < update > } while (< condition >); Example: Prompt for a number between 0 and 100, loop until such a number is entered ( user should enter at least one number) do { Console.WriteLine(&quot;enter number in range [0..100]&quot;); num = Convert.ToInt32(Console.ReadLine()); } while (num < 0 || num > 100 ); Don’t forget
  • 58. foreach Good with arrays or collections, we will revisit
  • 59. The break statement causes immediate exit from a statement. When count is 5 , the break statement terminates the for statement. break
  • 60. break and continue The continue statement skips the remaining statements in the loop body and tests whether to proceed with the next iteration of the loop. In a for statement, the increment expression executes, then the application evaluates the loop-continuation test. Software Engineering Some programmers feel that break and continue statements violate structured programming, since the same effects are achievable with structured programming techniques.
  • 61. Skipping to the next iteration when count is 5 . Console.Write skips 5 because of the continue statement. continue

Editor's Notes

  • #6: Loops start with testing a condition first: if the condition is false, the loop exits and moves to the next statement. If the condition is true, the loop statements execute and move to the beginning of the loop. This continues until the condition becomes false. Hence this enables the repetition of the loop statements.
  • #27: This is not a very good approach to solve this problem because …
  • #42: Let’s compare for loop with the while loop. for loop merges the 3 pieces (initialization, condition and update) of a while loop into one line. This makes loops easier to write and read in one line.
  • #44: They look very similar and they achieve the exact same result. So you can use any of them. Note the scope of the i is during the for loop only.