REPETITION 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

CS0004: Introduction to Programming Repetition – Do Loops.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
7. C program structure.
- SEARCHING - SORTING.  Given:  The array  The search target: the array element value we are looking for  Algorithm:  Start with the initial array.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
+ ARRAYS - SEARCHING - SORTING Dr. Soha S. Zaghloul updated by Rasha M. AL_Eidan 2015.
Nested LOOPS.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Chapter 5: Repetition and Loop Statements By: Suraya Alias.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
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.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
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.
CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes  Define the concept of repetition structure.  Specify.
Week 3.  TO PRINT NUMBERS FROM 1 TO 20  TO PRINT EVEN NUMBERS FROM 1 TO 20 2.
Repetition statements
ARRAYS.
Lesson #5 Repetition and Loops.
Decision making If.. else statement.
REPETITION CONTROL STRUCTURE
ECE Application Programming
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
CHAPTER 6: REPETITION AND LOOP STATEMENTS
Lecture 7: Repeating a Known Number of Times
Topics Introduction to Repetition Structures
Lesson #5 Repetition and Loops.
Chapter 4 Loops DDC 2133 Programming II.
Chapter 5: Control Structure
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
FUNCTIONS EXAMPLES.
Topics Introduction to Repetition Structures
The while Looping Structure
Lesson #5 Repetition and Loops.
INPUT & OUTPUT scanf & printf.
Functions.
SELECTION STATEMENTS (2)
Repetition and Loop Statements
Lec 6.
1) C program development 2) Selection structure
The while Looping Structure
The ‘while’ loop ‘round and ‘round we go.
Control Statements Loops.
Decision making If statement.
Repetition and Loop Statements
Week 6 CPS125.
REPETITION STATEMENTS
Let’s all Repeat Together
Topics Introduction to Repetition Structures
Lesson #5 Repetition and Loops.
Repetition Statements (Loops) - 2
Control Statements Loops.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
The while Looping Structure
Chapter 4 Repetition Structures
The while Looping Structure
CprE 185: Intro to Problem Solving (using C)
ICS103: Programming in C 5: Repetition and Loop Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

REPETITION STATEMENTS while STATEMENT

1. The WHILE STATEMENT – SYNTAX while (condition) { statement 1 statement 2 ----- } // end of while loop statement n The body loop (statements) execute as long as the condition is true. Once the condition is false, statement n is executed. Dr. Soha S. Zaghloul 2

2. The WHILE STATEMENT – why? When we don’t know how many iterations we need to repeat a block of statements, the “for” statement cannot be used. In this case, we can use “while”. However, a “while” statement can replace a “for” statement. Consider the following code fragment: for (count_emp= 0; count_emp < 7; count_emp++) { printf (“Hours> “); scanf (“%d”, &hours); printf (“Rate> “); scanf (“%f”, &rate); pay = hours * rate; printf (“Pay is SR%6.2f\n”, pay); } // end of for loop printf (“\n All employees processed\n”); Dr. Soha S. Zaghloul 3

3. The WHILE STATEMENT – compare with “for” The previous code fragment can be rewritten using a “while” statement as follows: The value of the loop control variable (count_emp) must change to avoid an infinite loop. count_emp = 0; while (count_emp < 7) { printf (“Hours> “); scanf (“%d”, &hours); printf (“Rate> “); scanf (“%f”, &rate); pay = hours * rate; printf (“Pay is SR%6.2f\n”, pay); count_emp++; //count_emp = count_emp + 1; } // end of while loop printf (“\n All employees processed\n”); Dr. Soha S. Zaghloul 4

4. The WHILE STATEMENT – flowchart count_emp =0 count_emp < 7? scanf hours scanf rate pay = hours * rate printf pay count_emp = count_emp +1 Dr. Soha S. Zaghloul 5

5. The WHILE STATEMENT – ??? What is the difference between the “while” and the “if” statements? Draw the flow chart for the following fragment code: count_emp = 0; while (count_emp < 7) if (count_emp < 7) { printf (“Hours> “); scanf (“%d”, &hours); printf (“Rate> “); scanf (“%f”, &rate); pay = hours * rate; printf (“Pay is SR%6.2f\n”, pay); count_emp++; //count_emp = count_emp + 1; } // end of while loop printf (“\n All employees processed\n”); Dr. Soha S. Zaghloul 6

6. The WHILE STATEMENT – be sure… The loop control variable (count_emp in the previous example) must be: Initialized before the loop (count_emp = 0) Tested before the start of each loop iteration (count_emp < 7) Updated within the loop body in each iteration (count_emp++) Dr. Soha S. Zaghloul 7

What is the output of the following code fragment: 7. Example 1 What is the output of the following code fragment: i = 0; while ( i <= 5) { printf (“%3d %3d\n”, i, 10 – i); i = i + 1; } printf (“End of loop with i= %3d”, i); iteration i i <= 5 output i = i + 1 0: initial value 0 <= 5? true 1 ~~0 ~10 2 1 <= 5? true ~~1 ~~9 3 2 <= 5? true ~~2 ~~8 4 3 <= 5? true ~~3 ~~7 5 4 <= 5? true ~~4 ~~6 6 5 <= 5? true ~~5 ~~5 7 6 <= 5? false end of loop with i = ~~6 Dr. Soha S. Zaghloul 8

8. COMPUTING A SUM or a product IN A LOOP Loops often accumulate a sum or a product by repeating an addition or a multiplication. Let us return to the first example, and calculate the total amount of the company’s payroll. total_pay = 0; //accumulator variable initialized count_emp = 0; while (count_emp < 7) { printf (“hours> “); scanf (“%d”, &hours); printf (“rate> “); scanf (“%f”, &rate); pay = hours * rate; printf (“pay is SR%6.2f\n”, pay); count_emp++; //count_emp = count_emp + 1; total_pay = total_pay + pay; // total_pay += pay; } // end of while loop printf (“\n all employees processed\n”); printf (“total payroll is sr%8.2f\n”, total_pay); Dr. Soha S. Zaghloul 9

8. COMPUTING A SUM or a product IN A LOOP Let us now make the program more general by accepting the number of employees from the user. printf (“enter the number of employees\n”); scanf (“%d”, number_emp); total_pay = 0; //accumulator variable initialized count_emp = 0; while (count_emp < number_emp) { printf (“hours> “); scanf (“%d”, &hours); printf (“rate> “); scanf (“%f”, &rate); pay = hours * rate; printf (“pay is SR%6.2f\n”, pay); count_emp++; //count_emp = count_emp + 1; total_pay = total_pay + pay; // total_pay += pay; } // end of while loop printf (“\n all employees processed\n”); printf (“total payroll is sr%8.2f\n”, total_pay); Dr. Soha S. Zaghloul 10

8. The complete program #include <stdio.h> Int main (void) { double total_pay, rate, hours, pay; int count_emp, number_emp; printf (“enter the number of employees\n”); scanf (“%d”, number_emp); total_pay = 0; //accumulator variable initialized count_emp = 0; while (count_emp < number_emp) printf (“hours> “); scanf (“%f”, &hours); printf (“rate> “); scanf (“%f”, &rate); pay = hours * rate; printf (“pay is SR%6.2f\n”, pay); count_emp++; //count_emp = count_emp + 1; total_pay = total_pay + pay; // total_pay += pay; } // end of while loop printf (“\n all employees processed\n”); printf (“total payroll is sr%8.2f\n”, total_pay); return (0); } //end of main Dr. Soha S. Zaghloul 11

Trace the previous program for the following input: 9. self-check exercise Trace the previous program for the following input: Complete the following output table: Number of Employees Emp. # hours Rate (in SR) 3 1 50 5.25 2 6 5.00 15 7.00 number_emp count_emp count_emp < number_emp hours rate pay total_pay Dr. Soha S. Zaghloul 12

In this example, we don’t know how many iterations will take place. Write a complete program that multiplies integer data as long as the product is less than 10,000. Input? Data to be multiplied Type? int How to get their values? scanf Note We don’t know how much they are Condition? product < 10000 Dr. Soha S. Zaghloul 13

10. EXAMPLE 2 (cnt’d) product = 1; //initialize the loop control variable while (product < 10000) { printf (“enter an integer\n”); scanf (“%d”, &number); product *= number; // product = product * number; } printf (“Product %d exceeds or equal to 10000\n”, product); Dr. Soha S. Zaghloul 14

10. EXAMPLE 2 (cnt’d) – the complete program #include <stdio.h> int main (void) { int number, product; product = 1; //initialize the loop control variable while (product < 10000) printf (“enter an integer\n”); scanf (“%d”, &number); product *= number; // product = product * number; } printf (“Product %d exceeds or equal to 10000\n”, product); return (0); } //end of main function Dr. Soha S. Zaghloul 15

The following code fragment is used to validate the user entry: 11. Validating user entry In order to have full control over the program, we must make sure that the user enters valid data. However, we cannot know how many times the user will enter invalid data. For example, if the program asks the user to enter a number of employees, the user may enter a negative number. The following code fragment is used to validate the user entry: printf (“enter number of employees\n”); scanf (“%d”, &number_emp); while (number_emp < 0) { printf (“negative number invalid; try again> ”); scanf (“%d”, &number_emp); // this updates the value of number_emp } Dr. Soha S. Zaghloul 16

11. Validating user entry – another solution printf (“enter number of employees\n”); scanf (“%d”, &number_emp); while (number_emp < 0) { printf (“negative number invalid; try again> ”); scanf (“%d”, &number_emp); // this updates the value of emp_number } printf (“enter number of employees\n”); scanf (“%d”, &number_emp); number_emp = -1; // or any negative number while (number_emp < 0) { printf (“negative number invalid; try again> ”); scanf (“%d”, &number_emp); // this updates the value of emp_number } Dr. Soha S. Zaghloul 17

11. Validating user entry in the employees example #include <stdio.h> Int main (void) { double total_pay, rate, hours, pay; int count_emp, number_emp; number_emp = -1; // or any negative number while (number_emp < 0) printf (“negative number invalid; try again> ”); scanf (“%d”, &emp_number); // this updates the value of emp_number } printf (“enter the number of employees\n”); scanf (“%d”, number_emp); total_pay = 0; //accumulator variable initialized count_emp = 0; while (count_emp < number_emp) printf (“hours> “); scanf (“%f”, &hours); printf (“rate> “); scanf (“%f”, &rate); pay = hours * rate; printf (“pay is SR%6.2f\n”, pay); count_emp++; //count_emp = count_emp + 1; total_pay = total_pay + pay; // total_pay += pay; } // end of while loop printf (“\n all employees processed\n”); printf (“total payroll is sr%8.2f\n”, total_pay); return (0); } //end of main Dr. Soha S. Zaghloul 18

12. sentinel-controlled loop In general, we don’t know how many data items the loop should process when it begins execution. Therefore, the program instruct the user to enter a unique data value after the last item is entered: this is called a sentinel. The loop condition will therefore check for the value of the sentinel. The sentinel value should be selected carefully. For example: If the program processes a “number of students” or “ages” or “salaries” or “hours”, etc… then the sentinel value should be -1. The sentinel value shouldn’t occur as data. Dr. Soha S. Zaghloul 19

13. sentinel-controlled loop – example 3 Write a complete program that calculates the sum of a collection of exam scores. The instructor may not know the exact number of students who took the exam. Therefore, we use a sentinel to mark the end of the data entry. The sentinel value should be a number that is impossible to occur as part of data. Therefore, we’ll make it as negative number. Since some scores may be still negative, we’ll choose a very big number in negative (very small in value). Of course, the sentinel should be the same type as the entered data. Dr. Soha S. Zaghloul 20

13. sentinel-controlled loop – example 3 Write a complete program that calculates the sum of a collection of exam scores. In this program, we’ll select -999 as our sentinel. #include <stdio.h> #define SENTINEL -999 int main (void) { int score; int sum = 0; // will be used as an accumulator printf (“Enter first score (or %d to quit)> “, SENTINEL); scanf (“%d”, &score); while (score != SENTINEL) sum += score; printf (“Enter next score (%d to quit)> “, SENTINEL); } printf (“\n Sum of exam scores is %d\n”, sum); return (0); Dr. Soha S. Zaghloul 21

14. self-check exercise (1) There are 9,870 people in a town whose population increases by 10 percent each year. Write a loop that displays the annual population. The program should stop and write a message “over population” if the population exceeds 30,000. Dr. Soha S. Zaghloul 22

14. self-check exercise (2) Write a program that calculates and prints the bill for Riyadh’s power consumption. The rates vary depending on whether the user is residential, commercial, or industrial. A code of R corresponds to a Residential, C corresponds to a Commercial, and I to Industrial. Any other code should be treated as an error. The program should read the power consumption rate in KWH (Kilowatt per Hour); then it calculates the due amount according to the following: The rate is SAR 5 per KWH for Residential, SAR 10 per KWH for Commercial and SAR 20 per KWH for Industrial. The program should display the number of users of each type. Use a sentinel to stop the data entry. Dr. Soha S. Zaghloul 23