1 / 96

CHAPTER 5: Decision Making and Looping

CHAPTER 5: Decision Making and Looping. CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon. Topics. Decision making using: Simple if selection Simple if…else selection and ?: conditional operator Handling multiple conditions Nested if…else selection if…else if selection

Télécharger la présentation

CHAPTER 5: Decision Making and Looping

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon BS (Sept 2013)

  2. Topics • Decision making using: • Simple if selection • Simple if…else selection and?: conditional operator • Handling multiple conditions • Nested if…else selection • if…else if selection • switch selection • Looping: • Design: Counter-controlled vs Sentinel-controlled • Using while loop • Using do…while loop • Using for loop • Data validation in selection and repetition structures • Combinations of control structures • Using continueand breakstatements BS (Sept 2013)

  3. Topic 1 Decision making BS (Sept 2013)

  4. Intro to Decision Making • Identify IOFC for the following problem statement: • Now, add the following three conditions/ constraints: • The value of height must be more than zero • The value of width must be more than zero • The value of length must be more than zero • Because of those conditions, before the program calculates the swimming pool’s volume, we must make it decide that all conditions have been met. • We can get our programs to make decisions of this sort using Selection Structure A swimming pool is shaped like a big box . Write a program to find the volume of the swimming pool. BS (Sept 2013)

  5. What is Selection Structure? • Take actions depending on the outcome of a condition. A condition is a logical expression that is either True or False. • General forms of selection structure (SYNTAX): 1 2 3 4 BS (Sept 2013)

  6. Topic 1-1 simple if Selection BS (Sept 2013)

  7. if Selection • Is used when a statement or a group of statements is to be executed when the logical expression of the condition is TRUE. • Syntax: • The expression of the condition must be specified using Relationaland Equality operators as follows: an expression that can return true or false if (condition) single then-statement; No semicolon at the end of the if statement. BS (Sept 2013)

  8. Example – Relational Operator1 • Case – Swimming Pool’s Volume: This algorithm is refined by making the program decide that the following condition is met: • The value of height must be more than zero Begin SET height=0.0, length=0.0, width=0.0, volume=0.0 INPUT height, length, width Begin SET height=0.0, length=0.0, width=0.0, volume=0.0 INPUT height, length, width if height > 0 COMPUTE: volume = height * length * width End if OUTPUT volume End IF height > 0? F T COMPUTE volume = height * length * width OUTPUT volume End BS (Sept 2013)

  9. Example – Relational Operator2 • Based on the refined algorithm, the program is as follows: BS (Sept 2013)

  10. if with Compound Statements • In the example that we have seen so far, there is only one statement to be executed after the if statement. • To execute more than one statement after the condition is satisfied, we have to put curly braces { }around those statements. • Syntax: • Example: if (condition) { multiple then-statements; } IF height > 0? F T OUTPUT message if (height > 0) { printf(“Calculating volume\n”); volume = height * length * width; } COMPUTE volume = height * length * width BS (Sept 2013)

  11. Example – Equality Operator • This example demonstrates the use of equality operators == and != • Note that == is different that =. Why? INPUT status char status; printf(“Enter membership status (m or p):”); scanf(“%c”, &status); if (status == ‘m’) printf(“Mechanical\n”); //end-if if (status == ‘p’) printf(“Civil\n”); //end-if IF status == ‘m’? F T OUTPUT “Mechanical” IF status == ‘p’? F T OUTPUT “Civil” BS (Sept 2013)

  12. Test Your Skill What is the output of this program? the If values entered are: • 789 and 12 • 44 and 44 • 3 and 9901 BS (Sept 2013)

  13. Topic 1-2 simple if…else selection BS (Sept 2013)

  14. Simple if..else • Is used when a statement or group of statements is to be executed when the logical expression of the condition is FALSE. • Syntax: • Example: No semicolon at the end of the if and else. if (condition) Single then-statement ; else Single else-statement ; IF height > 0? F T OUTPUT error message COMPUTE volume = height * length * width if (height> 0) volume = height* length * width; else printf(“Invalid value!\n”); BS (Sept 2013)

  15. if…else with Compound Statements • put curly braces { }around a group of statements • Syntax: Example: if (height > 0) { • printf(“Calculating volume\n”); volumne = height * length * width; } else { printf(“Invalid value!\n”); volume = 0.0; } //end-if-else if (condition) { Multiplethen-statements ; } else { Multiple else-statements; } IF height > 0? F T OUTPUT error message OUTPUT message SET volume = 0.0 COMPUTE volume = height * length * width BS (Sept 2013)

  16. Other Variations of Syntax of if…else1 With one then-statement and multiple else-statements. Syntax: if (condition) Single then-statement; else { Multiple else-statements; } IF height > 0? F T OUTPUT error message COMPUTE volume = height * length * width Example: SET volume = 0.0 if (height > 0) volume = height * length * width; else { printf(“Invalid value!\n”); volume = 0.0; flag = ‘I’; } //end-if SET flag = ‘I’ BS (Sept 2013)

  17. Other Variations of Syntax of if…else2 With multiple then-statements and one else-statement. Syntax: if (condition) { Multiple then-statements; } else single else-statement ; height > 0? F T COMPUTE volume = height * length * width Example: OUTPUT error message if (height > 0) { volume = height * length * width; flag = ‘V’; } else printf(“Invalid value!\n”); //end-if-else SET flag = ‘V’ BS (Sept 2013)

  18. Effect of Omitting { } • This what might happens if the { } are omitted int score; printf(“Enter the score: ”); scanf(“%d”,&score); if (score >= 60) { printf(“You have done very well\n”); printf(“I’ll give you a present\n”); } else printf(“You have failed the course\n”); printf(“Sorry no present for you\n”); printf(“Go and study more”); • Enter the score: 75 • You have done very well • I’ll give you a present • Sorry no present for you • Go and study more BS (Sept 2013)

  19. Test Your Skill • What happens if we omit the { }? int score; printf(“Enter the score: ”); scanf(“%d”,&score); if (score >= 60) printf(“You have done very well\n”); printf(“I’ll give you a present\n”); else { printf(“You have failed the course\n”); printf(“Sorry no present for you\n”); printf(“Go and study more”); } BS (Sept 2013)

  20. Conditional Operator ( ? : ) • Used to simplify an if…else statement. • Syntax: • The statement above is equivalent to: ( condition) ? Single then-statement : single else-statement; if (condition) singlethen-statement; else singleelse-statement; BS (Sept 2013)

  21. Example1 • if…else statement: • Conditional statement: if (total > 60) printf("Passed!!\n"); else printf("Failed!!\n"); OUTPUT “Passed” IF total > 0? F T printf("%s!!\n", total > 60?"Passed":"Failed"); OUTPUT “Failed” OR total > 60 ? printf("Passed\n") : printf(“Failed\n"); BS (Sept 2013)

  22. Example2 #include <stdio.h> void main(void) { char grade; int marks; printf("Enter marks"); scanf("%d\n", &marks); grade = (marks > 60)? 'P': 'F'; printf("\nGrade = %c\n", grade); } (marks > 60)? printf("%c",'P'): printf("%c",'F'); BS (Sept 2013)

  23. Topic 1-3 Handling multiple conditions BS (Sept 2013)

  24. Multiple Conditions – Box’s Volume Case • Re-call that in the Swimming Pool’s Volume Case problem, we have identified three conditions/ constraints: • The value of height must be more than zero • The value of width must be more than zero • The value of length must be more than zero • So far, we have handled only the first condition in these statements: • We can get our program to check multiple conditions in one logical expression, using logical operator &&. Example: if (height > 0) volume = height * length * width; if (height > 0 && length > 0 && width > 0) volume = height * length * width BS (Sept 2013)

  25. Logical Operators • To connect two conditions: BS (Sept 2013)

  26. Results of a Logical Expression • Each logical expression with multiple conditions has either True or False value, depending of the value of each condition in it. • This table lists possible result of a logical expression. Symbols A and B indicate conditions. BS (Sept 2013)

  27. Example #include<stdio.h> void main ( ) { int x=5, y=0; printf(“x=%d y=%d\n\n”, x,y); if (x>0 && y>=0) printf(“x greater than zero and ” “y greater than or equal to zero\n\n”); if (x==0 || y==0) • printf(“x and y equal to zero\n\n”); if (!(x==y)) printf(“x is not equal to y\n”); } • x=5 y=0 • x greater than zero and y greater than or equal to zero • x and y equal to zero • X is not equal to y BS (Sept 2013)

  28. Test Your Skill • What is the output of this program? If input data are: • f25 - m25- F25 - M25 • f17- m17- F17 - M17 #include<stdio.h> void main ( ) { char gender; int age=0; float loan=0.0; printf(“Enter your gender (f/F or m/M) and age:”); scanf(“%c %d”, &gender, &age); if (gender == ‘f’ && age > 20) { car_loan = 200000.00; printf(“Your car loan is %.2f\n”, loan); printf(“Well done.\n”); } } BS (Sept 2013)

  29. Evaluating Multiple Operators in a Logical Expression • The C rules for evaluating logical expression with multiple mix of operators are parentheses rule, precedence rule and associativity rule. • For a complete list, refer to Appendix C (Hanly &Koffman) BS (Sept 2013)

  30. Example • Single variable – returns Trueor False based on its value • 0 : False • 1(non-zero): True #include<stdio.h> void main ( ) { int a=8, b=-3, c=0, x=0; if(a) printf(“a=%d, !a=%d\n”, a, !a); • if(b) printf(“b=%d, !b=%d\n”, a, !a); if(c) printf(“Never gets printed\n”); else printf(“c=%d, !c=%d\n”, c, !c); if (a>b && B>c || a==b) printf(“Answer is TRUE\n”); else printf(“Answer is FALSE\n”); x = a>b || b>c && a==b; printf(“x=%d, !x=%d\n”, x, !x); } • a=8 !a=0 • b=-3 !a=0 • c=0 !c=1 • Answer is FALSE • x=1 !x=0 logical expression – returns Trueor False and the result can be assigned to an integer variable BS (Sept 2013)

  31. Topic 1-4 Nested if…else SElection BS (Sept 2013)

  32. What is Nested if..else? • if and if…else contained in another if…else selection. • However, as if…else statements become nested, programs become harder to understand. • To improve readability, indent each pair of if…else statement • Example syntax (*numbers of ‘if’s and the numbers of ‘else’s are not necessarily equal): if (outer-condition) { … //if outer is True, execute this block • if (inner1-condition) { inner1 -then-statement;}//if inner1 is True, execute this block • else { inner1-else-statement n; } //if inner1 is False, execute this block } else { … //if outer is False, execute this block • if (inner2-condition) { inner 2-then-statement; } //if inner2 is True, execute this block • else { inner2-else-statement n; } //if inner2 is False, execute this block } BS (Sept 2013)

  33. Example #include<stdio.h> void main ( ) { int day=0, time=0; printf(“Enter day and time: ”); scanf(“%d %d”, &day, &time); if (day>0 && day<=6) { if (time<=900) printf(“\nSleep\n”); else { if (time <=1900) printf(“\nWork\n”); else printf(“\nRelax\n”); } } else { if (time<=1100) printf(“\nSleep\n”); else printf(“\nHave fun\n”); } } • Enter day and time: 3 1000 • Relax • Draw a flowchart for this program BS (Sept 2013)

  34. Topic 1-5 if…else if selection BS (Sept 2013)

  35. What is if…else if selection? • One type of nested selection structure • If any one of the condition is already satisfied, the other conditions will be ignored completely. if (score >= 90) printf(“A\n”); else if (score >= 80) printf(“B\n”); else if (score >= 70) printf(“C\n”); else if (score >= 60) printf(“D\n”); else printf(“F\n”); // end-if-else-if IF score>=90? F T IF score>=80? OUTPUT “A” F T IF score>=70? F T OUTPUT “B” F T IF score>=60? OUTPUT “C” OUTPUT “F” OUTPUT “D” BS (Sept 2013)

  36. Re-writing if…else if • if..else if statements can be re-written to multiple single if statements. But this applies to condition that uses equality operator only. Example: • … • if (number == 1) • printf(“One\n”); • else if (number == 2) • printf(“Two\n”); • else if (number == 3) • printf(“Three\n”); • else • printf(“Others\n”); • … • if (number == 1) • printf(“One\n”); • if (number == 2) • printf(“Two\n”); • if (number == 3) • printf(“Three\n”); • if (number < 1 && number > 3) • printf(“Others\n”); • Enter the score: 2 • Two • Enter the score: 2 • Two BS (Sept 2013)

  37. Test Your Skill1 • What are the outputs of these programs segments? If value of score entered is 85 • What’s the effect of re-writing the above if..else if statements to multiple if statements? • if (score >= 90) • printf(“A\n”); • else if (score >= 80) • printf(“B\n”); • else if (score >= 70) • printf(“C\n”); • else if (score >= 60) • printf(“D\n”); • else • printf(“F\n”); • if (score >= 90) • printf(“A\n”); • if (score >= 80) • printf(“B\n”); • if (score >= 70) • printf(“C\n”); • if (score >= 60) • printf(“D\n”); • if (score < 60) • printf(“F\n”); BS (Sept 2013)

  38. Test Your Skill2 • Write a program that prompts the users to enter the value of Ritcher scale number (n), and print its equivalent effect as a message to the users based on the following table: BS (Sept 2013)

  39. Topic 1-6 switchSelection BS (Sept 2013)

  40. switch Statement • A switch statement is used to choose one choice from multiple cases and one default case. • Syntax: The break statement is needed so that once a case has been executed, it will skip all the other cases and go outside the switch statement. • switch (ControlVariable) • { • caseconstant 1: statement; • break; • caseconstant-n:statement; • break; • default:statement; • } The default clause is executed if the cases are not met. BS (Sept 2013)

  41. Rules for switch Statement • The valuefor ‘case’ must be integer or characteronly. • Examples: • The value checked in each ‘case’ must be constant only and not values in range. • switch (number) • { • case 1 : • num += 2; • break; • } The value for each case is followed by colon (:). • if (number==1) • num += 2; • switch (color) • { • case ‘R’ : • colorstr = ‘r’; • break; • } • if (color==‘R’) • colorstr = ‘r’; • case 1 : √ • case >= 1 : X BS (Sept 2013)

  42. Example #include <stdio.h> void main() { int num; printf(“Enter number:"); scanf("%d", &num); switch (num) { case 1: printf("Bad (D)\n");break; case 2: printf("Good (C)\n");break; case 3: printf("Excellent (A)\n");break; default: printf(“False grade\n"); } } CASE 1? F T F T CASE 2? OUTPUT “Bad (D)” F T CASE 3? OUTPUT “Good (C)” OUTPUT “False grade” OUTPUT “Excellent (A)” • Enter number: 3 • Excellent (A) • The logic of this switch selection is similar to if…else if BS (Sept 2013)

  43. Omitting break Statement If the break statement is omitted, the execution will be carried out to the next alternatives until the next break statement is found. #include <stdio.h> void main() { intmajorCode; printf("Enter your majoring code: "); scanf("%d", &majorCode); switch(majorCode) { case 1 : case 3 : case 5 : printf(“\nScience Student\n”); break; case 2 : case 4 : printf(“\nArt Student\n”); } /* end_switch */ } • Enter your majoring code: 3 • Science Student BS (Sept 2013)

  44. Example • Observe the equivalent logical expression. What can you conclude from these two program segments? • char grade; • printf(“Enter the grade you scored:”); • scanf(“%c”,&grade); • switch (grade) • { • case ‘a’: • case ‘A’: • printf(“Excellent!!\n”); • printf(“You brilliant..\n”); • break; • case ‘b’: • case ‘B’: • printf(“Job well done!!\n”); • printf(“You deserve it..\n”); • break; • default: • printf(“undefined grade\n”); • } if (grade == ‘a’ || grade == ‘A’) { printf(“Excellent!!\n”); printf(“You brilliant..\n”); } else if (grade == ‘b’ || grade == ‘B’) { printf(“Job well done!!\n”); printf(“You deserve it..\n”); } else printf(“undefined grade\n”); BS (Sept 2013)

  45. Test Your Skill • Using switchstatement, write a program that reads a positive integer number between 1 to 5, and prints the word equivalent to it. For example, if the user enters 5, the program should print the word “Five” to the screen. BS (Sept 2013)

  46. Topic 2 LOoping BS (Sept 2013)

  47. Intro to Looping • Re-call the Swimming Pool’s Volume problem: • Before this, we’ve learned to get our program to make decisions using Selection Structure. • With the program, when a user key-in values of height, length, and width the computer will output the volume for one pool. However, to calculate the volume for 100 pools, the user would need to execute this program 100 times! • So, the method by which it is possible to repeat processing without executing the program or writing the same statementsover and over is called Looping or Iteration using Repetition Structure. A swimming pool is shaped like a big box . Write a program to find the volume of the swimming pool. BS (Sept 2013)

  48. What is Repetition Structure? • Used to repeat a block of statementsa number of times (loop) until a certain condition is met without having to write the same statements multiple times. • Two design of loops: • To execute a number of instructions from the program for a finite, pre-determined number of time • Loop depends of arithmetic or conditional expression. • To execute a number of instructions from the program indifinitely until the user tells it to stop or a special condition is met • Loop depends on asentinel value. Counter-controlled Sentinel-controlled BS (Sept 2013)

  49. Types of Looping InitializationExpression while(condition){ LoopBody-statement(s) UpdateExpression } 1 while NO semicolon (;) 2 do { LoopBody-statement(s) UpdateExpression } while (condition); do…while 3 for for (InitializationExp; Condition;UpdateExp){ LoopBody-statement(s); } BS (Sept 2013) Exp = Expression

  50. Topic 2-1 Counter-controlled loop Design BS (Sept 2013)

More Related