Chapter 5: Loops

57
Chapter 5: Loops

description

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; - PowerPoint PPT Presentation

Transcript of Chapter 5: Loops

Page 1: Chapter 5: Loops

Chapter 5:

Loops

Page 2: Chapter 5: Loops

Slide 5- 2

Outline

Increment and Decrement while loop do-while loop for loop

Page 3: Chapter 5: Loops

Slide 5- 3

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++;

Page 4: Chapter 5: Loops

Slide 5- 4

The Increment and Decrement Operators -- 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--;

Page 5: Chapter 5: Loops

Slide 5- 6

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

Page 6: Chapter 5: Loops

Slide 5- 7

Prefix vs. Postfix - Examples

int num, val = 12;

cout << val++; // displays 12, // val is now 13;

cout << ++val; // sets val to 14, // then displays 14num = --val; // sets val to 13,

// stores 13 in numnum = val--; // stores 13 in num,

// sets val to 12

Page 7: Chapter 5: Loops

Slide 5- 9

The general form of the while statement is:

while (expression) statement;

OR while (expression) {

statement1; statement2;

}

Introduction to Loops: The while Loop

Page 8: Chapter 5: Loops

Slide 5- 10

The Logic of a while Loop

Page 9: Chapter 5: Loops

Slide 5- 11

Page 10: Chapter 5: Loops

Slide 5- 14

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++;}

Page 11: Chapter 5: Loops

Slide 5- 15

An Infinite Loop

int number = 1;while (number <= 5){ cout << "Hello\n";}

Page 12: Chapter 5: Loops

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;}

}

Page 13: Chapter 5: Loops

The Power of the while statementNote: The expression (num <= 10) could have been used in place of (num <

11).

Number Square Cube------------ ---------- -- ----------- 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 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).

Page 14: Chapter 5: Loops

Slide 5- 19

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 ;

The do-while Loop

Page 15: Chapter 5: Loops

Slide 5- 20

The Logic of a do-while Loop

Page 16: Chapter 5: Loops
Page 17: Chapter 5: Loops

Slide 5- 22

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 initialization2) Evaluate test expression

• If true, execute statement• If false, terminate loop execution

3) Execute update, then re-evaluate test expression

Page 18: Chapter 5: Loops

Slide 5- 23

A Closer Look at the Previous Example

Page 19: Chapter 5: Loops

Slide 5- 25

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;

Page 20: Chapter 5: Loops

Slide 5- 28

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 accumulatorwhile (num <= 10){ sum += num;

num++;}cout << "Sum of numbers 1 – 10 is" << sum << endl;

Page 21: Chapter 5: Loops

OutputHow many numbers would you like to total?4Please enter a number: 56Please enter a number: 45Please enter a number: 85Please enter a number: 43The total of the numbers you entered is: 229The average of the numbers you entered is: 57.25

Page 22: Chapter 5: Loops

Slide 5- 31

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++) //outerfor (col=1; col<=3; col++)//inner

cout << row * col << endl;

Page 23: Chapter 5: Loops

Examplefor (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.

Page 24: Chapter 5: Loops

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

Page 25: Chapter 5: Loops

Chapter 6:

Functions

Page 26: Chapter 5: Loops

Outline

• What is “Function”• Sending data into function• The return statement• Local and Global variables

Page 27: Chapter 5: Loops

Slide 6- 40

Page 28: Chapter 5: Loops

Slide 6- 42

Function Definition

Page 29: Chapter 5: Loops
Page 30: Chapter 5: Loops

Slide 6- 44

Calling a Functionvoid 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.

Page 31: Chapter 5: Loops

Slide 6- 46

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();

Page 32: Chapter 5: Loops

Slide 6- 47

(Program Continues)

Page 33: Chapter 5: Loops

Slide 6- 48

Page 34: Chapter 5: Loops

Slide 6- 49

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.

Page 35: Chapter 5: Loops

Slide 6- 50

What is the output?

Page 36: Chapter 5: Loops

Slide 6- 51

The function call in line 11 passes the value 5as an argument to the function.

Page 37: Chapter 5: Loops

Slide 6- 52

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); //prototypevoid evenOrOdd(int num) //headerevenOrOdd(val); //call

Page 38: Chapter 5: Loops

Slide 6- 53

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.

Page 39: Chapter 5: Loops

Slide 6- 54

Page 40: Chapter 5: Loops

Slide 6- 55

The function call in line 18 passes value1, value2, and value3 as arguments to the function.

Page 41: Chapter 5: Loops

Slide 6- 56

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

Page 42: Chapter 5: Loops

Slide 6- 57

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 }

Page 43: Chapter 5: Loops

Slide 6- 58

Program 6-11(Continued)

Page 44: Chapter 5: Loops

Slide 6- 59

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;}

Page 45: Chapter 5: Loops

Slide 6- 60

A Value-Returning Function

int sum(int num1, int num2){ double result; result = num1 + num2; return result;}

Return Type – Incorrect

Value Being Returned

Page 46: Chapter 5: Loops

Slide 6- 61

A Value-Returning Function

double sum(int num1, int num2){ double result; result = num1 + num2; return result;}

Return Type – Correction – Depending on design of code

Value Being Returned

Page 47: Chapter 5: Loops

Slide 6- 62

A Value-Returning Function

int sum(int num1, int num2){ int result; result = num1 + num2; return result;}

Return Type – Correction – Depending on design of code

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

Page 48: Chapter 5: Loops

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( ).

Page 49: Chapter 5: Loops

//function prototypesdouble inputFahrenheit( ); //reads fahrenheit temp from userdouble convertFahenheitToCelsius(double); //converts fahren temp to celsiusvoid displayConvertedDegree (double, double); //displays converted temperatureint 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;}

Page 50: Chapter 5: Loops

• Output:Please enter the temperature recorded in Fahreheit that you wish to be converted to Celsius: 3232 Fahrenheit is 0 Celsius.

• This program consists of 4 functionsmain( )inputFahrenheitToCelsius( )convertFahrenheitToCelsius( )displayConvertedDegree( )

Page 51: Chapter 5: Loops

Slide 6- 67

Local Variables

Page 52: Chapter 5: Loops

Slide 6- 69

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

Page 53: Chapter 5: Loops

Chapter 7:

Arrays

Page 54: Chapter 5: Loops

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 array5, in [5], is the size declarator. It

shows the number of elements in the array.

Page 55: Chapter 5: Loops

Slide 7- 74

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.0 1 2 3 4

subscripts:

Page 56: Chapter 5: Loops

Slide 7- 75

(Program Continues)

Page 57: Chapter 5: Loops

Slide 7- 76

Here are the contents of the hours array, with the values entered by the user in the example output: