Title: C++ PROGRAMMING SKILLS Part 2 Programming Structures
1C PROGRAMMING SKILLSPart 2Programming
Structures
- If structure
- While structure
- Do While structure
- Comments, Increment Decrement operators
- For statement
- Break Continue statements
- Switch structure
2Control Structures
- Sequential structure
- Statements executed in order. Programs executed
sequentially by default - Selection structures
- Next statement executed not next one in sequence
- if, if/else, switch
- Repetition structures
- Statement repeatedly executed a number of times
- while, do/while, for
- single-entry/single-exit control structures
- Connect exit point of one control structure to
entry point of the next (control-structure
stacking). - Makes programs easy to build.
3if Selection Structure
- Selection structure
- Choose among alternative courses of action
- Pseudocode example
- If students grade is greater than or equal to 50
- Print Passed
- If the condition is true
- Print statement executed, program continues to
next statement - If the condition is false
- Print statement ignored, program continues
- Indenting makes programs easier to read
- C ignores whitespace characters (tabs, spaces,
etc.)
4if Selection Structure
- Translation into C
- If students grade is greater than or equal to 50
- Print Passed
- if ( grade gt 50 ) cout ltlt "Passed"
- Diamond symbol (decision symbol)
- Indicates decision is to be made
- Contains an expression that can be true or false
- Test condition, follow path
- if structure
- Single-entry/single-exit
A decision can be made on any expression. zero -
false nonzero - true Example (3 4) is true
5 if/else Selection Structure
- if
- Performs action if condition true
- if/else
- Different actions if conditions true or false
- Pseudocode
- if students grade is greater than or equal to
50print Passed - else
- print Failed
- C code
- if ( grade gt 60 ) cout ltlt "Passed"else
cout ltlt "Failed"
6if Statement Syntax
if (Expression) statement
Eg2. if (age lt 18) coutltlt Not eligible
Eg1. if (grade gt 50) coutltlt Passed
7if/else Statement Syntax
if (Expression) statementi else statementk
condition
true
false
Statementi
Statementk
Eg1. if (grade gt 50) coutltlt Passed
else coutltlt Failed
8if/else Selection Structure
- Compound statement
- Set of statements within a pair of braces
- if ( grade gt 50 ) cout ltlt
"Passed.\n" else cout ltlt "Failed.\n"
cout ltlt "You must take this course again.\n" - Without braces,
- cout ltlt "You must take this course again.\n"
- always executed
- Block
- Set of statements within braces
9if/else Selection Structure
- More on Compound statement
- if ( grade gt 50 )
- cout ltlt "Passed.\n"
- cout ltlt Very Good.\n" else cout ltlt
"Failed.\n" - if ( grade gt 50 )
- cout ltlt "Passed.\n"
- cout ltlt Very Good.\n" else cout ltlt
"Failed.\n" cout ltlt Must take this course
again.\n" -
10if/else Selection Structure
- Nested if/else structures
- One inside another, test for multiple cases
- Once condition met, other statements skipped
- if students grade is greater than or equal to
90 Print A - else if students grade is greater than or
equal to 80 Print B else if
students grade is greater than or equal to 70
Print C else if students
grade is greater than or equal to 60
Print D else - Print F
11if/else Selection Structure
- Example
- if ( grade gt 90 ) // 90 and above cout
ltlt "A"else if ( grade gt 80 ) // 80-89 cout
ltlt "B"else if ( grade gt 70 ) // 70-79 cout
ltlt "C" else if ( grade gt 60 ) // 60-69
cout ltlt "D"else // less
than 60 cout ltlt "F"
12while Repetition Structure
- Repetition structure
- Action 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 lt 1000 )
- product 2 product
13while Statement Syntax
while (Expression) statement
int prod 2 while (prod lt 100) prod
2 prod
int prod 2 while (prod lt 100) prod
2 prod cout ltlt Product ltlt
prod ltltendl
14The 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 )
- Example (letting counter 1)
- do
- coutltltcounterltlt" "countercounter1
- while (counter lt 10)
- This prints the integers from 1 to 10
- All actions are performed at least once.
15do-while Repetition Structure
do statement while (Expression)
do cout ltlt Enter a Positive integer
cin gtgt num while (num lt 0) cout ltlt
Thank You !
Input Validation Examples
do coutltltEnter an integer between 1 and
7, please cingtgtnum while (num lt 1
num gt 7) cout ltlt Thank You Very Much.\n
16do-while and while Examples
sum0 counter1 while (counterlt100)
sumsumcounter countercounter1 //
increment counter
do//age validation not equal or less then zero
coutltltEnter your Age cingtgtage
while (agelt0)
17do-while and while Examples
// Add even numbers between 1 and 100 sum0
counter2 while (counterlt100)
sumsumcounter countercounter2
Question1 Write C program to Add EVEN numbers
together from a 100 input Values
Question2 Write C program to separately add
Even numbers and Odd numbers. Finally prints
sumEv sumO
18Example Sum Evens
// Add only Even number of 100 inputs include
ltiostream.hgt int main( ) int num, sum,
counter sum0 counter0 do
coutltltEnter a number cingtgtnum if(
num20) sum sum num countercounter
1 while (counter lt 100)
coutltltsum return 0 // end function main
19Example sum odds Evens
// separately add Even numbers and Odd numbers.
Prints the sum of each includeltiostream.hgt int
main() int num, sumEven0, sumOdd0,
counter0 do coutltltEnter a number
cingtgtnum if(num20)
sumEven sumEven num
else sumOddsumOdd num
countercounter1 while
(counter lt 100) coutltltsum of Ever
Numbers ltltsumEvenltltendl coutltltsum of
Odd numbers ltltsumOddltltendl return 0
20Nested do and while Example
Question Write C program to Read any set of
numbers then calculates and prints the sum of Odd
numbers and the sum of Even numbers. The program
should continues to do this until user decide to
stop
Solution
21Nested do and while Example
Solution //Nested while loop in do while sum of
Even Odd numbers includeltiostream.hgt char
answer int main() int sumEven, sumOdd, num,
counter, limit do coutltltHow many number in
your set ? (value gt0) cingtgtlimit // limit
value must be gt0 counter0
22Nested do and while Examplecont.1
sumEvensumOdd0 while (counter lt limit)
coutltltEnter a number cingtgtnum if(
num20) sumEvensumEvennum else sum
OddsumOddnum counter // end while
statement coutltltsum of Even numbers ltlt
sumEven coutltltendl coutltltsum of odd
numbers ltlt sumOdd
23Nested do and while Examplecont.2
coutltlt\n more? Type Y for Yes or N for No
cingtgtanswer while(answerY
answery) coutltlt\n\n Bye Bye\n\n return
0 // end function main
24Counter-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.
25Counter-Controlled Repetition- Formulating
Algorithms
- Pseudocode for example
- 1. Set total to zero
- 2. Set grade counter to one
- 3. While grade counter is less than or equal to
ten 3.1 Input the next grade 3.2 Add the grade
into the total 3.3 Add one to the grade counter - 4. Set the class average to the total divided by
tenPrint the class average - 5. Output the result
- Following is the C code for this example
26- Outline
- 1. Initialize Variables
- 2. Execute Loop
- 3. Output results
27 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
28Sentinel-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)
29Sentinel-Controlled RepetitionFormulating
Algorithms with Top-Down, Stepwise Refinement
- 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
30Formulating 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
31Formulating Algorithms with Top-Down, Stepwise
Refinement
- Refine
- Input, sum and count the quiz grades
- to
- 1. Input the first grade (possibly the sentinel)
- 2. While the user has not as yet entered the
sentinel - 2.1 Add this grade into the running total
- 2.2 Add one to the grade counter
- 2.3 Input the next grade (possibly the
sentinel) - Refine
- Calculate and print the class average
- to
- 1. If the counter is not equal to zero
- 1.1 Set the average to the total divided by
the counter - 1.2 Print the average
- Else
- 2.1Print No grades were entered
32- Outline
- 1. Initialize Variables
- 2. Get user input
- 2.1 Perform Loop
33- 3. Calculate Average
- 3.1 Print Results
Program Output
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
34Nested 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 usedone 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 numbereither 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
35Nested 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
- 1. Initialize passes to zero
- 2. Initialize failures to zero
- 3. Initialize student counter to one
36Nested control structures
- Refine
- Input the ten quiz grades and count passes and
failures - to
- While student counter is less than or equal to
tenInput the next exam result - If the student passed
- Add one to passesElse 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
37- 1. Initialize variables
- 2. Input data and count passes/failures
38- Outline
- 3. Print results
- Program Output
Enter result (1pass,2fail) 1 Enter result
(1pass,2fail) 1 Enter result (1pass,2fail)
1 Enter result (1pass,2fail) 1 Enter result
(1pass,2fail) 2 Enter result (1pass,2fail)
1 Enter result (1pass,2fail) 1 Enter result
(1pass,2fail) 1 Enter result (1pass,2fail)
1 Enter result (1pass,2fail) 1 Passed 9 Failed
1 Raise tuition
39Assignment 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)
40Increment 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. - Postincrement
- 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 ltlt c prints out 6 (c is changed before
cout is executed) - cout ltlt c prints out 5 (cout is executed
before the increment. c now has the value of 6)
41Increment and DecrementOperators
- When Variable is not in an expression
- Preincrementing and postincrementing have the
same effect. - c
- cout ltlt c
- and
- c
- cout ltlt c
- have the same effect.
42Increment Decrement OperatorsExamples
int
c
c5coutltltcltltendl
5coutltltcltltendl
5coutltltcltltendl
6coutltlt\n
int
cc5coutltltcltltendl
5coutltltcltltendl
6coutltltcltltendl
6
OUTPUT
OUTPUT
43Increment Decrement OperatorsExamples
int
c
c5coutltltcltltendl
5coutltltc- -ltltendl
5coutltltcltltendl
4coutltlt\n
c5coutltltcltltendl
5coutltlt- -cltltendl
4coutltltcltltendl
4
44Increment Decrement OperatorsExample
- / The following code demonstrates true use of
several format for increment decrement
operators. / - counter1
- do
- counter
- counter1
- counter
- while(counterlt10)
- counter10
- do
- counter --
- counter- 1
- -- counter
- while(countergt0)
45The for Repetition Structure
- The general format when using for loops is
- for ( initialization LoopContinuationTest increm
ent ) - statement
- Example
- for( int counter 1 counter lt 10 counter )
- cout ltlt counter ltlt endl
- Prints the integers from one to ten
No semicolon after last expression
46The for Repetition Structure
- for loops can usually be rewritten as while
loops - initialization
- while ( loopContinuationTest)
- statement
- increment
-
- Initialization and increment as comma-separated
lists - for (int i 0, j 0 j i lt 10 j, i)
- cout ltlt j i ltlt endl
47Examples Using the for Structure
- Program to sum the even numbers from 2 to 100
48Examples Using the for Structure
Example 1
for(n1nlt9n) coutltltn
Example 2
sum 0 for(n1 nlt5 n) cout ltlt
Enter a number cin gtgt num sum
sum num Cout ltlt sum ltlt sum
Output Enter a number 81 Enter a number
1 Enter a number 5 Enter a number 100 Enter
a number 4 Sum 191
49Examples Using the for Structure
Be careful of infinite loop
50Examples Using the for Structure
Output 2 7 12 17 22 27 32 37
x2 y10 for (jx jlt2xy j
y/x) cout ltlt j ltlt endl
the above for is the same as
for (j2 jlt40 j 5) cout ltlt jltlt endl
51Examples Using the for Structure
- Remarks
- Initial value does not have to start with 1
- Incremental value can be greater then 1.
- Initial value, condition and incremental can all
be expressions. - Example
- // control variable varies from 1 to 100 and vice
versa - for(i1 ilt10 i)
- coutltlt i ltlt
- for(i10 igt1 i--)
- coutltlt i ltlt
- // control variable varies from 20 to 2 in steps
of -2. - for(i20ilt2 i-2)
- coutltltiltlt
Output 1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 2 1
Output 20 18 16 14 12 10 8 6 4 2
52Examples Using the for Structure
// control variable vary over 2,5,8,11,14,17,20
. for(i2ilt20i3) coutltltiltlt cout
ltltendlltlt i // control variable vary from 7 to
77 in steps of 7. for(i7ilt77i7) coutltltiltlt
cout ltltendlltlt i Example 2 // control
variable vary over 99,88,77,66,55,44,33,22,11 for(
i99 igt11 i-11) coutltltiltlt cout ltltendlltlt
i
Output 2 5 8 11 14 17 20 23 7 14 21 28 35 42 49
56 63 70 77 84 99 88 77 66 55 44 33 22 11 10
53Nested For Loop examples
Example 1 for(r1rlt5r )
for(c1clt5c) coutltlt
coutltltendl Output
Example 2 // multiplication table for(x1 xlt3
x ) for(y1 ylt3 y)
coutltltxltltltltyltltltltxyltltendl Output 111 12
2 133 212 224 236 313 326 339
54for Loop and while Loop
Example 1 for(i1ilt5i) coutltlti Output 1
2 3 4 5 Example 1 i1 while(ilt5) coutltlti
i Output 1 2 3 4 5
for (Expr1 Expr2 Expr3) statement
Equivalent while Syntax
Expr1 while(Expr2) statement Expr3
55More examples on for
- Float index in the for loop
- float x
- for(x1.0xlt5.0x0.5)
- cout ltlt x ltlt
- Output
- 1 1.5 2 2.5 3 3.5 4 4.5 5
- Char index in the for loop
- char ch
- for(cha chltf ch b - a)
- cout ltlt ch ltlt
- Output
- a b c d e f
- float ch
- for(cha ch ltc ch j - i)
output - coutltltHello!\n
Hello! -
Hello! -
Hello!
56The break and continue Statements
- 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
57The break and continue Statements
- Continue
- Skips the remaining statements in the body of a
while, for or do/while structures 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
58Break Statement
The break statement when executed in a while,
for, do/while, or switch structure, causes
immediate exit from that structure. Note If
break comes in nested loops, it causes immediate
exit from the innermost-loop. Thus, it is used
to escape early from a loop or to skip the
remainder of a switch structure Example
1 i1 while (true) // endless condition, it
is always true coutltlti if(i5) break i
Output break stop and exit the loop 1
2 3 4 5
59break Statement
Example 2 for(x1xlt10x) if(x5) break
coutltltx Output exit before printing 5 1
2 3 4 ----------------------------------------
--------------------------------------------------
--------- Example 3 for(x1xlt10x) coutltltx
if(x5) break Output exit after
printing 5 1 2 3 4 5
60break Statement
Quiz Write program to calculate the following
arithmetic expression, but must a void dividing
by Zero and the program must continue executing
until the user decide to stop it.
includeltiostream.hgt include ltmath.hgt double
x, y char ans int main( ) do
coutltltEnter value of x cingtgtx if(x
0) break ysqrt(fabs(x)5)/x coutltltylt
lty coutltltwould you like to enter more
(y/n)? cingtgtans while(ansY
ansy) return 0
61continue Statement
The continue statement when executed in a while
,for or do-while structure. Skip the remaining
statement in body of the loop and proceeds with
the next iteration of the loop Note In while and
dowhile ,the condition evaluated immediately
after the continue statement is executed in for,
the increment is executed first, then the
condition is evaluated. Remark How continue
affect the analogy between for and while
? Usually, while can be used to represent for.
The one exception occurs when the increment in
the while following the continue. In this case,
the increment is not executed before the
repetition condition is tested and the while does
not execute in the same manner as the for.
62continue Statement
- for(x1xlt10x)
- if(x5)
- continue
- coutltltxltlt
-
- Output continue prevented printing 5
- 1 2 3 4 6 7 8 9 10
- Implementing for using while (the exception case)
- x1
- while (xlt10)
- if (x5)
- continue
- coutltltxltlt
- x
-
- Output continue goes direct to the
condition (no increment) ? infinite loop! - 1 2 3 4
63continue Statement
- To enforce equivalence
- for
- for(x1 xlt10 x)
- if(x 5)
- continue
- cout ltlt x
-
- while
- x0
- while (x lt 9)
- x
- if( x 5 )
- continue
- cout ltlt x
64The switch Multiple-Selection Structure
- switch
- Useful when variable or expression is tested for
multiple values - Consists of a series of case labels and an
optional default case
65switch Statement Syntax
switch (expression) case value1
statement(s) break case value2
statement(s) break . . case
valuen statement(s) break
. default statement(s) break
66- 1. Initialize variables
-
- 2. Input data
- 2.1 Use switch loop to update count
67- 2.1 Use switch loop to update count
- 3. Print results
68 Enter the letter grades. Enter the EOF
character to end input. a B c C A d f C E Incorrec
t 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