Simple Control Structures

Slides:



Advertisements
Similar presentations
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Advertisements

10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
11-Jun-15 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Additional control structures. The if-else statement The if-else statement chooses which of two statements to execute The if-else statement has the form:
16-Jun-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
2-1 Making Decisions Sample assignment statements PayAmount = Hours * Rate PayAmount = 40*Rate + (Hours – 40)*Rate*1.5.
Introduction to Programming with Java, for Beginners Control Structures.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSci 125 Lecture 10 Martin van Bommel. Simple Statements Expression followed by semicolon Assignments total = n1 + n2; Function calls printf(”Hello.\n”);
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Decision Structures and Boolean Logic
2440: 211 Interactive Web Programming Expressions & Operators.
1 Relational Expressions Relational expressions: –Expressions that compare operands –Sometimes called conditions –Evaluated to yield a result –Typically.
CONTROLLING PROGRAM FLOW
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.
If…else statements. Boolean Expressions Boolean expression - An expression whose value is either true or false true = 1 false = 0 Datatype: boolean.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CCSA 221 Programming in C CHAPTER 6 MAKING DECISIONS 1.
Agenda Basic Logic Purpose if statement if / else statement
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Week 8: Decisions Bryan Burlingame 21 October 2015.
Programming Fundamentals. Today’s Lecture The Conditional Operator Logical Operators Structures Enumerations.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Conditions, Logical Expressions, and Selection Control Structures ROBERT REAVES.
CSCI 161 Lecture 7 Martin van Bommel. Control Statements Statements that affect the sequence of execution of other statements Normal is sequential May.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Fluency with Information Technology Third Edition by Lawrence Snyder Chapter.
19-Feb-16 Simple Control Structures boolean s, the if statement, and the while loop.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
Just Enough Java 29-Sep-17.
Discussion 4 eecs 183 Hannah Westra.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Based on slides by Shawn.
CMSC201 Computer Science I for Majors Lecture 03 – Operators
VBScript Session 3.
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Chapter 3: Decisions and Loops
Overview: Programming Concepts
Chapter 3 Edited by JJ Shepherd
Debugging and Random Numbers
Week 4 - Monday CS 121.
Operator Precedence Operators Precedence Parentheses () unary
Topics The if Statement The if-else Statement Comparing Strings
CMSC201 Computer Science I for Majors Lecture 03 – Operators
Topics The if Statement The if-else Statement Comparing Strings
2-1 Making Decisions Sample assignment statements
Chapter 8 JavaScript: Control Statements, Part 2
Variables Numbers can be stored and retrieved while a program is running if they are given a home. The way that integers and decimal numbers are stored.
C Operators, Operands, Expressions & Statements
Introduction to Primitive Data types
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Simple Control Structures
Javascript Chapter 19 and 20 5/3/2019.
Additional control structures
CprE 185: Intro to Problem Solving (using C)
Just Enough Java 17-May-19.
OPERATORS in C Programming
CSC215 Lecture Control Flow.
Introduction to Primitive Data types
Presentation transcript:

Simple Control Structures booleans, the if statement, and the while loop 2-May-19

What are control structures? You can’t do very much if your program consists of just a list of commands to be done in order The program cannot choose whether or not to perform a command The program cannot perform the same command more than once Such programs are extremely limited! Control structures allow a program to base its behavior on the values of variables

For C and C++ programmers only Statement types are almost identical to those in C and C++ Main difference: true/false conditions must be boolean, not numeric! Some unusual uses of the comma in for statements are not permitted in Java There are two new statement types (try and assert) which we won’t talk about today

boolean boolean is one of the eight primitive types booleans are used to make yes/no decisions All control structures use booleans There are exactly two boolean values, true (“yes”) and false (“no”) boolean, true, and false are all lowercase booleans are named after George Boole, the founder of Boolean logic

Declaring boolean variables boolean variables are declared like any other kind of variable: boolean hungry; boolean passingGrade; boolean taskCompleted = false; boolean values can be assigned to boolean variables: taskCompleted = true;

Numeric comparisons The following numeric comparisons each give a boolean result: x < y // is x less than y? x <= y // is x less than or equal to y? x == y // is x equal to y? (do not use =) x != y // is x unequal to y? x >= y // is x greater than or equal to y? x > y // is x greater than y? Reminder: Don’t use == or != for floating-point numbers

The if statement The if statement has the form: Examples: if (boolean-expression) statement Examples: if (passingGrade) System.out.println("Whew!"); if (x > largest) largest = x; if (citBook.price < 40.00) citBook.purchase(); The if statement controls one other statement Often this isn’t enough; we want to control a group of statements

Compound statements We can use braces to group together several statements into one “compound” statement: { statement; statement; ...; statement; } Braces can group any number of statements: { } // OK--this is an “empty” statement { x = 0; } // OK--braces don’t hurt { temp = x; x = y; y = temp; } //typical use The compound statement is the only kind of statement that does not end with a semicolon

The if statement again The if statement controls one other statement, but it can be a compound statement Example: if (cost < amountInPocket) { System.out.println("Spending $" + cost); amountInPocket = amountInPocket - cost; } It’s good style to use braces even if the if statement controls only a single statement: if (cost > amountInPocket) { System.out.println("You can't afford it!"); } I personally make an exception to this style rule when the controlled statement fits easily on the same line with the if: if (x < 0) x = -x; // use absolute value of x

Flowchart for the if statement condition? statement true false

The if-else statement The if-else statement chooses which of two statements to execute The if-else statement has the form: if (condition) statement-to-execute-if-true ; else statement-to-execute-if-false ; Either statement (or both) may be a compound statement Notice the semicolon after each controlled statement

Example if-else statements if (x >= 0) absX = x; else absX = -x; if (itemCost <= bankBalance) { writeCheck(itemCost); bankBalance = bankBalance - itemCost; } else { callHome(); askForMoreMoney(2 * itemCost); }

Flowchart for the if-else statement condition? true statement-1 statement-2 false

Aside: the “mod” operator The modulo, or “mod,” operator returns the remainder of an integer division The symbol for this operation is % Examples: 57 % 10 gives 7 20 % 6 gives 2 Useful rule: x is divisible by y if x % y == 0 If the left operand is negative, the result is negative (or zero) Examples: -20 % 3 = -2, 20 % -3 = 2, -20 % -3 = -2

Nesting if (or if-then) statements A year is a leap year if it is divisible by 4 but not by 100, unless it is also divisible by 400 if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) leapYear = true; else leapYear = false; } else leapYear = true; } else leapYear = false;

Operations on booleans Assume p and q are booleans There are four basic operations on booleans: Negation (“not”): !p is true if p is false (and false otherwise) Conjunction (“and”): p && q is true if both p and q are true Disjunction (“or”): p || q is true if either of p and q is true Exclusive or (“xor”): p ^ q is true if just one of p and q is true

Simpler tests A simpler leap-year test: if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) leapYear = true; else leapYear = false; An even simpler leap-year test: leapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);

The while loop This is the form of the while loop: while (condition) statement ; If the condition is true, the statement is executed, then the whole thing is done again The statement is executed repeatedly until the condition becomes false If the condition starts out false, the statement is never executed at all

Flowchart for the while loop condition? statement true false

Countdown example seconds = 5; while (seconds > 0) { System.out.print(seconds + "..."); seconds = seconds - 1; } System.out.println("Blast off!"); Result: 5...4...3...2...1...Blast off!

The End “640K ought to be enough for anybody.” --Bill Gates, 1981