CPS120: Introduction to Computer Science Decision Making in Programs.

Slides:



Advertisements
Similar presentations
Flow Control if, while, do-while Juan Marquez (03_flow_control.ppt)
Advertisements

True or false A variable of type char can hold the value 301. ( F )
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 5: Loops and Files.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSC 200 Lecture 4 Matt Kayala 1/30/06. Learning Objectives Boolean Expressions –Building, Evaluating & Precedence Rules Branching Mechanisms –if-else.
Objectives You should be able to describe:
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Flow of Control. 2 Control Structures Control structure: An instruction that determines the order in which other instructions in a program are executed.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120 Introduction to Computer Science Iteration (Looping)
Chapter 4 Selection Structures: Making Decisions.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
CPS120: Introduction to Computer Science
CPS120 Introduction to Computer Programming The Programming Process.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
Control Structures By Shyam Gurram. Control Structure In this chapter we have two different types of structures. Conditional Structure Iterative Control.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
CPS120: Introduction to Computer Science Functions.
1 Chapter 9 Additional Control Structures Dale/Weems.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Controlling Execution Dong Shao, Nanjing Unviersity.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
CPS120: Introduction to Computer Science Lecture 14 Functions.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Control Structures CPS120: Introduction to Computer Science Lecture 5.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
1 CS161 Introduction to Computer Science Topic #9.
JavaScript, Fourth Edition
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
CPS120 Introduction to Computer Science Iteration (Looping)
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
Loops and Files. 5.1 The Increment and Decrement Operators.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
CPS120: Introduction to Computer Science Decision Making in Programs.
JavaScript and Ajax (Control Structures) Week 4 Web site:
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Suppose we want to print out the word MISSISSIPPI in big letters.
CPS120: Introduction to Computer Science
CPS120: Introduction to Computer Science
Chapter 4: Control Structures I (Selection)
Flow of Control.
Repetition Statements (Loops) - 2
Control Statements Paritosh Srivastava.
CPS120: Introduction to Computer Science
Presentation transcript:

CPS120: Introduction to Computer Science Decision Making in Programs

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

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

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

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: *, /, % +, -, =, ==, != ! && ||

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

Selection Statements Flow of control of if statement

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

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

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

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

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

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

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

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

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

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

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.

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

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

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

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

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

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

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

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.

‘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

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

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

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

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.

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

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.

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

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

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

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

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

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

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

Functions -- Flow of Control Subprogram flow of control

Returning a Value Subprogram flow of control

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

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)

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.

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.

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

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

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.

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

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

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

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

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

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.