Chapter 5 (Loop Statements)

Slides:



Advertisements
Similar presentations
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 5: Repetition and Loop Statements Problem Solving & Program.
Advertisements

Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Chapter 5 Repetition and Loop Statements Instructor: Alkar & Demirer.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Topic 6 – Repetition and Loops. CISC 105 – Topic 6 Program Repetition Repetition refers to the repeats of certain program statements within a program.
1 CSE1301 Computer Programming Lecture 10: Iteration (Part 1)
CS 201 Selection Structures (2) and Repetition
CS 117 Spring 2002 Repetition Hanly Chapter 4 Friedman-Koffman Chapter 5.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Chapter 5 Repetition and Loop Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Unit 4 Repetition and Loops. Key Concepts Flowcharting a loop Types of loops Counter-controlled loops while statement Compound assignment operator for.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
1 ICS103 Programming in C Ch5: Repetition and Loop Statements.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
Chapter 5 Repetition and Loop Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville,
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
Iterations Very Useful: Ability to repeat a block of code Example:
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Chapter 5: Repetition and Loop Statements By: Suraya Alias.
H1-1 University of Washington Computer Programming I Lecture 9: Iteration © 2000 UW CSE.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
BY ILTAF MEHDI (MCS, MCSE, CCNA)1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI (MCS, MCSE, CCNA)2 Chapter No: 04 “Loops”
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
CISC105 – General Computer Science Class 4 – 06/14/2006.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
PGT C Programming1 Week 4 – Repetition Structures / Loops.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.
C++ Programming: CS102 LOOP. Not everything that can be counted counts, and not every thing that counts can be counted. −Albert Einstein Who can control.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes  Define the concept of repetition structure.  Specify.
Repetition statements
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
CHAPTER 6: REPETITION AND LOOP STATEMENTS
ICS103 Programming in C Lecture 7: Repetition Structures
Chapter 4 (Conditional Statements)
Chapter 4 - Program Control
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
REPETITION STATEMENTS
JavaScript: Control Statements I
Control Structures Lecture 7.
Looping.
Repetition and Loop Statements
Chapter 4 - Program Control
Repetition and Loop Statements
Chapter 5: Control Structures II (Repetition)
Chapter 4 Repetition Structures
ICS103: Programming in C 5: Repetition and Loop Statements
Presentation transcript:

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 12-10-1429

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.

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++;

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

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)

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

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); }

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

P1 ATM Simulation 3

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

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

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

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)

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

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

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

P3 Validating Numbers

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)

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);

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

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); }

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 5 6 2 3 13 2 When a sentinel is appeared in a month, this indicates that no bald eagle will appear in that month bald eagle

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

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.

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

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

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