0% found this document useful (0 votes)
20 views

CS101

The document discusses different types of repetition structures in programming, including while loops, counter-controlled repetition, and sentinel-controlled repetition. It provides pseudocode and C++ code examples to calculate the class average of student quiz grades using these different repetition structures. The code examples demonstrate initializing variables, inputting grades within a loop, summing the grades, counting them, and calculating the average. The document also discusses nested control structures and provides an example algorithm and code to analyze exam results and determine if tuition should be raised based on the number of students who passed.

Uploaded by

sibghat ullah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

CS101

The document discusses different types of repetition structures in programming, including while loops, counter-controlled repetition, and sentinel-controlled repetition. It provides pseudocode and C++ code examples to calculate the class average of student quiz grades using these different repetition structures. The code examples demonstrate initializing variables, inputting grades within a loop, summing the grades, counting them, and calculating the average. The document also discusses nested control structures and provides an example algorithm and code to analyze exam results and determine if tuition should be raised based on the number of students who passed.

Uploaded by

sibghat ullah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 23

Control Structures - II

Dr. Shahab Ansari


The while Repetition Structure

• Repetition structure
– Programmer specifies an action to be repeated while some condition
remains true
– Psuedocode
while there are more items on my shopping list
  Purchase next item and cross it off my list
– while loop repeated until condition becomes false.
• Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
The while Repetition Structure
• Flowchart of while loop

true
product <= 1000 product = 2 * product

false
Formulating Algorithms (Counter-Controlled
Repetition)
• Counter-controlled repetition
– Loop repeated until counter reaches a certain value.
• Definite repetition
– Number of repetitions is known
• Example
A class of ten students took a quiz. The grades (integers in the range 0
to 100) for this quiz are available to you. Determine the class average on
the quiz.
Formulating Algorithms (Counter-Controlled
Repetition)
• Pseudocode for example:
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average

• Following is the C++ code for this example


1// Fig. 2.7: fig02_07.cpp
2// Class average program with counter-controlled repetition

3#include <iostream>

5using std::cout;

6using std::cin;

7using std::endl;

9int main()

10 {

11 int total, // sum of grades

12 gradeCounter, // number of grades entered

13 grade, // one grade

14 average; // average of grades

15

16 // initialization phase

17 total = 0; // clear total

18 gradeCounter = 1; // prepare to loop

19 The counter gets incremented each


20 // processing phase
time the loop executes. Eventually,
21 while ( gradeCounter <= 10 ) { // loop 10 times
the counter causes the loop to end.
22 cout << "Enter grade: "; // prompt for input

23 cin >> grade; // input grade

24 total = total + grade; // add grade to total

25 gradeCounter = gradeCounter + 1; // increment counter

26 }

27

28 // termination phase

29 average = total / 10; // integer division

30 cout << "Class average is " << average << endl;

31

32 return 0; // indicate program ended successfully

33 }
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
Formulating Algorithms with Top-Down, Stepwise
Refinement (Sentinel-Controlled Repetition)

• Suppose the problem becomes:


Develop a class-averaging program that will process an arbitrary number
of grades each time the program is run.
– Unknown number of students - how will the program know to end?
• Sentinel value
– Indicates “end of data entry”
– Loop ends when sentinel inputted
– Sentinel value chosen so it cannot be confused with a regular input
(such as -1 in this case)
Formulating Algorithms with Top-Down, Stepwise
Refinement (Sentinel-Controlled Repetition)

• Top-down, stepwise refinement


– begin with a pseudocode representation of the top:
Determine the class average for the quiz
– Divide top into smaller tasks and list them in order:
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
Formulating Algorithms with Top-Down, Stepwise
Refinement
• Many programs can be divided into three phases:
– Initialization
• Initializes the program variables
– Processing
• Inputs data values and adjusts program variables accordingly
– Termination
• Calculates and prints the final results.
• Helps the breakup of programs for top-down refinement.
• Refine the initialization phase from
Initialize variables
to
Initialize total to zero
Initialize counter to zero
Formulating Algorithms with Top-Down, Stepwise
• Refine
Refinement
Input, sum and count the quiz grades
to
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)
• 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”
1// Fig. 2.9: fig02_09.cpp

2// Class average program with sentinel-controlled repetition.

3#include <iostream>

5using std::cout;

6using std::cin;

7using std::endl;

8using std::ios;

10 #include <iomanip>

11

12 using std::setprecision;

13 using std::setiosflags;

14

15 int main()

16 {

17 int total, // sum of grades

18 gradeCounter, // number of grades entered

19 grade; // one grade

20 double average; // number with decimal point for average

21

22 // initialization phase

23 total = 0;

24 gradeCounter = 0;

25

26 // processing phase

27 cout << "Enter grade, -1 to end: ";

28 cin >> grade;

29

30 while ( grade != -1 ) {
31 total = total + grade;

32 gradeCounter = gradeCounter + 1;

33 cout << "Enter grade, -1 to end: ";

34 cin >> grade;

35 }

36

37 // termination phase

38 if ( gradeCounter != 0 ) {

39 average = static_cast< double >( total ) / gradeCounter;

40 cout << "Class average is " << setprecision( 2 )

41 << setiosflags( ios::fixed | ios::showpoint )

42 << average << endl;

43 }

44 else

45 cout << "No grades were entered" << endl;

46

47 return 0; // indicate program ended successfully

48 }

Enter grade, -1 to end: 75


Enter grade, -1 to end: 94
Enter grade, -1 to end: 97
Enter grade, -1 to end: 88
Enter grade, -1 to end: 70
Enter grade, -1 to end: 64
Enter grade, -1 to end: 83
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50
Nested control structures
• 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".
• We can see that
– The program must process 10 test results. A counter-controlled loop will
be used.
– Two counters can be used—one to count the number of students who
passed the exam and one to count the number of students who failed
the exam.
– Each test result is a number—either a 1 or a 2. If the number is not a 1,
we assume that it is a 2.
• Top level outline:
Analyze exam results and decide if tuition should be raised
Nested control structures
• 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
• Refine
Initialize variables
to
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
• Refine
Nested control structures
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
• 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”
1// Fig. 2.11: fig02_11.cpp
2// Analysis of examination results
3#include <iostream>
4
5using std::cout;
6using std::cin;
7using std::endl;
8
9int main()
10 {
11 // initialize variables in declarations
12 int passes = 0, // number of passes
13 failures = 0, // number of failures
14 studentCounter = 1, // student counter
15 result; // one exam result
16
17 // process 10 students; counter-controlled loop
18 while ( studentCounter <= 10 ) {
19 cout << "Enter result (1=pass,2=fail): ";
20 cin >> result;
21
22 if ( result == 1 ) // if/else nested in while
23 passes = passes + 1;
24 else
25 failures = failures + 1;
26
27 studentCounter = studentCounter + 1;
28 }
29
30 // termination phase
31 cout << "Passed " << passes << endl;
32 cout << "Failed " << failures << endl;
33
34 if ( passes > 8 )
35 cout << "Raise tuition " << endl;
36
37 return 0; // successful termination
38 }

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): 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
Passed 9
Failed 1
Raise tuition
The do/while Repetition Structure
• The do/while repetition structure is similar to the
while structure,
– Condition for repetition tested after the body of the loop is
executed
• Format:
do {
  statement
} while ( condition );
action(s)
• Example (letting counter = 1):
do {
cout << counter << " "; true
condition
} while (++counter <= 10);
false
– This prints the integers from 1 to 10
• All actions are performed at least once.
Assignment Operators
• Assignment expression abbreviations
c = c + 3; can be abbreviated as c += 3; using the
addition assignment operator
• Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
• Examples of other assignment operators include:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
Increment and Decrement Operators
• Increment operator (++) - can be used instead of c += 1
• Decrement operator (--) - can be used instead of c -= 1
– Preincrement
• When the operator is used before the variable (++c or –c)
• Variable is changed, then the expression it is in is evaluated.
– Posincrement
• When the operator is used after the variable (c++ or c--)
• Expression the variable is in executes, then the variable is
changed.
• If c = 5, then
– cout << ++c; prints out 6 (c is changed before cout is executed)
– cout << c++; prints out 5 (cout is executed before the increment. c
now has the value of 6)
Increment and Decrement Operators
• When Variable is not in an expression
– Preincrementing and postincrementing have the same effect.
++c;
cout << c;
and
c++;
cout << c;
have the same effect.
References
Dietal and Dietal : How to Program C++
3rd Edition

You might also like