C++ Conditions Test Cases

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 2 Flow of Control. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 2-2 Learning Objectives Boolean Expressions Building, Evaluating.
Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
Decisions If statements in C.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
CSC 200 Lecture 4 Matt Kayala 1/30/06. Learning Objectives Boolean Expressions –Building, Evaluating & Precedence Rules Branching Mechanisms –if-else.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Chapter 4 Making Decisions
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
Today’s Lecture  Boolean Expressions  Building, Evaluating & Precedence Rules  Branching Mechanisms  if-else  switch  Nesting if-else  Loops  While,
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Flow of Control Part 1: Selection
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
CPS120: Introduction to Computer Science Decision Making in Programs.
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 2 Flow of Control. Learning Objectives Boolean Expressions – Building, Evaluating & Precedence Rules Branching Mechanisms – if-else – switch –
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
Chapter 4 Making Decision Csc 125 C++ programming language Fall 2005.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 3 (2) & 4 September 8 & 10, 2009.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Selection Structures: if and switch Statements. 2 Selection Statements –In this chapter we study statements that allow alternatives to straight sequential.
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 2 Flow of Control Copyright © 2016 Pearson, Inc. All rights reserved.
Program Flow Control Addis Ababa Institute of Technology Yared Semu April 2012.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Bill Tucker Austin Community College COSC 1315
Review 1.
The if…else Selection Statement
Chapter 3 Control Statements
Data Types and Expressions
Data Types and Expressions
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Flow of Control.
The Selection Structure
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Lecture 2-3 C++ Basic Constructs
Control Structures – Selection
Control Statement Examples
Chapter 4: Control Structures I (Selection)
Introduction to C++ Programming
3 Control Statements:.
Chapter 7 Conditional Statements
Chapter 4 Selection.
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Boolean Expressions to Make Comparisons
Chapter 4: Selection Structures: if and switch Statements
Selection Control Structure
CSS 161: Fundamentals of Computing
Presentation transcript:

C++ Conditions Test Cases COMP 51 Week Three C++ Conditions Test Cases

Learning Objectives Boolean Expressions Flow Charts and Pseudo Code Building, Evaluating & Precedence Rules Flow Charts and Pseudo Code Branching Mechanisms if-else switch Nesting if-else Debugging and Test Cases

Why Do We Care? Fundamental building block for all programming logic Implement real life decisions based upon program input Need to plan for failure!

Getting Logical : Boolean Expressions Logical Operators Logical AND (&&) Logical OR (||)

Evaluating Boolean Expressions Data type bool Returns true or false true, false are predefined library consts State capital example

Display 2.3 Precedence of Operators (1 of 4)

Display 2.3 Precedence of Operators (2 of 4)

Display 2.3 Precedence of Operators (3 of 4)

Display 2.3 Precedence of Operators (4 of 4)

Precedence Examples Arithmetic before logical Short-circuit evaluation x + 1 > 2 || x + 1 < -3 means: X++ > 0 X = sqrt(16) > 2 Short-circuit evaluation int x = 1, y = 1; (x >= 0) || (y++ > 1) What is value of y? Integers as boolean values All non-zero values  true Zero value  false Arithmetic before logical x + 1 > 2 || x + 1 < -3 means: (x + 1) > 2 || (x + 1) < -3 Short-circuit evaluation (x >= 0) && (y > 1) Be careful with increment operators! (x > 1) && (y++) Integers as boolean values All non-zero values  true Zero value  false

Learning Objectives Boolean Expressions Flow Charts and Pseudo Code Building, Evaluating & Precedence Rules Flow Charts and Pseudo Code Branching Mechanisms if-else switch Nesting if-else Debugging and Test Cases

Intro to Flow Charts Basic Shapes Sheldon’s Friendship Algorithm - http://www.youtube.com/watch?v=k0xgjUhEG3U Begin Process Swim Lane Process Step Decision Step Next Process Yes Data Store No Document End Process

You Can Flowchart Anything http://www.youtube.com/watch?v=IIEVqFB4WUo

Flowchart Alternative – Pseudo Code Almost like code Goal – Capture the logic of the problem you are trying to solve Ignore syntax issues Simplify process Speed up development

Pseudo Code Example Calculate the average of a set of numbers Set the total and count to zero Get a number from user Repeat while the number entered is not zero Add the number to the total Increment the count of numbers Get another number from user Set the average to equal the total divided by the count of numbers Display the average.

Learning Objectives Boolean Expressions Flow Charts and Pseudo Code Building, Evaluating & Precedence Rules Flow Charts and Pseudo Code Branching Mechanisms if-else switch Nesting if-else Debugging and Test Cases

Branching Mechanisms if-else statements Example: if (hrs > 40) grossPay = rate*40 + 1.5*rate*(hrs-40); else grossPay = rate*hrs; Hrs > 40 Formal syntax: if (<boolean_expression>) <yes_statement> else <no_statement> Note each alternative is only ONE statement! To have multiple statements execute in either branch  use compound statement No Yes grossPay = regular hours grossPay = overtime hours

C++ If-Else Practice Create a program that calculates over time pay based on previous slide Create a new project – overtimepay Remember your #include and using statement Prompt the user for hours and rate You can copy and paste the code from slide

Compound/Block Statement Must use compound statement { } for multiple statements in a branch Also called a "block" stmt Each block should have block statement Even if just one statement Enhances readability

Compound Statement in Action Note indenting in this example: if (myScore > yourScore) { cout << "I win!\n"; wager = wager + 100; } else { cout << "I wish these were golf scores.\n"; wager -= 100; }

Common Pitfalls Operator "=" vs. operator "==" One means "assignment" (=) One means "equality" (==) VERY different in C++! Example: if (x = 12) Note operator used! Do_Something else Do_Something_Else

The Optional else else clause is optional If, in the false branch (else), you want "nothing" to happen, leave it out Example: if (sales >= minimum) salary = salary + bonus; cout << "Salary = %" << salary; Note: nothing to do for false condition, so there is no else clause! Execution continues with cout statement

Nested Statements if-else statements can contain more if-else statements. Example: if (speed > 65) if (speed > 80) cout << "You’re gonna get pulled over!"; else cout << "You’re driving OK for I-5."; Note proper indenting!

Multiway if-else

switch Statement Syntax Note the multiple branches The controlling expression must be integral! This includes char.

The switch Statement in Action

The switch: multiple case labels Execution "falls thru" until break switch provides a "point of entry" Example: case 'A': case 'a': cout << "Excellent: you got an "A"!\n"; break; case 'B': case 'b': cout << "Good: you got a "B"!\n"; break; Note multiple labels provide same "entry"

switch Pitfalls/Tip Forgetting the break; Biggest use: MENUs No compiler error Execution simply "falls thru" other cases until break; Biggest use: MENUs Provides clearer "big-picture" view Shows menu structure effectively Each branch is one menu choice

switch Menu Example Switch stmt "perfect" for menus: switch (response) { case 1: // Execute menu option 1 break; case 2: // Execute menu option 2 break; case 3: // Execute menu option 3 break; default: cout << "Please enter valid response."; }

C++ Switch Practice Create a new project to print out an employee ranking message Ask the user to enter a number between 1 and 5 Use a switch statement to print out a message A value of 5 results in “Exceeds All Objectives” being displayed 4 results in “Exceeds Most Objectives” 2 or 3 results in “Meets Objectives” 1 results in “Does not Meet Objectives” Anything else should display “Invalid Ranking”

Conditional Operator Also called "ternary operator" Allows embedded conditional in expression Essentially "shorthand if-else" operator Example: if (n1 > n2) max = n1; else max = n2; Can be written: max = (n1 > n2) ? N1 : n2; "?" and ":" form this "ternary" operator Which alternative “reads easier”? Which is more efficient?

Learning Objectives Boolean Expressions Flow Charts and Pseudo Code Building, Evaluating & Precedence Rules Flow Charts and Pseudo Code Branching Mechanisms if-else switch Nesting if-else Debugging and Test Cases

Debugging History Because stuff happens!!!

Unit Test Plan Concepts Does the Program/Function Work? Functional Data Entry – Does Every Field Accept correct data values (Ex. dates, SSN) Validation Rule Checking (Ex. Start Date <= End Date) Calculations Executed Properly (Ex. Sales Tax) Performance Page Load Time Page to page navigation quick Buttons Calculate fast Security User Access to pages Role Setup and Assignment Hacking Attempts http://templateforfree.com/how-to-write-test-cases/

Test Cases and Test First HP Racial Profiling  http://adage.com/bigtent/post?article_id=141184

Logic Test Scenarios Normal Case Boundary Case Error Condition Data is valid, user input is OK Example – Calculate letter grade based on 0-100 score Boundary Case User input is OK Data is at range limit Example – Score = 100, Score = 92.4 Error Condition Bad user input Example – Score = 101, Score =-1

Test Case Template Purpose of the Test Pre-Conditions Post-Conditions Step Action Expected System Response Pass/ Fail Comments

Test Case Example Calculating Letter Grade Purpose of the Test Verify that test score will calculate the appropriate letter grade result Pre-Conditions None Post-Conditions All valid scores entered will have received a letter grade. Step Action Expected System Response Pass/ Fail Comments 1 Enter a number 0 < n < 100 Calculate the appropriate grade 2 Enter 92.4 Grade = A- 3 Enter 100 Prompt user with invalid entry 4 Enter -1 5 Enter A Note – More complex test cases require establishing the initial conditions and sample data prior to executing the test. This must be specified in the test case.

Syntax Errors in Visual Studio Find first occurrence of error Other errors may be a result of the first one Using the output tab in Visual Studio Recommend turning on line numbers for editor. Click on Tools  Options  Text Editor  C/C++  General. Check the Line numbers box. Double click on the error  brings you to the line in the program

Spot the Mistake! int x; cout << "Hello World" cin >> x; cout << "Hello " x ", how are you?\n"; cout >> "Hello World"; #include <isostream> 1>c:\users\ebowring\documents\visual studio 2008\projects\aaa\debugging.cpp(8) : error C2146: syntax error : missing ';' before identifier 'cin‘ 1>c:\users\ebowring\documents\visual studio 2008\projects\aaa\debugging.cpp(7) : error C2146: syntax error : missing ';' before identifier 'x‘ 1>c:\users\ebowring\documents\visual studio 2008\projects\aaa\debugging.cpp(7) : error C2784: 'std::basic_istream<char,_Traits> &std::operator >>(std::basic_istream<char,_Traits> &,unsigned char &)' : could not deduce template argument for 'std::basic_istream<char,_Traits> &' from 'std::ostream' 1>c:\users\ebowring\documents\visual studio 2008\projects\aaa\debugging.cpp(1) : fatal error C1083: Cannot open include file: 'isostream': No such file or directory

Other Common Mistakes Failing to declare a variable before using it Undeclared identifier error Not initializing a variable Warning message is generated Brace mismatch Not using braces on if-then-else

Debugging Main Approaches Print Statements Use cout or cerr Before and after conditions and loops Code Execution or Program Trace Viewer Discussed in Week 8

Key Takeaways What does a Boolean expression result in? It Depends If  Then  Else Switch File I/O What character separates input? Test Early and Test Often!