Exam2 Review

advertisement
Chapter 5:
Loops
Outline




Increment and Decrement
while loop
do-while loop
for loop
Slide 5- 2
The Increment and Decrement Operators

++ is the increment operator.
It adds one to a variable.
val++; is the same as val = val + 1;

++ can be used before (prefix) or after (postfix) a
variable:
++val;
val++;
Slide 5- 3
The Increment and
Operators

Decrement
-- is the decrement operator.
It subtracts one from a variable.
val--; is the same as val = val - 1;

-- can be also used before (prefix) or after (postfix) a
variable:
--val;
val--;
Slide 5- 4
Prefix vs. Postfix



++ and -- operators can be used in complex
statements and expressions
In prefix mode (++val, --val) the operator
increments or decrements, then returns the value of
the variable
In postfix mode (val++, val--) the operator
returns the value of the variable, then increments or
decrements
Slide 5- 6
Prefix vs. Postfix - Examples
int num, val = 12;
cout << val++;
cout << ++val;
num = --val;
num = val--;
//
//
//
//
//
//
//
//
displays 12,
val is now 13;
sets val to 14,
then displays 14
sets val to 13,
stores 13 in num
stores 13 in num,
sets val to 12
Slide 5- 7
Introduction to Loops:
The while Loop
The general form of the while statement is:
while (expression)
statement;
OR
while (expression)
{
statement1;
statement2;
}
Slide 5- 9
The Logic of a while Loop
Slide 5- 10
Slide 5- 11
while is a Pretest Loop
• expression is evaluated before the loop
executes. The following loop will never
execute:
int number = 6;
while (number <= 5)
{
cout << "Hello\n";
number++;
}
Slide 5- 14
An Infinite Loop
int number = 1;
while (number <= 5)
{
cout << "Hello\n";
}
Slide 5- 15
The Power of the while statement
• To illustrate the power of the while statement, consider the task of printing
a table of numbers from 1 to 10 with their squares and cubes. This can be
done with a simple while statement:
void main ( void )
{
int num = 1;
//Display Heading
cout << "Number
Square
Cube\n"
<< "-------------------------\n";
while (num < 11)
{
cout << num << "
"
<< pow(num, 2) << "
"
<< pow(num, 3) << "
"<< endl;
num = num + 1;
}
}
The Power of the while statement
Note: The expression (num <= 10) could have been used in place of (num < 11).
Number
-----------1
2
3
4
5
6
7
8
9
10
Square
---------1
4
9
16
25
36
49
64
81
100
Cube
-- ----------1
8
27
64
125
216
343
512
729
1000
If we wanted to use the previous program to produce a table of 1000
numbers, all we have to do is change the expression in the while statement
from (num < 11) to (num < 1001).
The do-while Loop
The do statement allows us to execute some statements before an
expression is evaluated. The general form of the do statement is:
do
statement;
while(expression); //don’t forget the ;
OR
do
{
statement1;
statement2;
}while(expression); //don’t forget the ;
Slide 5- 19
The Logic of a do-while Loop
Slide 5- 20
The for Loop
•
•
Useful for counter-controlled loop
General Format:
for(initialization; test; update)
statement; // or block in { }
•
•
No semicolon after 3rd expression or after the )
for Loop - Mechanics
1) Perform initialization
2) Evaluate test expression
•
•
If true, execute statement
If false, terminate loop execution
3) Execute update, then re-evaluate test expression
Slide 5- 22
A Closer Look at the Previous Example
Slide 5- 23
for loop – pretest loop
• When to Use the for Loop?
– In any situation that clearly requires
• an initialization
• a false condition to stop the loop
• an update to occur at the end of each iteration
• The for loop tests its test expression before
each iteration, so it is a pretest loop.
• The following loop will never iterate:
for (count = 11; count <= 10; count++)
cout << "Hello" << endl;
Slide 5- 25
Keeping a Running Total
• running total: accumulated sum of numbers from each
repetition of loop
• accumulator: variable that holds running total
int sum=0, num=1; // sum is the accumulator
while (num <= 10)
{
sum += num;
num++;
}
cout << "Sum of numbers 1 – 10 is"
<< sum << endl;
Slide 5- 28
Output
How many numbers would you like to total?
4
Please enter a number:
56
Please enter a number:
45
Please enter a number:
85
Please enter a number:
43
The total of the numbers you entered is: 229
The average of the numbers you entered is: 57.25
Nested Loops
• A nested loop is a loop inside the body of
another loop
• Inner (inside), outer (outside) loops:
for (row=1; row<=3; row++) //outer
for (col=1; col<=3; col++)//inner
cout << row * col << endl;
Slide 5- 31
Example
for (int i = 1; i <= 5; i++)
// start outer loop
{
cout << "\n i is now " << i << endl;
for (int j = 1; j <= 4; j++)
// start inner loop
cout << " j = " << j;
// end of inner loop
}
// end of outer loop
The first loop, controlled by the value of i, is called the outer loop. The
second loop, controlled by the value of j, is called the inner loop. For each
single trip through the outer loop, the inner loop runs through its entire
sequence. Thus, each time the i counter increases by 1, the inner for loop
executes completely.
Output
• Below is the output from the previous nested loop:
i is now 1
j= 1 j= 2 j= 3 j= 4
i is now 2
j= 1 j= 2 j= 3 j= 4
i is now 3
j= 1 j= 2 j= 3 j= 4
i is now 4
j= 1 j= 2 j= 3 j= 4
i is now 5
j= 1 j= 2 j= 3 j= 4
Chapter 6:
Functions
Outline
•
•
•
•
What is “Function”
Sending data into function
The return statement
Local and Global variables
Slide 6- 40
Function Definition
Slide 6- 42
Calling a Function
void printHeading()
{
cout << "Monthly Sales\n";
}
• To call a function, use the function name followed by ()and ;
printHeading();
• When called, program executes the body of the called
function
• After the function terminates, execution resumes in the
calling function at point of call.
Slide 6- 44
Function Prototypes
• Ways to notify the compiler about a function
before a call to the function:
1. Place function definition before calling function’s
definition
or
2. Use a function prototype (function declaration) – like
the function definition without the body
• Header: void printHeading()
• Prototype: void printHeading();
Slide 6- 46
(Program Continues)
Slide 6- 47
Slide 6- 48
Sending Data into a Function
• Can pass values into a function at time of call:
displayValue(5);
// function call
• Values (data) passed to function are arguments
• Variables in a function that hold the values passed as
arguments are parameters
void displayValue(int num)
{
cout << "The value is " << num << endl;
}
The integer variable num is a parameter. It accepts any integer
value passed to the function.
Slide 6- 49
What is the output?
Slide 6- 50
The function call in line 11 passes the value 5
as an argument to the function.
Slide 6- 51
Parameters, Prototypes, and Function
Headers
• For each function argument,
– the prototype must include the data type of each
parameter inside its parentheses
– the header must include a declaration for each
parameter in its ()
void evenOrOdd(int);
//prototype
void evenOrOdd(int num) //header
evenOrOdd(val);
//call
Slide 6- 52
Passing Multiple Arguments
When calling a function and passing multiple
arguments:
– the number of arguments in the call must match
the prototype and definition
– the first argument will be used to initialize the first
parameter, the second argument to initialize the
second parameter, etc.
Slide 6- 53
Slide 6- 54
The function call in line 18 passes value1, value2, and
value3 as arguments to the function.
Slide 6- 55
The return Statement
The RETURN statement has two purposes:
• The return statement causes a function to
END immediately
• A function may send ONE value back to the
part of the program that called the function
Slide 6- 56
The return Statement
• Used to end execution of a function
• Can be placed anywhere in a function
– Statements that follow the return statement
will not be executed
• Can be used to prevent abnormal termination
of program
• In a void function without a return
statement, the function ends at its last }
Slide 6- 57
Program 6-11(Continued)
Slide 6- 58
Returning a Value From a Function
• A function can return a value back to the statement that
called the function.
• A function returning a value must specify, in its header
line, the data type of the value that will be returned.
• In a value-returning function, the return statement can
be used to return a value from function to the point of call.
Example:
int sum(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
Slide 6- 59
A Value-Returning Function
Return Type – Incorrect
int sum(int num1, int num2)
{
double result;
result = num1 + num2;
return result;
}
Value Being Returned
Slide 6- 60
A Value-Returning Function
Return Type – Correction – Depending on
design of code
double sum(int num1, int num2)
{
double result;
result = num1 + num2;
return result;
}
Value Being Returned
Slide 6- 61
A Value-Returning Function
Return Type – Correction – Depending on
design of code
int sum(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
Value Being Returned
Failure to match the return value exactly with the function's declared data
type may not result in an error when the program is compiled, but it may
lead to undesired results because the return value is always converted to the
data type declared in the function declaration
Slide 6- 62
Calling function to receive the value
• On the receiving side, the called function must:
– be alerted to the type of value to expect
– properly use the returned value
• provide a variable to store the value
– accomplished by using a standard assignment statement, e.g.:
total = sum (firstnum, secondnum);
• use the value directly in an expression, e.g.:
2 * sum (firstnum, secondnum);
cout << sum(firstnum, secondnum);
The next program illustrates the inclusion of both the prototype and
assignment statements for main( ) to correctly call and store a
returned value from sum( ).
//function prototypes
double inputFahrenheit( );
//reads fahrenheit temp from user
double convertFahenheitToCelsius(double); //converts fahren temp to celsius
void displayConvertedDegree (double, double); //displays converted temperature
int main ( void )
{
//Declaration statements
double fahrenheit = 0.0; //stores the temp in fahren entered by user
double celsius = 0.0;
//stores the calculated converted temp in celsius
fahrenheit = inputFahrenheit( ); //function call to get data from user
celsius = convertFahenheitToCelsius(fahrenheit);//function call-convert F˚ to celsius
displayConvertedDegree(celsius, fahrenheit); //function call -display converted temp
return 0;
}
/* This function allows the user to input the temperature in Fahrenheit that is to be converted to Celsius */
double inputFahrenheit( )
{
double f;
cout << "Please enter the temperature recorded in Fahreheit " << endl << "that you wish to be converted to
Celsius: ";
cin >> f;
return f;
}
/* This function converts Fahrenheit to Celsius */
double convertFahenheitToCelsius(double f_degrees)
{ return (5.0 / 9.0 ) * ( f_degrees - 32.0 ); }
/*This function displays Celsius equivalent of the temperture that was entered in Fahrenheit */
void displayConvertedDegree(double cel, double fahren)
{ cout << fahren << " Fahrenheit is " << cel << " Celsius. " << endl;}
• Output:
Please enter the temperature recorded in Fahreheit
that you wish to be converted to Celsius: 32
32 Fahrenheit is 0 Celsius.
• This program consists of 4 functions
main( )
inputFahrenheitToCelsius( )
convertFahrenheitToCelsius( )
displayConvertedDegree( )
Local Variables
Slide 6- 67
Global Variables
• A global variable is any variable defined
outside all the functions in a program.
• The scope of a global variable is the portion of
the program from the variable definition to
the end.
• This means that a global variable can be
accessed by all functions that are defined
after the global variable is defined.
• Constant variable is a good example for global
variable
Slide 6- 69
Chapter 7:
Arrays
Arrays Hold Multiple Values
• Declared using [] operator:
int tests[5]; // definition
int is the data type of the array elements
tests is the name of the array
5, in [5], is the size declarator. It shows
the number of elements in the array.
Accessing Array Elements
• Each element in an array is assigned a unique
subscript.
• Subscripts start at 0
• The last element’s subscript is n-1 where n is
the number of elements in the array.
subscripts:
0
Slide 7- 74
1
2
3
4
(Program Continues)
Slide 7- 75
Here are the contents of the hours array, with the values entered by the user in
the example output:
Slide 7- 76
Download