Compound Statements If you want to do more than one statement if an IF- else case, you can form a block of statements, or compound statement, by enclosing.

Slides:



Advertisements
Similar presentations
The if-else Statements
Advertisements

8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Creating PHP Pages Chapter 7 PHP Decisions Making.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
INSTRUCTOR: SHIH-SHINH HUANG Windows Programming Using Java Chapter4: Control Statements Part I.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
Computer Science 1620 Loops.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
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.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Repetition Statements repeat block of code until a condition is satisfied also called loops Java supports 3 kinds of loops: while statement – repeats a.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
JAVA Control Statement.
UNIT II Decision Making And Branching Decision Making And Looping
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Flow of Control Part 1: Selection
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
1 Chapter 9 Additional Control Structures Dale/Weems.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Chapter 5: Structured Programming
Compound Statements If you want to do more than one statement if an if- else case, you can form a block of statements, or compound statement, by enclosing.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Introduction to Java Java Translation Program Structure
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.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Calvin College Controlling Behavior The if, switch and for Statements.
Application development with Java Lecture 6 Rina Zviel-Girshin.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control Statements: Part1  if, if…else, switch 1.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
ECE122 Feb 10, Unary Operator An operator that takes only a single operand Plus: + Minus: – Cast: (type). E.g. (double)
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Lecture 4b Repeating With Loops
Selections Java.
The switch Statement, and Introduction to Looping
JavaScript: Control Statements.
JavaScript: Control Statements I
3 Control Statements:.
Control Statements Paritosh Srivastava.
Control Statements:.
Presentation transcript:

Compound Statements If you want to do more than one statement if an IF- else case, you can form a block of statements, or compound statement, by enclosing the list of statements in curly braces ({ }). The statements in side of the braces will be executed sequentially, and the block counts as one statement.

Compound Statement Example if (a > b) { c = a; System.out.println(a); } else { c = b; System.out.println(b); }

IF statement If there is nothing to do if the test is fals e, then the else part of the statement can be omitted, leaving just an IF statement: if (n > 0) n = n + 1;

Nested If statements If statements can be nested, that is, the statement to be done when the test is true (or false) can also be an If statement. Consider printing out three numbers in order:

An Extended Example if(a > b) if(b > c) System.out.println(a + " " + b + " " + c); else // b <= c if(a > c) System.out.println(a + " " + c + " " + b); else // a <= c System.out.println(c + " " + a + " " + b); else // a <= b if(a > c) System.out.println(b + " " + a + " " + c); else // a <= c...

Multi-way If-else Statement If the statement that is done when the test is false is also an If statement, it is customary to write the else and the if on one line: if(b > c) System.out.prinln(a + " " + b + " " + c); else if(a > c) is written if (b > c) System.out.print(a + " " + b + " " + c); else if (a > c)

More on Multi-way If Statements This is common when there are a number of possibilities based on the value of a variable: if (bedSoftness > 10) System.out.println("Too hard!"); else if(bedSoftness > 5) System.out.println("Just right!"); else System.out.println("Too soft!");

Dangling Else Problem Consider the following code: if (a > b) if (b > c) System.out.println(c); else System.out.println(b); Does the else go with if(a > b) or with if (b > c) ?

Answer It goes with the last if statement that is without an else, that, is if(b > c).

The Switch Statement If there are many cases the depend on the exact value of an int or char variable, rather than on ranges, we could use a multi-way if statement: if (class == 1) System.out.println("COSC 150"); else if (class == 2) System.out.println("COSC 160"); else if (class == 3) System.out.println("COSC 507");

The Switch Statement (cont'd) Or, we could use the switch statement, which implements multi-way branches based on the value of an expression. switch (class) { case 1: System.out.println("COSC 150"); break; case 2: System.out.println("COSC 160"); break; case 3: System.out.println("COSC 507"); break; default: System.out.println("Illegal value"); break; }

The Switch statement (cont'd) What the switch statement does depends on the controlling expression, given in parentheses. If the value matches one of the cases, that code is done. Without the break statement, the next case is also done. The break statement forces the program to bypass the rest of the cases. The default case is done if the value doesn't match any of the cases.

The Break Statement The use (or non-use) of the break statement gives the programming greater flexibility. You decide if the next case is to be done or not. The reason you might want the next case to be done is that often different values should be processed the same way: switch (inputCommand) { case 'A': case 'a': System.out.println("command a"); break; case 'C': case 'c': System.out.println("command c"); break; }

Multi-way If vs. Switch The switch statement is more compact than the multi-way if statement and should be used when the code to be done is based on the value of an int or char expression. However, the switch statement cannot be floating point expressions and so the multi-way if statement must be used. The switch statement may be used for strings in Java SE 7 and later.

Enumerated Types Often, a problem uses a set of named literals (constants), e.g., the months of the year, or the days of the week. Good programming practice says that we should use mnemonic names rather that numbers to represent such items. Instead of creating twelve (or seven) constants, we can use an enumerated type – that is create a set of new literals to represent the items.

Enumerated Type Examples public enum Month { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEPT, OCT, NOV, DEC }; public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };

Using an Enumerated Type Enumerated types can be used with the Switch statement: Month m; switch (m) { case JAN: break; case FEB: break;... case DEC: break; }

The Conditional Operator The conditional operator (my personal favorite of all the operators) is a trinary operator (three operands) which evaluates a test (Boolean expression) and based on the value of the expression, takes its value from one of two other expressions (the true-case value or the false-case value). It is similar to an if- else statement, but can be used in an expression.

Conditional Operator Example System.out.println(a > b ? a : b); is more succinct than the if-else statement if (a > b) System.out.println(a); else System.out.println(b);

Reading in a char via Scanner The Scanner class has a nextInt() method, and a nextDouble() method, but no nextChar() method. To read in a character, you must read in a String (using the next() method) and then extract the first character. The code is: char c = sc.next().charAt(0);

Exercise Write a Java program that reads in a char from the user and then a number (double). If the char is 'C' or 'c', then the number is the radius of a circle. If the char is 'S' or 's', then the number is the side of a square. If the letter is 'G' or 'g' then the number is the radius of a sphere. The program should then print out the area of the object.

Exercise (cont'd) Your program should: Read in a char shape Read in a double d Use a multi-way if statement or a switch statement to distinguish the choices Calculate the area (vol) of the object and print it out Circle = PI * d 2 ; Square == d 2 ; Sphere: 4/3 * PI * d 3

Loops Use to repeat steps Different kinds: Count-controlled: when you know ahead of time how many times to loop Sentinel-controlled: when reading until a special value General Condition: Arbitrary loop Three Java statements to implement loops: while, do-while, and for.

Count-Controlled Loops If you know the number of times you want to repeat a section of code, you can use a count-controlled loop. A for-statement is usually used. The syntax is: for(int i = 0; i < 10; i++) Note the use of semicolons to separate the parts of the for statement. If the loop body is more than one statement, braces may be used.

Anatomy of a For Statement Here is a close-up of the For statement:  int i = 0; // initialization  i < 10; // test  i++ // increment The variable i is the loop index. First it is initialized to 0. Then before the loop body is executed, the test is checked. If the test evaluates to true the loop body is executed and the increment is done.

Anatomy of a For Statem't (cont'd) If the test evaluates to the false, the loop is done, and the program continues with the next line following the loop. Note: The loop index is only valid inside of the loop. Once the loop is finished, that i becomes meaningless.

Syntax The syntax of a For statement is: for( ; ; ) Any of the the parts may be omitted. For example, for(;;) is an infinite loop.

Example for (int i=0; i<10; i++) System.out.println(i + "^2 = " + i*i); would print out: 0^2 = 0 1^2 = 1 2^2 = 4 3^2 = 9 4^2 = 16 5^2 = 25 6^2 = 36 7^2 = 49 8^2 = 64 9^2 = 81

Note on Example The index of loop goes from 0 to 9, inclusive, and not from 0 to 10. It is a Java idiom to begin loops at 0, since arrays start at 0. Thus to repeat code ten times, the test is “i < 10” and not “i <= 10.”

Potential Pitfall It is a bad idea to change the value of the loop index inside of the loop. For example, for (int i=0; i<10; i++) { System.out.println(i + "^2 = " + i*i); i++; } would print out: 0^2 = 0 2^2 = 4 4^2 = 16 6^2 = 36 8^2 = 64

Potential Pitfall (cont'd) In this case, it would be better to use a different increment step, e.g., i = i + 2. Another case where programmers change the index variable is to jump out the loop prematurely, e.g., set i to 10. It is better to use the break statement to jump out of the loop this way.

Break, Continue, and Return The break statement can be used to jump out of a loop prematurely. Control passes to the statement following the loop. The continue statement will cause the program to skip over any remaining part of the loop body and begin the next iteration of the loop. The return statement will exit the method that the loop is in.

Example int a = 5, b = 7; for (int i=0; i<10; i++) { a = a * b; if(a > 1000) // too big break; } System.out.println(a);

Nested Loops Loops, including For statements, may be nested, that is, one loop is included in the loop body of another loop. This is useful for processing 2-dimensional tables. The loop indices must be different variables.

Example for(int i=1; i<= 10; i++) { for(int j=1; j<= 10; j++) System.out.printf( " %3d", i * j); System.out.println(); } will print out the multiplication table.

Exercise Write a loop that will read in 25 numbers (ints) and will print out the smallest number read in.

While Statement In addition to the For statement, Java contains the While statement, which allows code to be repeated while an arbitrary condition holds. For example: while(a < b) a *= 2; is a while loop. The loop continues as long as a is less than b, and halts when a becomes greater than or equal to b.

Using a While for a For A While statement could be used instead of a For statement. The For statement: for(int i=0; i<25; i++) could be re-written as: int i = 0; while(i < 25) { i++; }

Sentinel Controlled Loop A sentinel-controlled loop reads values until a special value (the sentinel) is read, which cannot be a valid. For example, if the program is reading in grades, then a negative number could be used for the sentinel, as it is not a valid grade.

Example total = 0; grade = sc.nextInt(); while(grade >= 0) { total += grade; grade = sc.nextInt(); }