Académique Documents
Professionnel Documents
Culture Documents
CS-141 Programming Fundamentals Lecture-5C Counter-Controlled Repetition Sentinel-Controlled Repetition Nested Control Structures
Jameel Ahmad Assistant Professor Jameel.ahmad@umt.edu.pk Department of Electrical Engineering University of Management and Technology
11/2/2011
Outline
3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 C Data Types Algorithms Pseudocode Control Structures The If Selection Statement The IfElse Selection Statement The While Repetition Statement Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) Formulating Algorithms with Top-down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) Formulating Algorithms with Top-down, Stepwise Refinement: Case Study 3 (Nested Control Structures) Assignment Operators Increment and Decrement Operators
11/2/2011
The while Loop The general form of the while statement is:
while (expression) statement
while is a reserved word Statement can be simple or compound Expression acts as a decision maker and is usually a logical expression Statement is called the body of the loop The parentheses are part of the syntax
false
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
11
Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input, add, and average multiple numbers using a limited number of variables For example, to add five numbers:
Declare a variable for each number, input the numbers and add the variables together Create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers
Expression provides an entry condition Statement executes if the expression initially evaluates to true Loop condition is then reevaluated Statement continues to execute until the expression is no longer true
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
10
12
11/2/2011
The while Loop (continued) Infinite loop: continues to execute endlessly Can be avoided by including statements in the loop body that assure exit condition will eventually be false
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
15 13
Statement is executed if the value of the expression is true Statement is bypassed if the value is false; program goes to the next statement
14
16
11/2/2011
If expression is true, statement1 is executed otherwise statement2 is executed statement1 and statement2 are any C statements else is a reserved word
17
19
Summary
Control structures alter normal control flow Most common control structures are selection and repetition Relational operators: ==, <, <=, >, >=, != Logical expressions evaluate to 1 (true) or 0 (false)
18
20
11/2/2011
23
Summary (continued)
Two selection structures: one-way selection and two-way selection The expression in an if or if...else structure is usually a logical expression A sequence of statements enclosed between braces, { and }, is called a compound statement or block of statements
21
22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Fig. 3.6: fig03_06.c counterClass average program with counter-controlled repetition */ #include <stdio.h> /* function main begins program execution */ int main() { entered int counter; /* number of grade to be entered next */ int grade; int total; /* grade value */ /* sum of grades input by user */
Outline
fig03_06.c (Part 1 of 2)
Lecture-5C
In this lecture, you will learn more about program control 3.8 3.9 3.10 Counter-Controlled while Repetition Sentinel-Controlled while Repetition Nested Control if-else and while Structures
int average; /* average of grades */ /* initialization phase */ total = 0; /* initialize total */ counter = 1; /* initialize loop counter */ /* processing phase */ while ( counter <= 10 ) { "%d", scanf( "%d", &grade ); total = total + grade; counter = counter + 1; } /* end while */ /* loop 10 times */ grade /* read grade from user */ /* add grade to total */ /* increment counter */ printf( "Enter grade: " ); /* prompt for input */
16 17 18 19 20 21 22 23 24
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
11/2/2011
25 26 27 28 29 30 31 32
/* termination phase */ 10; average = total / 10; /* display result */ %d\n", printf( "Class average is %d\n", average ); return 0; /* indicate program ended successfully */ /* integer division */
Outline
fig03_06.c (Part 2 of 2)
27
Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Class
grade: 98 grade: 76 grade: 71 grade: 87 grade: 83 grade: 90 grade: 57 grade: 79 grade: 82 grade: 94 average is 81
Program Output
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
26
28
Another example
#include <stdio.h> int main( void ) { int counter; /* counter for 10 repetitions */ int number; /* current number input */ int largest; /* largest number found so far */ /* get first number */ printf( "Enter the first number: " ); scanf( "%d", &largest ); counter = 2; /* loop 9 more times */ while ( counter <= 10 ) { printf( "Enter next number: " ); /* get next number */ scanf( "%d", &number );
3.9
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
11/2/2011
29
31
3.9
Formulating Algorithms with TopDown, Stepwise Refinement Refine Calculate and print the class average to
If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print No grades were entered
3.9
30
32
Formulating Algorithms with TopDown, Stepwise Refinement Refine the initialization phase from Initialize variables to:
Initialize total to zero Initialize counter to zero
3.9
3.9
Initialize total to zero Initialize counter to zero Input the first grade While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print No grades were entered
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
11/2/2011
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
/* Fig. 3.8: fig03_08.c sentinelClass average program with sentinel-controlled repetition */ #include <stdio.h> /* function main begins program execution */ int main() { int counter; int grade; int total; entered /* number of grades entered */ /* grade value */ /* sum of grades */
Outline
fig03_08.c (Part 1 of 2)
Enter Enter Enter Enter Enter Enter Enter Enter Enter Class
grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: average is 82.50
75 94 97 88 70 64 83 89 -1
Outline
Program Output
float average; /* number with decimal point for average */ /* initialization phase */ total = 0; counter = 0; /* initialize total */ /* initialize loop counter */
/* processing phase */ /* get first grade from user */ printf( "Enter grade, -1 to end: " ); "%d", scanf( "%d", &grade ); /* prompt for input */ /* read grade from user */
/* loop while sentinel value not yet read from user */ while ( grade != -1 ) { total = total + grade; counter = counter + 1; /* add grade to total */ /* increment counter */
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
printf( "Enter grade, -1 to end: " ); /* prompt for input */ scanf("%d", scanf( "%d", &grade); "%d" } /* end while */ /* termination phase */ grade /* if user entered at least one grade */ if ( counter != 0 ) { /* calculate average of all grades entered */ average = ( float ) total / counter; /* display average with two digits of precision */ is %.2f\n", printf( "Class average i s %.2f\ n", average ); } /* end if */ else { /* if no grades were entered, output message */ entered\ printf( "No grades were entered\ n" ); } /* end else */ return 0 ; /* indicate program ended successfully */ /* read next grade */
36
Outline
Problem
A college has a list of test results (1 = pass, 2 = fail) for 10 students Write a program that analyzes the results
If more than 8 students pass, print "Raise Tuition"
Notice that
The program must process 10 test results
Counter-controlled loop will be used
11/2/2011
37
39
First Refinement
Initialize variables Input the ten quiz grades and count passes and failures Print a summary of the exam results and decide if tuition should be raised
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
38
1 2 3 4 5
/* Fig. 3.10: fig03_10.c Analysis of examination results */ #include <stdio.h> /* function main begins program execution */ int main() { /* initialize variables in definitions */ int passes = 0; int student = 1; int result; /* number of passes */ /* student counter */ /* one exam result */ int failures = 0; /* number of failures */
Outline
fig03_10.c (Part 1 of 2)
3.10 Nested control structures Refine Input the ten quiz grades and count passes and failures to
While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes else Add one to failures Add one to student counter
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* process 10 students using counter-controlled loop */ counterwhile ( student <= 10 ) { /* prompt user for input and obtain value from user */ printf( "Enter result ( 1=pass,2=fail ): " ); scanf( "%d", &result ); "%d", /* if result 1, increment passes */ if ( result == 1 ) { passes = passes + 1; } /* end if */
Refine Print a summary of the exam results and decide if tuition should be raised to
Print the number of passes Print the number of failures If more than eight students passed Print Raise tuition
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
10
11/2/2011
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
else { /* otherwise, increment failures */ failures = failures + 1 ; } /* end else */ student = student + 1 ; /* increment student counter */ } /* end while */ /* termination phase; display number of passes and failures */ printf( "Passed %d \n" , passes ); printf( "Failed %d \n" , failures ); /* if more than eight students passed, print "raise tuition" */ if ( passes > 8 ) { p rintf( "Raise tuition \n" ); } /* end if */ return 0; /* indicate program ended successfully */
Outline
fig03_10.c (Part 2 of 2)
Residential Business
43
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Enter Result Enter Result Enter Result Enter Result Enter Result Enter Result Enter Result Enter Result Enter Result Enter Result Passed 6 Failed 4
(1=pass,2=fail): (1=pass,2=fail): (1=pass,2=fail): (1=pass,2=fail): (1=pass,2=fail): (1=pass,2=fail): (1=pass,2=fail): (1=pass,2=fail): (1=pass,2=fail): (1=pass,2=fail):
1 2 2 1 1 1 2 1 1 2
Outline
Program Output
Rates
For residential customer:
Enter Result (1=pass,2=fail): Enter Result (1=pass,2=fail): Enter Result (1=pass,2=fail): Enter Result (1=pass,2=fail): Enter Result (1=pass,2=fail): Enter Result (1=pass,2=fail): Enter Result (1=pass,2=fail): Enter Result (1=pass,2=fail): Enter Result (1=pass,2=fail): Enter Result (1=pass,2=fail): Passed 9 Failed 1 Raise tuition
Bill processing fee: $15.00 Basic service fee: $75.00 for first 10 connections and $5.00 for each additional connection Premium channel cost: $50.00 per channel for any number of connections
44
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Programming Example-1
1 1 1 2 1 1 1 1 1 1
Bill processing fee: $4.50 Basic service fee: $20.50 Premium channel: $7.50 per channel
For business customer:
11
11/2/2011
Requirements
Ask user for account number and customer code Assume R or r stands for residential customer and B or b stands for business customer
Programming Example-1
Program Analysis
The purpose of the program is to calculate and print billing amount Calculating the billing amount requires:
Programming Example-1
Customer for whom the billing amount is calculated (residential or business) Number of premium channels to which the customer subscribes
45
47
Input:
Customer account number Customer code Number of premium channels For business customers, number of basic service connections
Programming Example-1
Output:
Customers account number Billing amount
46
48
Programming Example-1
12
11/2/2011
Algorithm Design
Named Constants
Set precision to two decimal places Prompt user for account number and customer type If customer type is R or r
Programming Example-1 Programming Example-1
Prompt user for number of premium channels Compute and print the bill
If customer type is B or b
Prompt user for number of basic service connections and number of premium channels Compute and print the bill
49
51
Variables
Formulas
Programming Example-1
50
52
Programming Example-1
13
11/2/2011
Formulas (continued)
Billing for business customers: if (numOfBasicServConn <= 10) amountDue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + numOfPremChannels * BUS_COST_PREM_CHANNEL; else amountDue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + (numOfBasicServConn - 10) * BUS_BASIC_CONN_COST + numOfPremChannels * BUS_COST_PREM_CHANNEL;
Prompt user to enter number of premium channels Get the number of premium channels Calculate the billing amount Print account number and billing amount
Programming Example-1
53
55
Main Algorithm
1.
Output floating-point numbers in fixed decimal with decimal point and trailing zeros
Output floating-point numbers with two decimal places, set the precision to two decimal places
Programming Example-1
7.
54
56
Programming Example-1
2. 3. 4. 5.
Prompt user to enter account number Get customer account number Prompt user to enter customer code Get customer code
If customer code is b or B, Prompt user to enter number of basic service connections Get number of basic service connections Prompt user to enter number of premium channels Get number of premium channels Calculate billing amount Print account number and billing amount 8. If customer code is other than r, R, b, or B, output an error message
14
11/2/2011
Programming Example-2
A local bank in your town needs a program to calculate a customers checking account balance at the end of each month Data are stored in a file in the following form:
Programming Example-2
57
59
Transaction codes
W or w means withdrawal D or d means deposit I or i means interest paid by the bank
58
60
Programming Example-2
Account number Balance at the beginning of the month Balance at the end of the month Interest paid by the bank Total amount of deposit Number of deposits Total amount of withdrawal Number of withdrawals Service charge if any
15
11/2/2011
Programming Example-2
61
63
Program Analysis
The first entry in the input file is the account number and the beginning balance Program first reads account number and beginning balance Thereafter, each entry in the file is of the following form:
Programming Example-2
Analysis Algorithm
This discussion translates into the following algorithm:
To determine account balance, process each entry that contains transaction code and transaction amount
62
64
Programming Example-2
transactionCode transactionAmount
1. 2. 3. 4. 5.
Declare the variables Initialize the variables Get the account number and beginning balance Get transaction code and transaction amount Analyze transaction code and update the appropriate variables 6. Repeat Steps 4 and 5 for all data 7. Print the result
Programming Example-2
16
11/2/2011
Variables
Steps
1. Declare variables as discussed previously 2. Initialize variables
Programming Example-2
Read the beginning balance in the variable beginningBalance from the file and initialize the variable accountBalance to the value of the variable beginningBalance Since the data will be read from a file, you need to open input file
65
67
Named Constants
Steps (continued)
3. Get account number and starting balance
infile >> acctNumber >> beginningBalance;
Programming Example-2 Programming Example-2
66
68
Programming Example-2
17
11/2/2011
Steps (continued)
6. Repeat Steps 4 and 5 until there is no more data
Since the number of entries in the input file is not known, use an EOF-controlled while loop
Programming Example-2
7.
69
71
Main Algorithm
1. 2. 3. 4. 5. 6. Declare and initialize variables Open input file If input file does not exist, exit
Programming Example-2
If transactionCode is other than 'D', 'd', 'I', 'i', 'W', or 'w', output an error message
Programming Example-2
18
11/2/2011
73
19