0% found this document useful (0 votes)
42 views32 pages

Decisions and Loops - Introduction To Pre-Defined Functions

This document discusses loops and pre-defined functions in C++. It covers do-while loops, for loops, increment/decrement operators, and avoiding infinite loops. It also discusses short-circuit evaluation and nested if/else statements. Finally, it introduces some common pre-defined math functions like sqrt() and explains how to include function libraries.

Uploaded by

Airas Akhtar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views32 pages

Decisions and Loops - Introduction To Pre-Defined Functions

This document discusses loops and pre-defined functions in C++. It covers do-while loops, for loops, increment/decrement operators, and avoiding infinite loops. It also discusses short-circuit evaluation and nested if/else statements. Finally, it introduces some common pre-defined math functions like sqrt() and explains how to include function libraries.

Uploaded by

Airas Akhtar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

CS 200 Introduction to Programming

- DECISIONS AND LOOPS


- INTRODUCTION TO PRE-DEFINED
FUNCTIONS
1

do-while loop
A variation of the while loop.
A do-while loop is always executed at least once
The body of the loop is first executed
The boolean expression is checked after the body
has been executed
Syntax:
do
{
statements to repeat
}
while (boolean_expression);

Increment/Decrement
Unary operators require only one operand
+ in front of a number such as +5
- in front of a number such as -5
++ increment operator
Adds 1 to the value of a variable
x ++;
is equivalent to
x = x + 1;
-decrement operator
Subtracts 1 from the value of a variable
x --;
is equivalent to
x = x 1;

Infinite Loops
Loops that never stop are infinite loops
The loop body should contain a line that will
eventually cause the boolean expression to
become false
Example: Print the odd numbers less than 12
x = 1;
while (x != 12)
{
cout << x << endl;
x = x + 2;
}

Better to use this comparison: while ( x < 12)

Short-Circuit Evaluation
Some boolean expressions do not need to be
completely evaluated
if x is negative, the value of the expression
(x >= 0) && ( y > 1)
can be determined by evaluating only (x >= 0)
C++ uses short-circuit evaluation
If the value of the leftmost sub-expression
determines the final value of the expression,
the rest
of the expression is not evaluated

Using Short-Circuit
Evaluation
Short-circuit evaluation can be used to prevent
run time errors
Consider this if-statement
if ((kids != 0) && (pieces / kids >= 2) )
cout << "Each child may have two pieces!";
If the value of kids is zero, short-circuit
evaluation
prevents evaluation of (pieces / 0 >= 2)
Division by zero causes a run-time error

Loops (contd)

For Loop
for ( init; condition; increment
)
{
statement(s);
}

#include <iostream>
using namespace std;
int main ()
{ // for loop execution
for( int a = 10; a < 20; a = a + 1 )
{
cout << "value of a: " << a <<
endl;
}
return 0;
}

10

Class Exercise: Fibonacci


Numbers
The Fibonacci sequence is a sequence Fn of natural
numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1

Write a function to generate the nth Fibonacci


number. Solutions can be iterative or recursive
(though recursive solutions are generally considered
too slow and are mostly used as an exercise in
recursion).
11

Class Exercise
Write multiplication tables for
integers 1-10 for numbers 1-10?

12

Multiway Branches
A branching mechanism selects one
out of a number of alternative actions
The if-else-statement is a branching
mechanism

Branching mechanisms can be a


subpart of another branching
mechanism
An if-else-statement can include another
if-else-statement as a subpart
13

Nested Statements
A statement that is a subpart of another
statement
is a nested statement
When writing nested statements it is normal to
indent each level of nesting
Example:

indented

if ( x < y)
cout << x << " is less than "

<< y;
else
cout << y << " is less than "
<< x;
14

Nested if-else Statements


Use care in nesting if-else-statements
Example: To design an if-else statement to
warn a driver when fuel is low, but tells the
driver to bypass pit stops if the fuel is close
to full. Other wise there should be no output.
Pseudocode: if fuel gauge is below then:
if fuel gauge is below then:
issue a warning
otherwise (gauge > ) then:
output a statement saying don't stop

15

Braces and Nested


Statements
Braces in nested statements are like
parenthesis in arithmetic expressions
Braces tell the compiler how to group
things

Use braces around substatements

16

Multi-way if-else-statements
An if-else-statement is a two-way
branch
Three or four (or more) way branches
can be
designed using nested if-elsestatements
Example: The number guessing game
with
the number stored in
variable
number, the guess in
variable
guess. How do we give hints? 17

Nested if-else Syntax


A Multiway if-else statement is
written as
if (Boolean_Expression_1)
Statement_1
else if ( Boolean_Expression_2)
Statement_2

else if (Boolean_Expression_n)
Statement _n
else
Statement_For_All_Other_Possibilities
18

The switch-statement
The switch-statement is an
alternative for
constructing multi-way branches

19

switch-statement Syntax

switch (controlling expression)


{
case Constant_1:
statement_Sequence_1
break;
case Constant_2:
Statement_Sequence_2
break;
...
case Constant_n:
Statement_Sequence_n
break;
default:
Default_Statement_Sequence
}

20

The Controlling Statement


A switch statement's controlling statement
must return one of these types
A bool value
An enum constant
An integer type
A character
The value returned is compared to the
constant values after each "case"
When a match is found, the code for that case
is used

21

The break Statement


The break statement ends the switch-statement
Omitting the break statement will cause the
code
for the next case to be executed!
Omitting a break statement allows the use of
multiple case labels for a section of code
case 'A':
case 'a':
cout << "Excellent.";
break;
Runs the same code for either 'A' or 'a'

22

The default Statement


If no case label has a constant that
matches the controlling expression,
the statements following the default
label are executed
If there is no default label, nothing
happens when the switch statement is
executed
It is a good idea to include a default
section
23

Class Exercise
Write a program for a state that computes tax
according to the rate schedule:

No tax on first $15,000 of income


5% tax on each dollar from $15,001 to $25,000
10% tax on each dollar over $25,001 to $50,000
15% tax on each dollar over $50,001 to $75,000
20% tax on each dollar over $75,001 to $100,000
25% tax on each dollar over $100,001

24

Designing Loops
Designing a loop involves designing
The body of the loop
The initializing statements
The conditions for ending the loop

25

PRE-DEFINED FUNCTIONS

26

Predefined Functions
C++ comes with libraries of
predefined
functions
Example: sqrt function
the_root = sqrt(9.0);
returns, or computes, the square root
of a number
The number, 9, is called the argument
the_root will contain 3.0
27

Function Calls
sqrt(9.0) is a function call
It invokes, or sets in action, the sqrt function
The argument (9), can also be a variable or an
expression
A function call can be used like any expression
bonus = sqrt(sales) / 10;
cout << The side of a square with area <<
area
<< is
<< sqrt(area);

28

Function Call Syntax


Function_name (Argument_List)
Argument_List is a comma separated list:

(Argument_1, Argument_2, ,
Argument_Last)

Example:
side = sqrt(area);
cout << 2.5 to the power 3.0 is
<< pow(2.5, 3.0);
29

Function Libraries
Predefined functions are found in libraries
The library must be included in a program
to make the functions available
An include directive tells the compiler which
library header file to include.
To include the math library containing sqrt():
#include <cmath>
Newer standard libraries, such as cmath, also
require
the directive
using namespace std;
30

Other Predefined Functions


abs(x) --- int value = abs(-8);
Returns absolute value of argument x
Return value is of type int
Argument is of type x
Found in the library cstdlib
fabs(x)
--- double value = fabs(-8.0);
Returns the absolute value of argument x
Return value is of type double
Argument is of type double
Found in the library cmath
31

32

You might also like