Professional Documents
Culture Documents
2.1 Introduction
Ref: http://math.hws.edu/javanotes/c1/s4.html
• Use global
if ( num1 != num2
variables )
sparingly
– Avoid them
cout << num1
as much << " is
as possible not equal to " << num2 << endl;
• Comment.
} Add comments to your code in plain English
that describe both what formtated
A poorly the code is doing
piece and why you
of code
decided to do it one way and not another way Ref:
int main()
• Check return values for error conditions
{ if (num1==num2)
• Provide useful error messages.
cout<<num1<<" is equal to "<<num2<<endl;
• Recover (or fail) gracefully.
if (num1!=num2)
http://www.kmoser.com/articles/Good_Programming_Practic
cout<<num1<<" is not equal to " <<num2<<endl; }
es.php
2000 Prentice Hall, Inc. All rights reserved.
6
2.2 Algorithms
2.3 Pseudocode
• Pseudocode
– Artificial, informal language used to develop algorithms
– Similar to everyday English
– Not actually executed on computers
– Allows us to “think out” a program before writing the code
for it
– Easy to convert into a corresponding C++ program
– Consists only of executable statements
Example:
If student’s grade is greater than or equal to 60
Print "Passed“
• C++ keywords
– Cannot be used as identifiers or variable names.
C++ Keyw o rd s
• Selection structure
– used to choose among alternative courses of action
– Pseudocode example:
If student’s grade is greater than or equal to 60
Print “Passed”
– If the condition is true
• print statement executed and program goes on to next
statement
– If the condition is false
• print statement is ignored and the program goes onto the next
statement
– Indenting makes programs easier to read
• C++ ignores whitespace characters
false true
grade >= 60
• C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
false true
grade >= 60
• Syntax errors
– Errors caught by compiler
• Logic errors
– Errors which have their effect at execution time
• Non-fatal logic errors
– program runs, but has incorrect output
• Fatal logic errors
– program exits prematurely
case '3':
case '4':
actions /* one or more statements */
break;
default:
actions /* one or more statements */
break;
}
true
case a case a action(s) break
false
true
case b case b action(s) break
false
.
.
.
true
case z case z action(s) break
false
default action(s)
• 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;
true
product <= 1000 product = 2 * product
false
While grade counter is less than or equal to ten while (gradeCounter ≤ 10)
Input the next grade input grade
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
Dry Run
• 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.
• Refine
Print a summary of the exam results and decide if tuition should be raised
to
Print the number of passes Print passes
Print the number of failures Print failures
If more than eight students passed if passes > 8
Print “Raise tuition” Print “Raise tuition
2000 Prentice Hall, Inc. All rights reserved.
1 // Fig. 2.11: fig02_11.cpp 42
2 // Analysis of examination results Outline
3 #include <iostream.h>
4 int main() 1. Initialize variables
5 {
6 // initialize variables in declarations 2. Input data and
count passes/failures
7 int passes = 0, // number of passes
8 failures = 0, // number of failures
9 studentCounter = 1, // student counter
10 result; // one exam result
11
12 // process 10 students; counter-controlled loop
13 while ( studentCounter <= 10 ) {
14 cout << "Enter result (1=pass,2=fail): ";
15 cin >> result;
16
17 if ( result == 1 ) // if/else nested in while
18 passes = passes + 1;
19 else
20 failures = failures + 1;
21
22 studentCounter = studentCounter + 1;
23 }
cout << c;
have the same effect.
Loop-continuation condition
• Example:
for( int counter = 1; counter <= 10; counter++ )
cout<<“\n“<< counter;
– Prints the integers from one to ten
true
product <= 1000 product = 2 * product
false
true
counter <= 10 Cout<<“\n” <<counter ; counter++
Increment
the control
Determine if final false Body of loop variable
value of control (this may be many
variable has been statements)
reached
counter = 1
Initialization placed before
the while statement
while Statement
true
counter <= 10 Cout<<“\n” <<counter ;
counter++
false
Counter integrated into the
2000 Prentice Hall, Inc. All rights reserved. body of while statement
1 /* Fig. 4.2: fig04_02.c 58
2 Counter-controlled repetition with the for statement */ Outline
3 #include <iostream.h>
fig04_02.c
4
5 /* function main begins program execution */
6 int main()
7 {
8 int counter; /* define counter */
9
10 /* initialization, repetition condition, and increment
11 are all included in the for statement header. */
12 for ( counter = 1; counter <= 10; counter++ ) {
13 cout<<”\n” << counter ;
14 } /* end for */
15
16 return 0; /* indicate program ended successfully */
17
18 } /* end function main */
Establish initial
value of control
variable
counter
counter = 1
= 1
true
counter <= 10 Cout<<“\n” <<counter ; counter++
Increment
the control
Determine if final false Body of loop variable
value of control (this may be many
variable has been statements)
reached
7
8 int main()
9 {
10 int sum = 0;
11
12 for ( int number = 2; number <= 100; number += 2 )
13 sum += number;
14
15 cout << "Sum is " << sum << endl;
16
17 return 0;
18 }
Sum is 2550
fig04_06.c (Part 2 of 2)
21 character places
action(s)
true
condition
false
condition action(s)
true
false
• Break
– Causes immediate exit from a while, for, do/while or
switch structure
– Program execution continues with the first statement after the
structure
– Common uses of the break statement:
• Escape early from a loop
• Skip the remainder of a switch structure
• Continue
– Skips the remaining statements in the body of a while,
for or do/while structure and proceeds with the next
iteration of the loop
– In while and do/while, the loop-continuation test is
evaluated immediately after the continue statement is
executed
– In the for structure, the increment expression is executed,
then the loop-continuation test is evaluated
switch ( value ){
case '1':
case '2':
actions /* one or more statements */
break;
case '3':
case '4':
actions /* one or more statements */
break;
default:
actions /* one or more statements */
break;
}
• switch
– Useful when variable or expression is tested for multiple values
– Consists of a series of case labels and an optional default case
true
case a case a action(s) break
false
true
case b case b action(s) break
false
.
.
.
true
case z case z action(s) break
false
default action(s)
action(s)
true
condition
false
condition action(s)
true
false
• Structured programming
– Programs are easier to understand, test, debug and, modify.
• Rules for structured programming
– Only single-entry/single-exit control structures are used
– Rules:
1) Begin with the “simplest flowchart”.
2) Any rectangle (action) can be replaced by two rectangles
(actions) in sequence.
3) Any rectangle (action) can be replaced by any control
structure (sequence, if, if/else, switch, while, do/while or for).
4) Rules 2 and 3 can be applied in any order and multiple times.
Rule 3
Rule 3 Rule 3
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.