Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 48

Applications

 What does the following prints if any:


– Assume x=2, y=3, the using statement is used.

– cout <<x;
– cout <<x+x;
– cout << “x=:”;
– cout << “x= “<<x;
– cout <<x+y<<“=“<<“x+y”;
– z=x+y;
– cin >>x>>y;
– //cout <<“x+y =“<<x+y;
– cout<<“\n;”;
applications
 Given the algebraic equation y=ax3 + 7,
which of the following if any, are correct
C++ statements for this equations
– y=a*x*x*x+7
– y=a*x*x*(x+7);
– y=(a*x)*x*(x+7);
– y=(a*x)*x*x+7;
– y=a*(x*x*x)+7;
– y=a*x*(x*x+7);
Applications
 Write a program that inputs 3 integers from
the keyboard and prints the sum, average,
product, smallest and largest of these
numbers. The screen dialogue should
appear as follows:
Input three different integers: 13 27 14
Sum is 54
Average is 18
Product is 4914
Smallest is 3
Largest is 27
Applications
 Write a program that reads in the radius of a
circle and prints the circle’s diameter,
circumference and area. Use the constant
value 3.14159 for П. Do these calculations
in output statements. (note use only integer
values for the radius for the moment)
 What does the following code print?

– cout <<“*\n**\n***\n****\n*****\n”;
 Write a program that reads an integer and
determines and prints whether it is odd or
even.
 Write a program that reads in two integers
and determines and prints if the first is a
multiple of the second or not.
 Using only the techniques we learned until
now, write a program that calculates the
squares and the cubes of the numbers from
0 to 6 and uses tabs to print the following.
 Number square cube
 0 0 0
 1 1 1
 2 4 8
 3 9 27 Try to use 1 var only
 4 16 64
 5 25 125
 6 36 216
Chapter 2

Control Structures
 Writing a program understand the
problem

 Understand types of building blocks

 Basic structures common to most HL


languages.
Algorithms

 Algorithm  procedure for solving


problems

– Actions to be executed
– Order of actions

 Example: rise and shine algorithm


1. Get out of bed
2. Take off pyjamas
3. Take a shower
4. Get dressed
5. Eat breakfast
6. Carpool to work

  changing order ???


 In a Nut Shell:

– Algorithm: Set of
actions + logical order
Pseudocode
 Artificial, informal language  for developing
algorithms

 Pseudocodes  transferred later on to PL

 Similar to English: user-friendly, convenient

 Not a PL
 Pseudocodes not executables

 Pseudocode  1st step before attempting to


write a code

 Good pseudocodes direct conversion to


C++
 Pseudocodes  executable statements
– Inputs, outputs, operations…

 No declaration for example


Control Structure
 Sequential execution

 Transfer of control

 1960s: transfer of control  difficulties


– The GOTO statement
 Intro to Structured Programming 
“GOTO elimination “  Codes can be
written without any GOTO statements

 1970s  structured programming increased


Results:
1. reduced development time
2.more frequent on time delivery
3.more within budget completions
 Programs can be written using only 3
Control Structures:

– Sequence structure

– Selection structure

– Repetition structure
Sequence structure
 Built in C++
 C++ statements one after another (unless
told otherwise)
 Example of a sequence structure

Add grade to total total = total + grade;

Add 1 to counter counter = counter + 1;


 Previous example: Flowchart

 Flowchart and pseudocodes illustrates


algorithms

 Flowchart: graphical representation


– Special symbols: (rectangles, diamonds, ovals
and small circles)
– Connectors: flowlines
 Rectangle symbol  action symbol

 Flow lines  order of actions

 Complete diagram: 2 oval symbols: begin + end

 Part of an algorithm: use of small circles

 Diamond symbol: Decision to be made


C++ selection structures
 3 types of C++ selection structures

 if selection structure

 if/else structure

 Switch selection structure (depends on the


value of an integer expression)
 If selection structure single selection
structure

 If/else  double selection structure

 Switch: multiple selection structure


C++ repetition structures
 While

 Do/While

 For

 Note: if, else, switch, do, while, for  C++


keywords

 PS: do not use C++ keywords as identifiers


Software Engineering Observation

 Any C++ program we will ever build can be


constructed from only seven different types
of control structures (sequence, if, if/else,
switch, while, do/while and for) combined
in only 2 ways : Control structure stacking
and Control structure nesting.
if selection structure
 Pseudocode statement:

– if student’s grade is greater than or equal to 60


Print “Passed”

(condition = true or false)


Then next statement is executed

Highly recommended indentation


 Indentations are highly recommended
– readability

 C++ Compiler ignores white space


characters (blanks, tabs, new lines)
 Pseudocode  C++ PL
– if (grade >= 60) or if (grade>=60)
cout<<“Passed”;

Same example using flowchart:


Flowchart

true
Grade>=60 Print “Passed”

false
 Diamond: Decision symbol

 C++ data type bool (just C++)  true and


false values

 Writing a code: use of empty control


structure to be filled by programmer
(actions and decisions) combined in only 2
ways (stacking or nesting).
if/else selection structure
 If  action to be performed when condition is true

 If/else : actions to be taken depending on the


condition

 if student’s grade is greater than or equal to 60


Print “Passed”
else
Print “Failed”
 Good Programming practice:
– Indent both if and else body statements

 Corresponding C++ code


if (grade >=60)
cout <<“Passed”;
else
cout<<“Failed”;
C++ conditional operator
 ? : closely related to if/else

 C++ only ternary operator

 2 operands + conditional operator


conditional expression

 Ex: cout <<(grade >=60 ? “Passed” : “Failed”);


 Ex: cout <<(grade >=60 ? “Passed” : “Failed”);

 Parentheses needed (low precedence of conditional


operator)

 Same functionality as if/else statements

 Values in a conditional expression can be actions:

 Grade >=60 ? cout << “Passed” : cout <<“Failed”;


 Grade >=60 ? cout << “Passed” : cout <<“Failed”;

 Similar to:

 If grade is greater than or equal to 60 then


cout <<“Passed”; otherwise cout<<
“Failed”;
Action/Decision model using
flowcharts

False true
Grade >= 60

Print “Failed” Print “Passed”


Nested if/else structures
 If/else structures inside if/else structures

 Ex: Pseudocode printing A for exam grades


greater than or equal to 90, B for grades in
the range 80 and 89, 70<=C<=79,
60<=D<=69, and F for all other grades
 Illustrate Pseudocode

 Illustrate C++ code

 2 styles for representing the C++ code


 Popular presentation
If
Else if  avoids deep indentation to the right
Performance tips
 Nested if/else much faster of single
selection if.

 In nested if/else structure test more likely


conditions first
 1 statement if selection structure and several statements 
{}

 A set of statements in {}  called a compound statement.


 Ex of compound statement:
– If (grade>=60)
» Cout <<“Passed.\n”;
– Else{
» Cout<< “Failed.\n”;
» Cout<< “you must take this course again.\n”;
– }  without } the 2nd output statement will always appear
Programming errors
 Forgetting to close a {  syntax or logic
errors

 adding a ; after an if structure


Good programming practice
 Adding {} at the beginning of an if/else
structure

 Always adding {} even In 1 statement


bodies

 Compounds can include declarations 


they’ will be called blocks. Ex: the main
function
while Repetition Structure
 Repetition structure
– Action repeated while some condition remains
true
– Pseudocode
 
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
Common Errors
 Not providing a terminating action in the
body of an if  infinite loop error (runtime)

 Spelling while as While  syntax error (C+


+ case sensitive)
Example
 Find 1st power of 2 larger than 1000.

 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
 Values of product: 4, 8, 16, 32, 64, 128,
256, 512, 1024.

 9 executions, 10 evaluations.

You might also like