Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 (Loop Statements)

Similar presentations


Presentation on theme: "Chapter 5 (Loop Statements)"— Presentation transcript:

1 Chapter 5 (Loop Statements)
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 5 (Loop Statements) © CPCS 202

2 CHAPTER 5 - Loops # ATM Simulation 3 Company Payroll
1. Compound Assignment Operators 2. Repetition and Loop Statements 2a. While Statement 2b. Do-While Statement 2c. For Statement ATM Simulation 3 Company Payroll Validating Numbers Illustrate Nested Loop Bald Eagle Sightings  column shows the topics index.  column shows the programs index.

3 Compound Assignment Operators
1 Compound Assignment Operators Introduction Giving programmers alternative ways to write equations Syntax When an assignment statement in the form: variable = variable op expression; It can be written in the following format variable op= expression; If we try to increase/decrease the value of the variable by only one, we can use increment (++) or decrement (--) operators Examples x = x * 5; as same as x *= 5; x = x + 1; as same as x += 1; as same as x++;

4 Repetition and Loop Statements
2 Repetition and Loop Statements Introduction Loop repeats a group of statements until a condition is met Avoid infinity loop Each loop has a loop control variable, and three components: Initialization of the loop control variable Testing of the loop repetition condition Changing (updating) of the loop control variable Nested Loop is a concept of loops inside loops Subtopics while Statement do-while Statement for Statement

5 Loop Repetition Condition
2a 1. While Statement Introduction The statement (loop body) is executed while the condition (Loop repetition condition) is True Avoid infinity loop Syntax while (loop repetition condition) one statement or while (loop repetition condition) { statements // loop body } Loop Repetition Condition T B F loop body A C Flow Diagram for (while)

6 P1 ATM Simulation 3 Write a program that simulates an ATM, where they are three main options: Deposit Money Withdraw Money Print Balance Assume the balance in the account is Zero Use if to choose an option from the Main Menu Validate the input; if a user choose a wrong option, display an error message REPEAT the menu until the user choose Zero

7 P1 ATM Simulation 3 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. #include <stdio.h> int main(void) { int command, money, balance; /* 1. Initial the balance */ /* 2. Ask the user to choose one of the 4 options */ while (command != 0) // stop the loop if command = 0 { switch (command) { case 1: /* 2.1 Deposit Money */ case 2: /* 2.2 Withdraw Money */ case 3: /* 2.3 Print Balance */ default: } } return(0); }

8 This loop will repeat based on the User Input
ATM Simulation 3 This loop will repeat based on the User Input #include <stdio.h> int main(void) { int command, money, balance; /* 1. Initial the balance */ balance = 0; /* 2. Ask the user to choose one of the 4 options */ printf(" Main Menu\n"); printf(" \n"); printf(" 0 - Exit\n"); printf(" 1 - Deposit money\n"); printf(" 2 - Withdraw money\n"); printf(" 3 - Print balance\n"); printf("Enter command number: "); scanf("%d", &command); while (command != 0) // stop the loop if command = 0 switch (command) case 1: /* 2.1 Deposit Money */ printf("Enter deposit amount: "); scanf("%d", &money); balance = balance + money; break; case 2: /* 2.2 Withdraw Money */ printf("Enter withdraw amount: "); balance = balance - money; case 3: /* 2.3 Print Balance */ printf("Current balance = %d\n", balance); default: printf("Error\n"); } printf("\nEnter command number: "); return(0); (loop control variable) 2. Condition 1. Initialization 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 3. Updating

9 P1 ATM Simulation 3

10 P2 Company Payroll Write a program that asks a user to choose the number of employees in a company The program calculates the payroll for each employee according to the number of working hours and the rate Also, the program calculates the total amount of money for all the employees

11 This loop will repeat based on a counter
Company Payroll #include <stdio.h> int main(void) { double total_pay; /* company payroll */ int count_emp; /* current employee */ int number_emp; /* number of employees */ double hours; /* hours worked */ double rate; /* hourly rate */ double pay; /* pay for this period */ /* Get number of employees. */ printf( "Enter number of employees> "); scanf("%d", &number_emp); /* compute each employee's pay and add it to the payroll */ total_pay = 0.0; count_emp = 0; while (count_emp < number_emp) printf("Hours> "); scanf("%lf", &hours); printf("Rate > $"); scanf("%lf", &rate); /* Calculate & display the payroll for each employee */ pay = hours * rate; printf("pay is $%.2f \n\n", pay); /* Sum the payroll for all the employees */ total_pay = total_pay + pay; count_emp = count_emp + 1; } printf("All employees processed\n"); printf("Total payroll is $%8.2f \n", total_pay); return(0); 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. (loop control variable) 2. condition 1. initialization 3. Updating This loop will repeat based on a counter

12 Company Payroll P2 statement hours rate pay total_pay count_emp
number_emp ? 0.0 3 count_emp < number_emp Round 1 scanf(“%lf”,&hours); 50.0 scanf(“%lf”,&rate); 5.25 Pay = hours * rate; 262.5 total_pay = total_pay + pay; count_emp = count_emp +1; 1 Round 2 6.0 5.0 30.0 292.5 2 Round 3 15.0 7.0 105.0 397.5

13 2. Do-While Statement 2b Introduction Syntax
The statement (loop body) is executed once before checking the condition Syntax do one statement while (loop repetition condition); or do { statements // loop body } while (loop repetition condition); A loop body B condition T F C Flow Diagram for (do-while)

14 2. Do-While Statement 2b Example 2b 1. 2. 3. 4. 5. 6. 7. 8.
char letter; do { printf("Enter a letter from A through E to exit: "); scanf(“%c", &letter); } while (letter < ‘A’ || letter > ‘E’); printf(“END...\n"); 1 4-5 6 T F 8

15 P3 Validating Numbers We need a program that asks a user to choose a value from the range 10 to 20 Validate the input and display an error message if a user chooses a number out of the range, a character, or an string

16 In this case, 3 ways to validate the input
Validating Numbers #include <stdio.h> int get_int(int n_min,int n_max) { int in_val, /* input - number entered by user */ status; /* status value returned by scanf */ char skip_ch; /* character to skip */ int error; /* error flag for bad input */ /* Get data from user until in_val is in the range. */ do error=0; // No errors detected yet. /* 1. Get a number from the user. */ printf("Enter an integer in the range from %d ",n_min); printf("to %d inclusive> ", n_max); status=scanf("%d", &in_val); printf("status = %d ", status); /* 2. Validate the number */ if(status!=1) error=1; scanf("%c",&skip_ch); printf("\nskip_ch = %c\n",skip_ch); printf("invalid character >>%c>>. ",skip_ch); printf("Skipping rest of line. \n"); } else if(in_val<n_min || in_val>n_max) printf("Number %d is not in range.\n",in_val); // Skip rest of data line while(skip_ch!='\n'); } while(error); return(in_val); int main(void) int i=get_int(10,20); printf("i=%d\n",i); return(0); 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 1. not a number 2. not in the range 3. Skip the extra In this case, 3 ways to validate the input Check the main() first Go to the function

17 P3 Validating Numbers

18 3. For Statement 2c Introduction Syntax
Put the three main components in one line in the same order Syntax for (initialization expression; loop repetition condition; update expression) { statements // loop body } initial update condition T F B A loop body C Flow Diagram for (for)

19 3. For Statement 2c Example 1 Example 2 5. 6. 7.
/* display N asterisks */ for (count_star = 0; count_star < N; count_star += 1) printf(“*"); 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. int factorial(int n) { int i, product; product = 1; /* computes the product n x (n-1) x (n-2) x ... x 2 x 1 */ for (i = n; i > l; i--) product = product * i; } return (product);

20 Illustrate Nested Loop
Write a simple program that illustrates how is nested loop working. Choose the outer loop from 1 to 3 Choose the inner loop from 0 to the outer number

21 Illustrate Nested Loop
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. /* * Illustrates a pair of nested counting loops */ #include <stdio.h> int main(void) { int i, j; printf (" I J\n"); printf (" \n"); for (i = 1; i<4; ++i) /* heading of outer loop */ printf("Outer %6d\n", i); for (j=0; j<i; ++j) /* heading of inner loop */ printf(" Inner%9d\n", j); } // end of inner loop } // end of outer loop return(0); }

22 P5 Bald Eagle Sightings Write a program that calculates the number of bald eagle appears in each month for one year In each month, the user will enter the number of the bald eagles in groups, such as When a sentinel is appeared in a month, this indicates that no bald eagle will appear in that month bald eagle

23 loop based on a USER INPUT
Bald Eagle Sightings loop based on a USER INPUT Month 1 5 8 2 5 3 1 4 Month 2 loop based on a COUNTER Month 3 1 Month 12

24 Bald Eagle Sightings P5 1. #include <stdio.h> 2.
#define SENTINEL 0 #define NUM_MONTHS 12 int main(void) { int month, /* number of month being processed */ mem_sight, /* one member's sightings for this month */ sightings; /* total sightings so far for this month */ printf("BALD EAGLE SIGHTINGS\n"); for (month = 1; month <= NUM_MONTHS; ++month) sightings = 0; scanf("%d", &mem_sight); while (mem_sight !=SENTINEL) if (mem_sight >= 0) sightings += mem_sight; else printf("warning, negative count ignored\n"); } // inner while printf(" month %2d: %2d\n", month, sightings); } // outer for return(0); } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29.

25 Bald Eagle Sightings P5 P5
Click on any character to move to the next scanf, such as Space or Enter

26 Questions Q Which of the following is an infinite loop?
for (int i=20; i>=10; i--) for (int i=1; i<=10; i++) for (int i=10; i<=20; i--) for (int i=20; i>=50; i++) The statement _______, when executed in a while loop, skips the remaining statements in the body of the structure and begins the next iteration of the loop. continue break next do/more

27 hw Homework Write a program to process 5 collections of daily high temperatures using loop. Your program should count and print: the number of hot days (85 or higher), the number of pleasant days (60-84), and the number of cold days (less than 60). It should also display the category of each temperature. At the end of the run, display the average temperature. HANDWRITING IN THE HOMEWORK IS NOT ACCEPTABLE


Download ppt "Chapter 5 (Loop Statements)"

Similar presentations


Ads by Google