Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPS120: Introduction to Computer Science Decision Making in Programs.

Similar presentations


Presentation on theme: "CPS120: Introduction to Computer Science Decision Making in Programs."— Presentation transcript:

1 CPS120: Introduction to Computer Science Decision Making in Programs

2 Structural Review: Types of Statements  sequence  selection (if and switch structures)  iteration (for and while loops)  invocation (functions)

3 Using Relational Operators  Relational operators provide the tools with which programs make decisions with true and false evaluations == equal to NOTE: this is two equals symbols next to each other, not to be confused with the assignment operator, = > greater than = greater than or equal to <= less than or equal to != not equal to

4 Order of Logical Operations  Logical operators may be mixed within evaluation statements but the following order of preference must be respected: 1. NOT operator (!) 2. AND operator (&&) 3. OR operator (||)

5 Complete order of operations  The complete order of operations including all of the arithmetic, relational, and logical operators including all of the basic arithmetic, relational, & logical operators is: *, /, % +, -, =, ==, != ! && ||

6 Compare and Branch  A program can instruct a computer to compare two items and do something based on a match or mismatch which, in turn, redirect the sequence of programming instructions.  There are two forms:  IF-THEN  IF-THEN-ELSE

7 Selection Statements Flow of control of if statement

8 Decision Making in C++ 1. if statement 2. switch statement There are also a couple that are arcane: 1. ? conditional operator statement 2. goto statement

9 Levels of Complexity for if  Simple if statement  if … else statement  Nested if … else statement

10 IF-THEN Test condition p falsetrue Entry Exit True statement a

11 Use the “IF” structure  In C++, the if structure is a one-way selection structure: if (number == 3) { cout << "The value of number is 3"; }  IF structures use a control expression to determine if the code in the braces is to be executed or not

12 Using Logical Operators  When complex decisions must be coded into an algorithm, it may be necessary to "chain together" a few relational expressions (that use relational operators)  This is done with logical operators (also called Boolean operators.) ! is the logical NOT operator && is the logical AND operator || is the logical OR operator

13 Compound Conditionals  You can use the AND operator (&&) to form a compound relational expression: if (0 < number && number < 10) { cout << number << " is greater than 0 but less than 10." << endl; }

14 Coding IF Structures  Place a semicolon at the end of each statement within the braces, which can contain many executable statements  Use curly braces around the body of an IF structure even if there is only one statement

15 IF…ELSE falsetrue Entry Exit Test condition p “true” statement a “false” statement a

16 General Form if (test expression) { True-block statements; } else { False-block statements; } next statement;

17 The If … Else statement  Two-way selection structure since either the block of code after the "if" part will be executed or the block of code after the "else" part will be executed  The “If" part is executed if the control expression is TRUE while the "else" part is executed if the "if" part is FALSE, guaranteeing one part of the expression to be executed or the other

18 Nested If Statements  If structures and if/else statements can be nested within one another in order to model complex decision structures.  Use the braces and semicolons properly when coding such structures.

19 General Form if (test condition 1) { // true-block1 statements if (test condition 2) { true-block2 statements; } else { false-block2 statements; } else { false-block1 statements; }

20 Switch Structure  The switch structure is a multiple-selection structure that allows even more complicated decision statements than a two-way if/else structure allows.  It chooses one of the "cases" depending on the result of the control expression.  Only variables with the INT or CHAR data types may be used in the control expressions (i.e. parentheses) of switch statements.  Single quotes must be used around CHAR variables  Single quotes are NOT used around the integer values

21 Sample Switch Structure switch (character_entered) { case ‘A’ : cout << “The character entered was A.\n”; break; case ‘B’: cout << “The character entered was B.\n”; default: cout << “Illegal entry\n”; }

22 Switch Structure  The break statement must be used within each case  When the break statement is executed within a switch, C++ will execute the next statement outside of the switch statement.  The default case, if present, will result if none of the prior cases apply

23 Looping  Loops allow your program to repeat groups of statements a specified number of times.

24 Iterate  A program loop is a form of iteration. A computer can be instructed to repeat instructions under certain conditions.

25 Iteration Control Structures  Loops repeat an activity until stopped. The location of the stopping mechanism determines how the loop will work:  Leading decisions  Trailing decisions

26 Leading Decisions  If the stop is at the beginning of the iteration, then the control is called a leading decision.  The command WHILE performs the iteration and places the stop at the beginning.

27 ‘For’ Loops  A for loop always executes a specific number of times.  Use a for loop when you know exactly how many times a set of statements must be repeated  A for loop is called a determinant or definite loop because the programmer knows exactly how many times it will iterate

28 Syntax of a for Loop for (initializing expression; control expression; step expression) { // one or more statements }  The initializing expression sets the counter variable for the loop to its initial value.  The control expression ends the loop at the specified moment.  The step expression changes the counter variable  Semi-colons, not commas, divide the expressions

29 Things to Remember About For Loops  It is possible to have variable increase by a value other than one  for (num = 1; num <= 10; num = num + 3)  If an if statement only contains one body statement, the compiler doesn't require the use of curly braces

30 WHILE Loop No Yes Entry Exit Test condition p Loop statement a

31 While Loops  A while loop does not necessarily iterate a specified number of times  As long as its control expression is true, a while loop will continue to iterate  An indeterminate or indefinite loop because only at run-time can it be determined how many times it will iterate  While is considered a top-checking loop  The control expression is located on the first line of code  If the control expression initially evaluates to FALSE, the loop will not execute even once.

32 While Loop Syntax while (control expression) { // one or more statements }  The control expression must evaluate to TRUE in order for the while loop to iterate even once

33 Trailing Decisions  If the stop is at the end of the iteration, the control mechanism is called a trailing decision.  The command DO / WHILE performs the iteration and puts the stop at the end of the loop.

34 DO WHILE Loop Loop statement a NoYes Entry Test condition p Exit

35 Do While Loops  As with a while loop, a do while loop does not necessarily iterate a specified number of times  A do while loop will iterate at least one time because its control expression is placed at the end of the loop  Considered to be an indeterminate or indefinite loop  Considered to be a bottom-checking loop, since the control expression is located after the body of the loop

36 Do While Syntax do { // body statements would be placed here }while (control expression);  Don't forget to include the required semicolon after the control expression

37 Break and Continue Statements  A break statement is used to stop the execution of a loop immediately and to continue by executing the statement that comes directly after the loop  A continue statement is used to stop the execution of the statements in the loop's body on that particular iteration and to continue by starting the next iteration of the loop

38 Nested Loops  A loop of any kind may be placed in another loop (of any kind).  Be sure to entirely encapsulate the inner loop inside of the outer loop, otherwise an error is sure to occur.  Two loops are considered to be nested loops if one is enclosed within the other

39 Subprograms / Functions  We can give a section of code a name and use that name as a statement in another part of the program  When the name is encountered, the processing in the other part of the program halts while the named code is executed

40 Passing Information  There are times when the calling unit needs to give information to the subprogram to use in its processing  A parameter list is a list of the identifiers with which the subprogram is to work, along with the types of each identifier placed in parentheses beside the subprogram name

41 Functions -- Flow of Control Subprogram flow of control

42 Returning a Value Subprogram flow of control

43 Subprogram Statements  Parameters: The identifiers listed in parentheses beside the subprogram name; sometimes they are called formal procedures  Arguments: The identifiers listed in parentheses on the subprogram call; sometimes they are called actual parameters

44 Types of Values  Value parameter: a parameter that expects a copy of its argument to be passed by the calling unit (put on the message board)  Reference parameter: a parameter that expects the address of its argument to be passed by the calling unit (put on the message board)

45 Functions  Every C++ program must have a main function  Each of the smaller tasks (let's say, subtasks) can be coded as C++ functions that go together with the main function to make up a structured program.

46 Function Syntax  Functions are given valid identifier names, just like variables.  A function name must be followed by parentheses  Add functions to the bottom of a C++ program, after the main function.  If the functions are listed after the main function, then function prototypes must be included at the top of the program, above the main function  An error will definitely result if you call a function from within the main function that has not been prototyped.

47 Structure of Functions in C++ function-name(argument list) argument declaration; { local variable declarations; executable statement1; executable statement2; ---------- ---------- return (expression); }

48 An Example of A Function #include void printMyMessage(int numOfTimes); // PROTOTYPE and NAME int main( ) { int userInput = 0; cout << "Enter a number between 1 and 10 (0 to Exit): " ; cin >> userInput; if (userInput != 0) { printMyMessage (userInput); // CALL STATEMENT WITH ACTUAL PARAMETER } else cout << "Thanks, Bye!"; return 0; } // end of main void printMyMessage(int numOfTimes)// FUNCTION HEADER WITH RETURN TYPE AND ACTUAL PARAMETER { int i=0; // LOCAL VARIABLE WITHIN THE FUNCTION for (i=0; i<= numOfTimes; i++)// BODY {cout << "Let's Go State!!" << endl;}// OF THE } //end of printMyMessage// FUNCTION

49 Describing a Function  The first line of a function is called the function header  Before the name of the function you must specify a "return type."  The return type is the data type of the value that is returned by the function to the calling function  If the function does not return any value, you must type the word void as the return type  After the name of the function in the function header, you must include a parameter list.  Immediately preceding each parameter, you must identify the data type of that parameter.

50 Returning Values  If the function is not a void function, there must be a return statement at the end of the function

51 Scope of Variables  The scope of a variable is the area in which it can be legally referenced  Variables are either global or local in nature  Global variables are ones that are declared outside and above the main function  They can be used in any function throughout the program.  It is not wise to use global variables any more than you have to.  Local variables are ones that are declared inside of a function, including main. They cannot be used or referred to in other functions

52 Passing Data in C++  Data is passed to functions as arguments  When a function is "called" by the main function one or more arguments are passed to the function  On the receiving end, the function accepts these arguments  The variable names of the arguments from the "calling" function do not have to be the same as the names in the "called" function.  The data types of the arguments and the parameters should match exactly

53 More About Passing Arguments  There are technically three ways to pass data as arguments to functions 1. passing by value is the preferred method. You simply use a variable name, an actual numeric literal, or an expression in the parentheses of the call statement 2. passing by reference is to be used when you want the function to actually and permanently change the values of one or more variables  You must use an ampersand (&) before the formal parameter names in the function header (the first line of the function definition) to denote passing by reference 3. passing by address is technically what happens when you pass an array to a function

54 Another Look at Return Values  Often, though, you want your function to return a computed value to the calling function  It is not possible in C++ to execute two return statements within a function and since it is not possible to return two values in the same return statement

55 Library Functions  There are many functions available to C++ programmers which were written by other programmers  Use the #include compiler directive at the top of your program to take advantage of these functions.  To use the you do not even have to know exactly how they work  You do have to know how many arguments to send to the functions and what datatypes to use for those functions.


Download ppt "CPS120: Introduction to Computer Science Decision Making in Programs."

Similar presentations


Ads by Google