230 likes | 325 Views
REPETITION STATEMENTS. while STATEMENT. 1. The WHILE STATEMENT – SYNTAX. w hile (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.
E N D
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_empin 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
7. Example 1 i = 0; while ( i <= 5) { printf (“%3d %3d\n”, i, 10 – i); i = i + 1; } printf (“End of loop with i= %3d”, i); • What is the output of the following code fragment: 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; intcount_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
9. self-check exercise • Trace the previous program for the following input: • Complete the following output table: Dr. Soha S. Zaghloul 12
10. EXAMPLE 2 Write a complete program that multiplies integer data as long as the product is less than 10,000. • In this example, we don’t know how many iterations will take place. 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
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; intcount_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); scanf (“%d”, &score); } 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