Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
2.11
2.12
2.13
2.14
2.15
Introduction
Algorithms
Pseudocode
Control Structures
The if Selection Structure
The if/else Selection Structure
The while Repetition Structure
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
Essentials of Counter-Controlled Repetition
The for Repetition Structure
Examples Using the for Structure
2.16
2.17
2.18
2.19
2.20
2.21
2.1 Introduction
Before writing a program:
Have a thorough understanding of problem
Carefully plan your approach for solving it
Ref: http://math.hws.edu/javanotes/c1/s4.html
if(num1==num2)
cout<<num1<<"isequalto"<<num2<<endl;
Chose
one naming style and stick with it
if(num1!=num2)
Use global
variables sparingly
cout<<num1<<"isnotequalto"<<num2<<endl;
Avoid
them as much as possible
}
Comment.
Add comments to your code in plain English
that describe both
what the
code ispiece
doing
and why you
A poorly
formtated
of code
decided to do it one way and not another way Ref:
intmain()
Check return values for error conditions
{if(num1==num2)
Provide useful error messages.
cout<<num1<<"isequalto"<<num2<<endl;
Recover (or fail) gracefully.
if(num1!=num2)
http://www.kmoser.com/articles/Good_Programming_Practice
cout<<num1<<"isnotequalto
" <<num2<<endl;}
s.php
2.2
Algorithms
Algorithm
A procedure determining the
Actions to be executed
Order in which these actions are to be executed
Program control
2.3
Pseudocode
Pseudocode
Print "Passed
2.4
Control Structures
Sequential execution
Statements executed one after the other in the order written
Transfer of control
When the next statement executed is not the next one in
sequence
Selection structures
C++ has three types - if, if/else, and switch
Repetition structures
10
2.4
Control Structures
C++ keywords
Cannot be used as identifiers or variable names.
C++ Keywords
Keywordscommontothe
CandC++programming
languages
auto
continue
enum
if
short
switch
volatile
break
default
extern
int
signed
typedef
while
case
do
float
long
sizeof
union
char
double
for
register
static
unsigned
const
else
goto
return
struct
void
C++onlykeywords
asm
delete
inline
private
static_cast
try
wchar_t
bool
dynamic_cast
mutable
protected
template
typeid
catch
class
explicit false
namespacenew
public
reinterpret_cast
this
throw
typename using
const_cast
friend
operator
true
virtual
Flowchart
2.4
Control Structures
Oval symbol
indicates beginning or end of a program, or a section of code
(circles).
11
12
2.5
Selection structure
used to choose among alternative courses of action
Pseudocode example:
If students grade is greater than or equal to 60
Print Passed
13
2.5
14
2.5
true
print Passed
zero - false
nonzero - true
Example:
false
3 - 4 is true
15
2.6
if
Only performs an action if the condition is true
if/else
A different action is performed when condition is true and
when condition is false
Psuedocode
if students grade is greater than or equal to 60
print Passed
else
print Failed
C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
2000 Prentice Hall, Inc. All rights reserved.
16
2.6
grade >= 60
print Failed
C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
true
print Passed
17
2.6
grade >= 60
print Failed
true
print Passed
18
19
2.6
Compound statement:
Set of statements within a pair of braces
Example:
if ( grade >= 60 )
cout << "Passed.\n";
else {
cout << "Failed.\n";
cout << "You must take this course again.\n";
}
Without the braces,
cout << "You must take this course again.\n";
would be automatically executed
Block
20
2.6
Syntax errors
Errors caught by compiler
Logic errors
Errors which have their effect at execution time
Format
Series of case labels and an optional default case
switch ( value ){
case '1':
actions
case '2':
actions
default:
actions
}
break; // exits from statement
2000 Prentice Hall, Inc. All rights reserved.
21
default:
actions
break;
}
2000 Prentice Hall, Inc. All rights reserved.
22
case a
true
case a action(s)
break
case b action(s)
break
case z action(s)
break
false
case b
true
false
.
.
.
case z
true
false
default action(s)
2000 Prentice Hall, Inc. All rights reserved.
2.7
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
Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
24
25
2.7
false
true
product = 2 * product
2.8
Counter-controlled repetition
Loop repeated until counter reaches a certain value.
Definite repetition
Number of repetitions is known
Example
26
2.8
27
total = 0
gradeCounter = 1
While grade counter is less than or equal to ten while (gradeCounter 10)
Input the next grade
input grade
Set the class average to the total divided by ten average = total / 10
Print the class average
Print average
9 int main()
10 {
11
12
int total,
// sum of grades
gradeCounter, // number of grades entered
13
14
16
17
18
grade,
// one grade
average;
// average of grades
// initialization phase
total = 0;
// clear total
gradeCounter = 1;
// prepare to loop
21
20
// processing phase
cout << "Enter grade: ";
cin >> grade;
24
total
25
// add grade to
gradeCounter = gradeCounter + 1;
// increment
counter
26
}
// termination phase
average = total / 10;
// integer division
cout << "Class average is " << average << endl;
return 0;
33 }
1. Initialize Variables
2. Execute Loop
3. Output results
// loop 10 times
22
23
28
29
30
31
32
Outline
28
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
Outline
Program Output
29
Sentinel value
30
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
31
2.9
Processing
Inputs data values and adjusts program variables accordingly
Termination
32
2.9
Refine
33
Processing step
input grade
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel while continue
Add this grade into the running total
total = total + grade
Add one to the grade counter
gradeCounter = gradeCounter + 1
input grade
Input the next grade (possibly the sentinel)
Refine
Termination step
}
2000 Prentice Hall, Inc. All rights reserved.
Outline
1. Initialize Variables
2. Get user input
2.1 Perform Loop
34
Outline
26
27
28
29
30
31
35
// termination phase
if ( gradeCounter != 0 ) {
3. Calculate Average
average = (float )( total ) / gradeCounter;
cout << "Class average is " << setprecision( 2 )
<< setiosflags( iostream::fixed | iostream::showpoint )
32
33
34
else
35
cout << "No grades were
entered" << endl;| iostream::showpoint) - stream
=-iostream::fixed
setprecision(2) - prints only two digits
36
(float)(total) - treats totalmanipulator
as a double
decimal point.
37
return 0;
// indicate program ended past
successfully
temporarily.
38 }
iostream::fixed
- output
numbers
withinclude
a fixed number of
Programs
that use
this must
Required
because
two75
integers
truncates the
Enter
grade,
-1dividing
to end:
decimal
points.
<iomanip.h>
remainder.
Enter
grade, -1 to end: 94
Enter grade, -1 to end: 97
iostream::showpoint - forces decimal point and trailing zeros,
Enter
grade,
-1
to
end:
88
gradeCounter is an int, but it gets
to
evenpromoted
if unnecessary:
66 printed as 66.00
Enter
grade,
-1
to
end:
70
double.
Enter grade, -1 to end: 64
Program Output
| - separates multiple option.
Enter grade, -1 to end: 83
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50
36
37
Dry Run
a dry run is a mental run of an algorithm,
sometimes expressed in pseudocode, where the
computer scientist examines the algorithm's
procedures one step at a time.
(Source: Wikipedia)
2.9
38
Outline
39
Outline
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
passes = 0
Initialize passes to zero
failures = 0
Initialize failures to zero
Initialize student counter to one studentCounter = 1
2000 Prentice Hall, Inc. All rights reserved.
40
Outline
41
Refine
Input the ten quiz grades and count passes and failures
to
Refine
Print a summary of the exam results and decide if tuition should be raised
to
Print passes
Print failures
if passes > 8
Print Raise tuition
1. Initialize variables
4 int main()
5 {
6
int passes = 0,
// number of passes
failures = 0,
// number of failures
studentCounter = 1,
// student counter
result;
10
11
12
13
14
15
16
17
if ( result == 1 )
18
passes = passes + 1;
19
else
20
failures = failures + 1;
21
22
studentCounter = studentCounter + 1;
23
Outline
42
Outline
24
25
// termination phase
26
27
3. Print results
28
29
if ( passes > 8 )
30
31
32
return 0;
// successful termination
33 }
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
1
1
1
1
2
1
1
1
1
1
Program Output
43
44
can be rewritten as
variable operator= expression;
d
e
f
g
-=
*=
/=
%=
4
5
3
9
(d
(e
(f
(g
=
=
=
=
d
e
f
g
*
/
%
4)
5)
3)
9)
45
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
46
and
c++;
cout << c;
47
*
**
***
****
*****
2. Practice questions
- print a square of * using nested while loop, rows and
column are given.
- Print a triangle as above but use sentinel repetition
control
48
c = (a++) + (b++)
#include<iostream.h>
c = a + b = 5 + 6 = 11 the summation result is stored
#include<conio.h>
a++ = 6
in c before the post increments
void main(){
b++ = 7
int a = 5; int b= 6;
int c = (a++) + (b++); clrscr();
Screen Output
cout<<"\na = "<<a;
a=6
cout<<"\nb = "<<b;
b=7
cout<<"\nc = "<<c;
c = 11
x=5
y=3
z =1
z = (x++) (--y)
--y = 3
z=43=1
x++ = 5
2000 Prentice Hall, Inc. All rights reserved.
Some Examples
int k; float f;
x = 5; y = 3;
cout<<"\n\nx/y = "<<x/y;
f = x/y;
cout<<"\n\nf = x/y = "<<f;
k = (float)(x/y);
cout<<"\n\nk = (float)(x/y) = "<<k;
f = (float)(x/y);
cout<<"\n\nf = (float)(x/y)= "<<f;
cout<<"\n\n(float)(x/y) = "<<(float)(x/y);
cout<<"\n\n(float)x /y = "<<(float)x /y;
cout<<"\n\n1.5 /3 = "<< 1.5/3;
cout<<"\n\n1/3.0 = "<< 1/3.0;
getch();
}
49
Screen Output
x/y = 1
f = x/y = 1
k = (float)(x/y) = 1
f = (float)(x/y) = 1
(float)(x/y) = 1
(float)x /y = 1.6666667
1.5/3 = 0.5
1/3.0 = 0.333333
Example:
int counter =1;
//initialization
while (counter <= 10){
//repetition condition
cout << counter << endl;
++counter;
//increment
}
2000 Prentice Hall, Inc. All rights reserved.
50
Names counter
Declares counter to be an integer
Reserves space for counter in memory
Sets counter to an initial value of 1
51
52
statement
Example:
for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
No
semicolon
after last
statement
53
forkeyword Controlvariablename
Finalvalueofthe
controlvariableforthe
conditionistrue
Incrementofcontrolvari
Loop-continuation condition
54
55
statement
----------------------------------------------------------------------------------------
statement1
statement2
..
statementN
}
No
semicolon
(;) after last
expression
Example:
for( int counter = 1; counter <= 10; counter++ )
cout<<\n<< counter;
56
Recap:
false
true
product = 2 * product
57
Establish initial
value of control
variable
counter
1
counter = 1
counter <= 10
Determine if final
value of control
variable has been
reached
false
true
Cout<<\n <<counter ;
Body of loop
(this may be many
statements)
counter = 1
counter++
Increment
the control
variable
while Statement
counter <= 10
true
Cout<<\n <<counter ;
counter++
false
2000 Prentice Hall, Inc. All rights reserved.
Outline
fig04_02.c
58
is equivalent to
for ( j = 2; j <= 80; j += 5 )
Control variable
59
60
counter
1
counter = 1
counter <= 10
Determine if final
value of control
variable has been
reached
false
true
Cout<<\n <<counter ;
Body of loop
(this may be many
statements)
counter++
Increment
the control
variable
61
#include <iostream.h>
7
8
int main()
10
int sum = 0;
11
12
13
14
15
16
17
return 0;
18 }
Sum is 2550
2000 Prentice Hall, Inc. All rights reserved.
Outline
fig04_06.c (Part 1 of 2)
62
27
28
29 } /* end function main */
Outline
fig04_06.c (Part 2 of 2)
04 character places
Program Output
21 character places
Year
1
2
3
4
5
6
7
8
9
10
Amount on deposit
1050.00
1102.50
1157.63
1215.51
1276.28
1340.10
1407.10
1477.46
1551.33
1628.89
63
64
Format:
do {
statement
} while ( condition );
action(s)
true
condition
false
action(s)
true
condition
false
action(s)
condition
true
false
67
1 2 3 4
Broke out of loop at x == 5
69
fig04_12.c
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
71
|| (logical OR)
Returns true if either of its conditions are true
Expression
true && false
true || false
!false
2000 Prentice Hall, Inc. All rights reserved.
Result
false
true
true
Example:
if ( payCode == 4 )
cout << "You get a bonus!" << endl;
Sets paycode to 4
4 is nonzero, so the expression is true and a bonus is awarded,
regardless of paycode.
2000 Prentice Hall, Inc. All rights reserved.
72
Rvalues
Expressions that can only appear on the right side of an
equation
Constants, such as numbers (i.e. you cannot write 4 = x;)
73
74
Format
Series of case labels and an optional default case
switch ( value ){
case '1':
actions
case '2':
actions
default:
actions
}
75
76
default:
actions
break;
}
2000 Prentice Hall, Inc. All rights reserved.
77
true
case a action(s)
break
case b action(s)
break
case z action(s)
break
false
case b
true
false
.
.
.
case z
true
false
default action(s)
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
28
29
30
31
32
33
34
78
1. Initialize variables
2. Input data
int main()
{
int grade,
aCount
bCount
cCount
dCount
fCount
=
=
=
=
=
0,
0,
0,
0,
0;
//
//
//
//
//
//
one grade
number of
number of
number of
number of
number of
A's
B's
C's
D's
F's
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
79
3. Print results
}
}
cout <<
<<
<<
<<
<<
<<
return 0;
2000 Prentice Hall, Inc. All rights reserved.
80
Enter the letter grades.
Enter the EOF character to end input.
a
B
c
C
A
d
f
C
E
Incorrect letter grade entered. Enter a new grade.
D
A
b
Totals for each letter grade are:
A: 3
B: 2
C: 3
D: 2
F: 1
Program Output
81
Format:
do {
statement
} while ( condition );
action(s)
true
condition
false
action(s)
true
condition
false
action(s)
condition
true
false
84
Rule 3
Rule 3
Rule 3
85
Repetition
86
87
http://mathbits.com/mathbits/compsci/looping/nested.htm
2000 Prentice Hall, Inc. All rights reserved.
88
http://mathbits.com/mathbits/compsci/looping/nested.htm
2000 Prentice Hall, Inc. All rights reserved.