slide1 n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter 5: Loops PowerPoint Presentation
Download Presentation
Chapter 5: Loops

Loading in 2 Seconds...

play fullscreen
1 / 57

Chapter 5: Loops - PowerPoint PPT Presentation


  • 79 Views
  • Uploaded on

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;

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Chapter 5: Loops' - xander


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
slide2

Outline

  • Increment and Decrement
  • while loop
  • do-while loop
  • for loop

Slide 5- 2

slide3

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

slide4

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

Slide 5- 4

slide5

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

slide6

Prefix vs. Postfix - Examples

int num, val = 12;

cout << val++; // displays 12,

// val is now 13;

cout << ++val; // sets val to 14,

// then displays 14

num = --val; // sets val to 13,

// stores 13 in num

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

// sets val to 12

Slide 5- 7

slide7

Introduction to Loops: The while Loop

The general form of the while statement is:

while (expression)

statement;

OR

while (expression)

{

statement1;

statement2;

}

while is a pretest loop
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++;}

an infinite loop
An Infinite Loop

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

the power of the while statement
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 )

{

intnum = 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 statement1
The Power of the while statement

Note: 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).

slide14

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 ;

the for loop
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
    • Performinitialization
    • Evaluate test expression
      • If true, execute statement
      • If false, terminate loop execution
    • Execute update, then re-evaluate test expression
for loop pretest loop
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;
keeping a running total
Keeping a Running Total
  • running total: accumulated sum of numbers from each repetition of loop
  • accumulator: variable that holds running total

intsum=0, num=1; // sum is the accumulator

while (num <= 10)

{ sum += num;

num++;

}

cout << "Sum of numbers 1 – 10 is"

<< sum << endl;

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

example
Example

for (inti = 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.

output1
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

slide25

Chapter 6:

Functions

outline
Outline
  • What is “Function”
  • Sending data into function
  • The return statement
  • Local and Global variables
calling a function
Calling a Function

voidprintHeading()

{

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.
function prototypes
Function Prototypes
  • Ways to notify the compiler about a function before a call to the function:
    • 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();
sending data into a function
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.

parameters prototypes and function headers
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

passing multiple arguments
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.
the return statement
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
the return statement1
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 }
returning a value from a function
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;}

a value returning function
A Value-Returning Function

Return Type – Incorrect

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

Value Being Returned

a value returning function1
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

a value returning function2
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

calling function to receive the value
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( ).

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

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

global variables
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
arrays hold multiple values
Arrays Hold Multiple Values
  • Declared using [] operator:

inttests[5]; // definition

intis 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
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:

slide57

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