[go: up one dir, main page]

0% found this document useful (0 votes)
3 views44 pages

Week 5 C Programming

The document outlines the objectives and structured programming techniques for a computer programming course, focusing on counter-controlled and sentinel-controlled iteration. It provides a detailed case study on formulating algorithms using top-down, stepwise refinement, specifically for a class-averaging program that processes an arbitrary number of grades. Additionally, it discusses nested control statements for analyzing exam results and determining if an instructor receives a bonus based on student performance.

Uploaded by

maher sawsak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views44 pages

Week 5 C Programming

The document outlines the objectives and structured programming techniques for a computer programming course, focusing on counter-controlled and sentinel-controlled iteration. It provides a detailed case study on formulating algorithms using top-down, stepwise refinement, specifically for a class-averaging program that processes an arbitrary number of grades. Additionally, it discusses nested control statements for analyzing exam results and determining if an instructor receives a bonus based on student performance.

Uploaded by

maher sawsak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

CENG 103 – 105 – 107

Computer Programming I
Week 5
Structured Program Development – II

Dr. Yucel Tekin


Objectives
• Use counter-controlled iteration and sentinel-controlled iteration.
• Use structured programming techniques.
• Use increment, decrement and assignment operators.
Outline
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Iteration

3.10 Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 3: Nested Control Statements

3.11 Assignment Operators

3.12 Increment and Decrement Operators

3.13 Secure C Programming


3.9 Formulating Algorithms with Top-Down, Stepwise Refinement Case
Study 2: Sentinel-Controlled Iteration

• Let’s generalize the class-average problem


• Consider the following problem:
– Develop a class-averaging program that will process an arbitrary
number of grades each time the program is run.
• No indication is given of how many grades the user might input
• The program must process an arbitrary number of grades
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement Case
Study 2Values: Sentinel-Controlled Iteration—Sentinel

• Use a sentinel value to indicate “end of data entry”


• Also is called a signal value, a dummy value, or a flag value

Sentinel value
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement Case
Study 2: Sentinel-Controlled Iteration—Sentinel Values
• The user then types the sentinel value
• Sentinel-controlled iteration is often called indefinite iteration because the number of
iterations isn’t known before the loop begins executing
• Choose a sentinel value that’s not an acceptable input value
• Grades on a quiz are non-negative integers, so 1 is an acceptable sentinel
• The sentinel value 1 should not enter into the averaging calculation
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration—Top-Down, Stepwise
Refinement (1 of 2)

• Essential to developing well-structured programs


• Begin with a pseudocode representation of the top:
– Determine the class average for the quiz
• The top is a single statement that conveys the program’s overall function
• Rarely conveys a sufficient amount of detail for writing the C program
• So we begin the refinement process
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration—Top-Down, Stepwise
Refinement (2 of 2)

• Divide the top into smaller tasks listed in the order in which they need to be
performed
• This results in the following first refinement:
– Initialize variables
– Input, sum, and count the quiz grades
– Calculate and print the class average
• Here, only the sequence structure has been used
• Each refinement is a complete specification of the algorithm
• Only the level of detail varies.
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration—Second Refinement
(1 of 3)

• Next, we commit to specific variables


– a running total of the grades,
– a count of how many grades have been processed,
– a variable to receive the value of each grade as it is input and
– a variable to hold the calculated average.

• The pseudocode statement


– Initialize variables

• can be refined as
– Initialize total to zero
– Initialize counter to zero

• Only the total and counter need to be initialized


– Others are calculated or input
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration—Second Refinement
(2 of 3)

• The following pseudocode statement requires an iteration structure


– Input, sum, and count the quiz grades
• We do not know how many grades are to be processed, so we’ll use
sentinel-controlled iteration
• The refinement of the preceding pseudocode statement is
– Input the first grade (possibly the sentinel)

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)
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration—Second Refinement (3
of 3)

• The pseudocode statement


– Calculate and print the class average
• may be refined as follows:
– 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”

• Test for the possibility of division by zero


– A fatal error that, if undetected, would cause the program to crash
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement Case
Study 2: Sentinel-Controlled Iteration—Complete Second Refinement

• Initialize total to zero


Initialize counter to zero
Input the first grade (possibly the sentinel)
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”
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration—Phases in a Basic
Program

• Many programs can be divided logically into three phases:


– an initialization phase that initializes the program variables, (lines 14 – 16)
– a processing phase that inputs data values and adjusts program variables
accordingly, and (lines 18 – 32)
– a termination phase that calculates and prints the final results. (lines 33 – 45)
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement Case
Study 2: Sentinel-Controlled Iteration—Number of Pseudocode Refinements

• The pseudocode algorithm was developed after only two levels of refinement
• Sometimes more levels are necessary
• You terminate the top-down, stepwise refinement process when the pseudocode
algorithm provides sufficient detail for you to convert the pseudocode to C
• The most challenging part of solving a problem on a computer is developing the
algorithm for the solution
• Once a correct algorithm has been specified, producing a working C program
usually is straightforward
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration—Class-Average
Program for an Arbitrary Number of Grades (1 of 9)

Output 1:
• Figure 3.4 shows the C program
Enter grade, −1 to end: 75
• Although only integer grades are entered, the Enter grade, −1 to end: 94
Enter grade, −1 to end: 97
averaging calculation is likely to produce a number Enter grade, −1 to end: 88
with a decimal point Enter grade, −1 to end: 70
Enter grade, −1 to end: 64
• Type int cannot represent such a number Enter grade, −1 to end: 83
Enter grade, −1 to end: 89
• This program introduces the data type double to Enter grade, −1 to end: −1
handle numbers with decimal points—floating-point Class average is 82.50
numbers
Output 2:
• Note that lines 13 and 23 both include the sentinel
Enter grade, −1 to end: −1
value in the prompts requesting data entry No grades were entered
– This is a good practice in a sentinel-controlled
loop
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-
Controlled Iteration—Class-Average Program for an Arbitrary Number of Grades (6 of 9)

• Always Use Braces in a while Statement


– Without this while loop’s braces (lines 25 and 30), only the statement
on line 25 would be in the loop’s body
– The code would be incorrectly interpreted as
while (grade != −1)
total = total + grade; // add grade to total
counter = counter + 1; // increment counter

// get next grade from user


printf("%s", "Enter grade, −1 to end: "); // prompt for input
scanf("%d", &grade); // read next grade

– This would cause an infinite loop if the user did not input -1 as the first grade
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration—Class-Average
Program for an Arbitrary Number of Grades (7 of 9)

• Converting Between Types Explicitly and Implicitly


– Floating-point numbers can be represented by type double
– Normally, the result of the calculation total / counter (line 38) is an
integer because total and counter are both int variables
– Dividing two ints results in integer division
▪ Any fractional part of the calculation is truncated
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration—Class-Average
Program for an Arbitrary Number of Grades (7 of 9)

• Converting Between Types Explicitly


• You can produce a floating-point by creating temporary floating-point numbers
– C provides the unary cast operator to accomplish this task
▪ double average = (double) total / counter;
▪ uses the cast operator (double) to create a temporary floating-point
copy of total
▪ The value stored in total is still an integer
▪ This operation is called as Explicit Conversion
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration—Class-Average
Program for an Arbitrary Number of Grades (8 of 9)

• Converting Between Types Implicitly


– In mixed-type expressions, the compiler implicitly converts operands to ensure
that they’re of the same type
– In an expression containing the data types int and double, copies of int
operands are made and implicitly converted to type double
– This operation is called as Implicit Conversion
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 2: Sentinel-Controlled Iteration—Class-Average
Program for an Arbitrary Number of Grades (8 of 9)

• Converting Between Types Explicitly and Implicitly


– Cast operators are formed by placing parentheses around a type name
– A cast is a unary operator that takes only one operand
– Cast operators group right-to-left and have the same precedence as other unary
operators
3.9 Formulating Algorithms with Top-Down, Stepwise Refinement Case Study
2: Sentinel-Controlled Iteration—Class-Average Program for an Arbitrary
Number of Grades (9 of 9)

• Formatting Floating-Point Numbers


– printf conversion specification %.2f
– f specifies that a floating-point value will be printed
– .2 is the precision—the value will have two (2) digits to the right of the
decimal point
– If %f is used without specifying the precision, the default precision is 6 digits
to the right of the decimal point
– When floating-point values are printed with precision, the printed value is
rounded to the indicated number of decimal positions
3.10 Formulating Algorithms with Top-Down, Stepwise Refinement
Case Study 3: Nested Control Statements (1 of 9)
• We’ve seen that control statements may be stacked on top of one another (in
sequence) just as a child stacks building blocks.
• In this case study, we’ll see the only other structured way control statements may
be connected in C, namely by nesting one control statement within another.
3.10 Formulating Algorithms with Top-Down,
Stepwise Refinement Case Study 3: Nested
Control Statements (2 of 9)

• Consider the following problem statement:


– A college offers a course that prepares students for the state licensing exam for real estate
brokers. Last year, 10 of the students who completed this course took the licensing examination.
Naturally, the college wants to know how well its students did on the exam. You’ve been asked
to write a program to summarize the results. You’ve been given a list of these 10 students. Next
to each name is a 1 if the student passed the exam or a 2 if the student failed.
– Your program should analyze the results of the exam as follows:
▪ Input each test result (i.e., a 1 or a 2). Display the prompting message “Enter result” each
time the program requests another test result.
▪ Count the number of test results of each type.
▪ Display a summary of the test results indicating the number of students who passed and the
number who failed.
▪ If more than eight students passed the exam, print the message “Bonus to instructor!”
3.10 Formulating Algorithms with Top-Down,
Stepwise Refinement Case Study 3: Nested
Control Statements (3 of 9)

• After reading the problem statement carefully, we make the following observations:
– The program must process 10 test results. We’ll use a counter-controlled loop.
– Each test result is a number—either a 1 or a 2. Each time the program reads a test result, it must
determine whether the result is a 1 or a 2. We’ll test for a 1 in our algorithm. If the number is not a 1,
we’ll assume that it’s a 2. Exercise 3.27 asks you to ensure that every test result is a 1 or a 2.
– Two counters are used—one to count the number of students who passed the exam and one to
count the number of students who failed the exam.
– After the program has processed all the results, it must decide whether more than 8 students
passed the exam and, if so, print "Bonus to Instructor!".
3.10 Formulating Algorithms with Top-Down,
Stepwise Refinement Case Study 3: Nested
Control Statements (4 of 9)

• Pseudocode Representation of the Top


– Analyze exam results and decide whether instructor should receive a bonus
3.10 Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 3: Nested Control Statements (5 of 9)

• First Refinement
– Initialize variables
– Input the ten quiz grades and count passes and failures
– Print an exam-results summary and decide whether to bonus the instructor
• Further refinement is necessary.
3.10 Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 3: Nested Control Statements (6 of 9)

• Second Refinement
– Commit to specific variables
– We need counters to record the passes and failures, a counter to control
the looping process, and a variable to store the user input.
– The pseudocode statement
▪ Initialize variables
– can be refined as follows:
▪ Initialize passes to zero
▪ Initialize failures to zero
▪ Initialize student to one
– Only the counter and totals are initialized.
3.10 Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 3: Nested Control Statements (7
of 9)

• Second Refinement
– The following pseudocode statement requires a loop
▪ Input the ten quiz grades and count passes and failures
– We know there are ten exam results, so we use counter-controlled looping
– Inside the loop (that is, nested within the loop), a double-selection statement will determine
whether each exam result is a pass or a failure and will increment the appropriate counter
– The refinement of the preceding pseudocode statement is then
▪ 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
3.10 Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 3: Nested Control Statements (8 of
9)

• Second Refinement
– The pseudocode statement
▪ Print an exam-results summary and decide whether to bonus the instructor
– may be refined as follows:
▪ Print the number of passes
Print the number of failures
If more than eight students passed
Print “Bonus to instructor!”
3.10 Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 3: Nested Control Statements (9 of 9)

• Complete second refinement


Initialize passes to zero
Initialize failures to zero
Initialize student to one
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
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Bonus to instructor!”
3.10 Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 3: Nested Control Statements—
Implementing the Algorithm (4 of 5)

• Output 1

Enter Result (1=pass, 2=fail): 1


Enter Result (1=pass, 2=fail): 2
Enter Result (1=pass, 2=fail): 2
Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 2
Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 2
Passed 6
Failed 4
3.10 Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 3: Nested Control Statements—
Implementing the Algorithm (5 of 5)

• Output 2

Enter Result (1=pass, 2=fail): 1


Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 2
Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 1
Enter Result (1=pass, 2=fail): 1
Passed 9
Failed 1
Bonus to instructor!
3.11 Assignment Operators (1 of 2)
• C provides assignment operators for abbreviating assignment expressions
• c = c + 3; // abriviated form is c += 3;
• can be abbreviated with the addition assignment operator += as
• c += 3;
• The += operator adds the value of the expression on the operator’s right to
the value of the variable on the operator’s left then stores the result in the
variable on the left
3.11 Assignment Operators (2 of 2)

Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;

Assignment operator Sample expression Explanation Assigns


+= c += 7 c = c + 7 10 to c
-= m inu s s ig n e qu als
d -= 4
d mi nu s s ign e qua ls 4
d = d -4
d e qu als d mi nus s ign 4

1 to d
=
a st eri sk eq ual s
e = 5
e as te ris k e qu als 5 e = e  5
e e qu als e as ter is k 5

20 to e
/=
f or war d sla sh eq ual s
f /= 3
f fo rw ard sl as h e qu als 3
f = f / 3
f = f fo rw ard sl as h 3

2 to f
%=
p er cen t equ als

g %= 9
g pe rc ent eq ua ls 9
g = g %9
g e qu als g pe rce nt 9

3 to g
3.12 Increment and Decrement Operators (1 of 9)

• The unary increment operator (++) and the unary


decrement operator (   ) add one to and subtract
one from an integer variable, respectively
3.12 Increment and Decrement Operators (2 of 9)

Operator Sample expression Explanation


++ ++a Increment a by 1, then use the new value of a in the
expression in which a resides.
++ a++ Use the current value of a in the expression in which a
resides, then increment a by 1.

--
min us si gn mi nus s ign
-- b Decrement b by 1, then use the new value of b in the
expression in which b resides.

--
min us si gn mi nus s ign
b --
b mi nus si gn mi nus s ign
Use the current value of b in the expression in which b
resides, then decrement b by 1.
3.12 Increment and Decrement Operators (3 of 9)

• If you place ++ or -- before a variable (i.e., prefixed),

they’re referred to as the preincrement or predecrement operators

• If you place ++ or -- after a variable (i.e., postfixed),


they’re referred to as the postincrement or postdecrement operators

• By convention, unary operators should be placed next to their operands


with no intervening spaces
3.12 Increment and Decrement
Operators (4 of 9)

• Figure 3.7 demonstrates the difference between the preincrementing and the
post-incrementing versions of the ++ operator.
3.12 Increment and Decrement
Operators (5 of 9)
1. // fig03_07.c
2. // Preincrementing and postincrementing.
3. #include <stdio.h>
4.
5. // function main begins program execution
6. int main(void) {
7. // demonstrate postincrement
8. int c = 5; // assign 5 to c
9. printf("%d\n", c); // print 5
10. printf("%d\n", c++); // print 5 then postincrement
11. printf("%d\n\n", c); // print 6
12.
13. // demonstrate preincrement
14. c = 5; // assign 5 to c
15. printf("%d\n", c); // print 5
16. printf("%d\n", ++c); // preincrement then print 6
17. printf("%d\n", c); // print 6
18. } // end function main
3.12 Increment and Decrement
Operators (6 of 9)

• Output:

5
5
6

5
6
6
3.12 Increment and Decrement Operators (7 of 9)
• The three assignment statements in Fig 3.6
ure

– passes = passes + 1;
– failures = failures + 1;
– student = student + 1;
• can be written more concisely with assignment operators as
– passes += 1;
– failures += 1;
– student += 1;
• with preincrement operators as
– ++passes;
– ++failures;
– ++student;
• or with postincrement operators as
– passes++;
– failures++;
– student++;
3.12 Increment and Decrement Operators (8 of 9)

• When incrementing or decrementing a variable in a statement by itself,


the preincrement and postincrement forms have the same effect

• Only a variable name may be used as a ++ or -- operator’s operand

• C generally does not specify the order in which an operator’s operands


will evaluate

• To avoid subtle errors, the ++ and -- operators should be used only


in statements that modify exactly one variable
3.12 Increment and Decrement Operators (9 of 9)

Operators Grouping Type

++ (postfix) -- (postfix) m inu s sig n m inu s sig n


right to left postfix

+ - minus sign (type) ++ (prefix) -- (prefix) minus sign minus sign


right to left unary


asterisk, forward slash, percent / % left to right multiplicative

+
p lus , min us si gn
- left to right additive

< <= >


l eft a ngl e bra cke t, le ft an gle b rac ket e qua ls , r igh t ang le br ack et , r ig ht ang le br ac ket eq ua ls
>= left to right relational

== !=
e qua ls eq ua ls, ex cl ama ti on mar k equ als
left to right equality

?:
q ues ti on ma rk col on
right to left conditional

= += -= = /= %=
e qua ls , p lu s e qua ls , m inu s sig n equ als , ast er isk eq ua ls, f orw ard s las h equ als , per ce nt equ al s right to left assignment
Questions

You might also like