+ All Categories
Home > Documents > REPETITION STATEMENTS

REPETITION STATEMENTS

Date post: 03-Jan-2016
Category:
Upload: briar-richardson
View: 32 times
Download: 0 times
Share this document with a friend
Description:
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. - PowerPoint PPT Presentation
23
REPETITION STATEMENTS while STATEMENT
Transcript
Page 1: REPETITION STATEMENTS

REPETITION STATEMENTS

while STATEMENT

Page 2: REPETITION STATEMENTS

while (condition){ statement 1 statement 2 -----} // end of while loopstatement n

The body loop (statements) execute as long as the condition is true.

Once the condition is false, statement n is executed.

1. THE WHILE STATEMENT – SYNTAX

Dr. Soha S. Zaghloul 2

Page 3: REPETITION STATEMENTS

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:

2. THE WHILE STATEMENT – WHY?

Dr. Soha S. Zaghloul 3

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 loopprintf (“\n All employees processed\n”);

Page 4: REPETITION STATEMENTS

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.

3. THE WHILE STATEMENT – COMPARE WITH “FOR”

Dr. Soha S. Zaghloul 4

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 loopprintf (“\n All employees processed\n”);

Page 5: REPETITION STATEMENTS

4. THE WHILE STATEMENT – FLOWCHART

Dr. Soha S. Zaghloul 5

count_emp < 7?

count_emp =0

scanf hoursscanf rate

pay = hours * rate

printf pay

count_emp = count_emp +1

Page 6: REPETITION STATEMENTS

What is the difference between the “while” and the “if” statements? Draw the flow chart for the following fragment code:

5. THE WHILE STATEMENT – ???

Dr. Soha S. Zaghloul 6

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 loopprintf (“\n All employees processed\n”);

Page 7: REPETITION STATEMENTS

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

6. THE WHILE STATEMENT – BE SURE…

Dr. Soha S. Zaghloul 7

Page 8: REPETITION STATEMENTS

What is the output of the following code fragment:

7. EXAMPLE 1

Dr. Soha S. Zaghloul 8

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 1

2 1 1 <= 5? true

~~1 ~~9 2

3 2 2 <= 5? true

~~2 ~~8 3

4 3 3 <= 5? true

~~3 ~~7 4

5 4 4 <= 5? true

~~4 ~~6 5

6 5 5 <= 5? true

~~5 ~~5 6

7 6 6 <= 5? false

end of loop with i = ~~6

Page 9: REPETITION STATEMENTS

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.

8. COMPUTING A SUM OR A PRODUCT IN A LOOP

Dr. Soha S. Zaghloul 9

total_pay = 0; //accumulator variable initializedcount_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 loopprintf (“\n all employees processed\n”);printf (“total payroll is sr%8.2f\n”, total_pay);

Page 10: REPETITION STATEMENTS

Let us now make the program more general by accepting the number of employees from the user.

8. COMPUTING A SUM OR A PRODUCT IN A LOOP

Dr. Soha S. Zaghloul 10

printf (“enter the number of employees\n”);scanf (“%d”, number_emp);total_pay = 0; //accumulator variable initializedcount_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 loopprintf (“\n all employees processed\n”);printf (“total payroll is sr%8.2f\n”, total_pay);

Page 11: REPETITION STATEMENTS

8. THE COMPLETE PROGRAM

Dr. Soha S. Zaghloul 11

#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

Page 12: REPETITION STATEMENTS

9. SELF-CHECK EXERCISE

Trace the previous program for the following input:

Complete the following output table:

Dr. Soha S. Zaghloul 12

Number of Employees

Emp. # hours Rate (in SR)

3 1 50 5.25

2 6 5.00

3 15 7.00

number_emp

count_emp

count_emp < number_emp

hours rate pay total_pay

Page 13: REPETITION STATEMENTS

In this example, we don’t know how many iterations will take place.

10. EXAMPLE 2

Dr. Soha S. Zaghloul 13

Write a complete program that multiplies integer data as long as the product is less than 10,000.

Condition?product < 10000

Input?Data to be multiplied

NoteWe don’t know how much they are

Type?int

How to get their values?scanf

Page 14: REPETITION STATEMENTS

10. EXAMPLE 2 (CNT’D)

Dr. Soha S. Zaghloul 14

product = 1; //initialize the loop control variablewhile (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);

Page 15: REPETITION STATEMENTS

10. EXAMPLE 2 (CNT’D) – THE COMPLETE PROGRAM

Dr. Soha S. Zaghloul 15

#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

Page 16: REPETITION STATEMENTS

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:

Dr. Soha S. Zaghloul 16

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}

Page 17: REPETITION STATEMENTS

11. VALIDATING USER ENTRY – ANOTHER SOLUTION

Dr. Soha S. Zaghloul 17

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 numberwhile (number_emp < 0) { printf (“negative number invalid; try again> ”); scanf (“%d”, &number_emp); // this updates the value of emp_number}

Page 18: REPETITION STATEMENTS

11. VALIDATING USER ENTRY IN THE EMPLOYEES EXAMPLE

Dr. Soha S. Zaghloul 18

#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

Page 19: REPETITION STATEMENTS

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

Page 20: REPETITION STATEMENTS

13. SENTINEL-CONTROLLED LOOP – EXAMPLE 3

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

Write a complete program that calculates the sum of a collection of exam scores.

Page 21: REPETITION STATEMENTS

13. SENTINEL-CONTROLLED LOOP – EXAMPLE 3

In this program, we’ll select -999 as our sentinel.

Dr. Soha S. Zaghloul 21

Write a complete program that calculates the sum of a collection of exam scores.

#include <stdio.h>#define SENTINEL -999int 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);}

Page 22: REPETITION STATEMENTS

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

Page 23: REPETITION STATEMENTS

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


Recommended