The if Statement and Practice Problems



Similar documents
9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

While Loop. 6. Iteration

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Conditional Statements Summer 2010 Margaret Reid-Miller

Conditionals (with solutions)

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Conditions & Boolean Expressions

Lecture 2 Notes: Flow of Control

Chapter 8 Selection 8-1

The While Loop. Objectives. Textbook. WHILE Loops

Moving from C++ to VBA

Chapter 5. Selection 5-1

Answers to Review Questions Chapter 7

J a v a Quiz (Unit 3, Test 0 Practice)

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Statements and Control Flow

Passing 1D arrays to functions.

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

13 Classes & Objects with Constructors/Destructors

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

6. Control Structures

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Chapter 2 Introduction to Java programming

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Selection Statements

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Topic 11 Scanner object, conditional execution

7.7 Case Study: Calculating Depreciation

Comp151. Definitions & Declarations

CS 241 Data Organization Coding Standards

Sample CSE8A midterm Multiple Choice (circle one)

Part I. Multiple Choice Questions (2 points each):

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Basics of I/O Streams and File I/O

C++FA 5.1 PRACTICE MID-TERM EXAM

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Chapter One Introduction to Programming

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?

COMPUTER SCIENCE 1999 (Delhi Board)

COMP 110 Prasun Dewan 1

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Answers to Mini-Quizzes and Labs

Member Functions of the istream Class

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Example of a Java program

C++ Input/Output: Streams

Ch 7-1. Object-Oriented Programming and Classes

Variables, Constants, and Data Types

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

if and if-else: Part 1

Computer Programming C++ Classes and Objects 15 th Lecture

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Iteration CHAPTER 6. Topic Summary

1. The First Visual C++ Program

Common Beginner C++ Programming Mistakes

VB.NET Programming Fundamentals

C++ Language Tutorial

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

While and Do-While Loops Summer 2010 Margaret Reid-Miller

JavaScript: Control Statements I

Formatting Numbers with C++ Output Streams

Informatica e Sistemi in Tempo Reale

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Chapter 3 Operators and Control Flow

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Compiler Construction

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

CS106A, Stanford Handout #38. Strings and Chars

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

UEE1302 (1102) F10 Introduction to Computers and Programming

Moving from CS 61A Scheme to CS 61B Java

CISC 181 Project 3 Designing Classes for Bank Accounts

Bash shell programming Part II Control statements

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

F ahrenheit = 9 Celsius + 32

Object Oriented Software Design

Fundamentals of Programming

Project 2: Bejeweled

Special Directions for this Test

3/13/2012. Writing Simple C Programs. ESc101: Decision making using if-else and switch statements. Writing Simple C Programs

Transcription:

The if Statement and Practice Problems The Simple if Statement Use To specify the conditions under which a statement or group of statements should be executed. Form if (boolean-expression) statement; where if is a reserved word, boolean-expression is an expression that evaluates to true or false, and statement is a C++ statement or a group of statements enclosed in curly braces (a compound statement). Action If the boolean expression is true, the specified statement is executed; otherwise it is not. In either case, execution continues with the next statement in the program. Examples // grade is a char if (grade == A ) cout << "EXCELLENT WORK!" << endl; ----------------------------------------------------------------------------- // yards is an int if (yards!= 0) cout << "There were " << yards << " yards." << endl; ----------------------------------------------------------------------------- // temperature, normaltemp and degreesoffever are doubles; // hasfever is a bool if (temperature > normaltemp) { degreesoffever = temperature - normaltemp; hasfever = true; 1

The if- Statement Use To choose exactly one out of two statements (possibly compound statements) to be executed; specifies the conditions under which the first statement is to be executed and provides an alternative statement to execute if these conditions are not met. Form if (boolean-expression) statement-1; statement-2; where if and are reserved words, boolean-expression is an expression that evaluates to true or false, and statement-1 and statement-2 are C++ statements (possibly compound statements, i.e. a group of statements enclosed by curly braces). Action If the boolean expression is true, statement-1 is executed and statement-2 is skipped; otherwise statement-1 is skipped and statement-2 is executed. In either case, execution continues with the next statement in the program. Examples // numitems is an int; averagecost and totalcost are doubles if (numitems >= 0) averagecost = totalcost / numitems; cout << "No items were purchased." << endl; --------------------------------------------------------------------- const double POLLUTION_CUTOFF = 3.5; // pollutionindexis a double if (pollutionindex < POLLUTION_CUTOFF) cout << "Safe Condition" << endl; cout << "Hazardous Condition" << endl; 2

The Extended-if Statement Use To choose one statement (possibly compound) to be executed from among a group of statements (possibly compound); specifies the conditions under which each statement may be executed and may contain a default statement (in an clause at the end) to be executed if none of these conditions are met. Note that in the absence of a final clause, it may be the case that none of the statements are executed. Form if (boolean-expression-1) statement-1; if (boolean-expression-2) statement-2;... if (boolean-expression-n) statement-n; statement-default; where if and are reserved words, boolean-expression-1, boolean-expression-2,..., boolean-expression-n are expressions that evaluate to true or false, and statement-1, statement-2,..., statement-n, and statement-default are C++ statements, possibly compound statements. (A compound statement is a group of statements enclosed by curly braces.) Action The boolean expressions are evaluated in the order of their appearance to determine the first expression that is true. The associated statement is executed, and execution continues with the first statement following the entire if--if construct. If none of the boolean expressions is true, the statement associated with the clause is executed, and execution then continues with the statement following the construct. If none of the boolean expressions is true and the clause is omitted, execution falls through to (continues with) the next statement in the program after the construct. Examples (next page) 3

Examples // score is a double; grade is a char if (score == 100) { grade = A ; cout << "Superb" << endl; if (score >= 90) { grade = A ; cout << "Excellent" << endl; if (score >= 80) { grade = B ; cout << "Very Good" << endl; if (score >= 70) { grade = C ; cout << "Good" << endl; if (score >= 60) grade = D ; grade = F ; --------------------------------------------------------------- // Ch is a char if ((Ch >= a ) && (Ch <= z )) { // code to process lower-case leter if ((Ch >= A ) && (Ch <= Z )) { // code to process upper-case leter if ((Ch >= 0 ) && (Ch <= 9 )) { // code to process digit character { // code to process non-letter/non-digit characters 4

Practice Problems What is wrong with the following if statement (there are at least 3 errors). The indentation indicates the desired behavior. if numneighbors >= 3 numneighbors = 4 ++numneighbors; cout << "You are dead!" << endl; --numneighbors; Describe the output produced by this poorly indented program segment: int number = 4; double alpha = -1.0; if (number > 0) if (alpha > 0) cout << "Here I am!" << endl; cout << "No, I m here!" << endl; cout << "No, actually, I m here!" << endl; Consider the following if statement, where doessignificantwork, makesbreakthrough, and nobelprizecandidate are all boolean variables: if (doessignificantwork) { if (makesbreakthrough) nobelprizecandidate = true; nobelprizecandidate = false; if (!doessignificantwork) nobelprizecandidate = false; First, write a simpler if statement that is equivalent to this one. Then write a single assignment statement that does the same thing. Write if statements to do the following: If character variable taxcode is T, increase price by adding the taxrate percentage of price to it. If integer variable opcode has the value 1, read in double values for X and Y and calculate and print their sum. 5

If integer variable currentnumber is odd, change its value so that it is now 3 times currentnumber plus 1, otherwise change its value so that it is now half of currentnumber (rounded down when currentnumber is odd). Assign true to the boolean variable leapyear if the integer variable year is a leap year. (A leap year is a multiple of 4, and if it is a multiple of 100, it must also be a multiple of 400.) Assign a value to double variable cost depending on the value of integer variable distance as follows: Distance Cost ----------------------------------- ---------- 0 through 100 5.00 More than 100 but not more than 500 8.00 More than 500 but less than 1,000 10.00 1,000 or more 12.00 6