1 / 57

Chapter 5: Loops

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;

xander
Télécharger la présentation

Chapter 5: Loops

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 5: Loops

  2. Outline • Increment and Decrement • while loop • do-while loop • for loop Slide 5- 2

  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++; Slide 5- 3

  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--; Slide 5- 4

  5. 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

  6. 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

  7. Introduction to Loops: The while Loop The general form of the while statement is: while (expression) statement; OR while (expression) { statement1; statement2; }

  8. The Logic of a while Loop

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

  10. An Infinite Loop int number = 1;while (number <= 5){ cout << "Hello\n";}

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

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

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

  14. The Logic of a do-while Loop

  15. 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

  16. A Closer Look at the Previous Example

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

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

  19. 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

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

  21. 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.

  22. 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

  23. Chapter 6: Functions

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

  25. Function Definition

  26. 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.

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

  28. (Program Continues)

  29. 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.

  30. What is the output?

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

  32. 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

  33. 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.

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

  35. 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

  36. 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 }

  37. Program 6-11(Continued)

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

  39. A Value-Returning Function Return Type – Incorrect int sum(int num1, int num2){double result; result = num1 + num2; return result;} Value Being Returned

  40. 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

  41. 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

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

  43. //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;}

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

More Related