Loops and Logic. Making Decisions Conditional operator Switch Statement Variable scope Loops Assertions.

Slides:



Advertisements
Similar presentations
Introduction to Control Statements Presented by: Parminder Singh BCA 5 th Sem. [ Batch] PCTE, Ludhiana 5/12/ Control Statements.
Advertisements

5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
1 Control Statements Lecture 6 from Chapter 5. 2 Three principles of OOP- Encapsulation Encapsulation allows changes to code to be more easily made. It.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
CSCI1402: Lecture 1 Week 6 Dr. David A. Elizondo Centre for Computational Intelligence School of Computing Office: Gateway 6.61
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.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CSCI1402: Lecture 2 Week 6 Dr. David A. Elizondo Centre for Computational Intelligence School of Computing Office: Gateway 6.61
Arrays, Conditionals & Loops in Java. Arrays in Java Arrays in Java, are a way to store collections of items into a single unit. The array has some number.
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
JAVA Control Statement.
UNIT II Decision Making And Branching Decision Making And Looping
L EC. 03: C ONTROL STATEMENTS Fall Java Programming.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
Chapter 4 Program Control Statements
MPL Week #02  Primitive Data Types  Comments  The for Statement  The if Statement  The while and do while Statements  The switch Statement  The.
Control Structures if else do while continue break switch case return for.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Chapter 4 คำสั่งควบคุม (control statement) If statement Switch statement While loop and do-while loop For loop and for-each loop Break and continue 1.
Chapter 5 Loops.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Lecture 4 Control Structures MIT – AITI What are Control Structures? Control structures are a way to alter the natural sequence of execution in.
 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
Decision making statements. Decision making statements are used to skip or to execute a group of statements based on the result of some condition. The.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Chapter 5: Control Structures II
Sahar Mosleh California State University San MarcosPage 1 Program Control 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.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
S ystem P rogrammers' A ssociation for R esearching C omputer S ystems 4. Controlling Execution SPARCS JAVA Study.
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Application development with Java Lecture 6 Rina Zviel-Girshin.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
CSI 3125, Preliminaries, page 1 Control Statements.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Structured Programming Structured Programming is writing a program in terms of only 3 basic control structures: sequence selection repetition We have already.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Core Java Statements in Java.
Java Fundamentals 4.
Lecture 4b Repeating With Loops
Java Language Basics.
Control Structures.
Chapter 5: Control Structures II
Chapter 5: Control Statements
Engineering Problem Solving with C++, Etter/Ingber
Control Statements Lecture 6 from Chapter 5.
CiS 260: App Dev I Chapter 4: Control Structures II.
Chapter 5: Control Structures II
IF if (condition) { Process… }
Outline Altering flow of control Boolean expressions
Lab5 PROGRAMMING 1 Loop chapter4.
OOP With Java/ course1 Sundus Abid-Almuttalib
PROGRAM FLOWCHART Iteration Statements.
Loops CGS3416 Spring 2019 Lecture 7.
REPETITION Why Repetition?
Presentation transcript:

Loops and Logic

Making Decisions Conditional operator Switch Statement Variable scope Loops Assertions

Making Decisions Conditions to be evaluated or tested by the program

If Statement If(condition) { statement 1; statement 2;... statement n; } int a, b;.. if(a < b) a = 0; If(b<10) b = 0;

if...else statement

int a, b; //... if(a < b) a = 0; else b = 0; boolean dataAvailable; //... if (dataAvailable) ProcessData(); else waitForMoreData();

if...else Program import java.lang.Math; public class NumberCheck { public static void main(String[] args) { int number = 0; number = 1+(int)(100*Math.random()); if(number%2 == 0) { // Test if it is even System.out.println(“You have got an even number, “ + number } else { System.out.println(“You have got an odd number, “ + number); }

Nested if statements  Nested if is an if statement that is the target of another if or else. if(number%2 == 0) { if(number < 50) { System.out.println(“You have got an even number < 50, “ + number); } else { System.out.println(“You have got an odd number, “ + number); }

Nested if statements if(i == 10) { if(j < 20) a = b; if(k > 100) c = d; else a = c; } else a = d;

if-else-if Ladder  Sequence of nested ifs is the if-elseif ladder if(condition) statement; else if(condition) statement; else if(condition) statement;. else statement;

if-else-if Ladder Program class IfElse { public static void main(String args[]) { int month = 4; // April String season; if(month == 12 || month == 1 || month == 2) season = "Winter"; else if(month == 3 || month == 4 || month == 5) season = "Spring"; else if(month == 6 || month == 7 || month == 8) season = "Summer"; else if(month == 9 || month == 10 || month == 11) season = "Autumn"; else season = "Bogus Month"; System.out.println("April is in the " + season + "."); }

if-else-if Ladder Program class IfElseDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } Output: Grade = C

Programs The aIsBigger() method should return true if the int parameter a is larger than b by 2 or more. Given two int values, a and b, return true if either one is 6. Or if their sum or difference is 6 Input 3 int a, b and c, write a function that calculate the largest value. You are driving a car. Write code to compute the result. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Calculate Odd or even number Given three ints, a b c, return true if it is possible to add two of the ints to get the third. You have a green lottery ticket, with ints a, b, and c on it. If the numbers are all different from each other, the result is 0. If all of the numbers are the same, the result is 20. If two of the numbers are the same, the result is 10.

switch Multiway branch statement Provides a better alternative than a large series of if-else-if statements switch (expression) { case value1: // statement sequence break; case value2: // statement sequence break;. case valueN : // statement sequence break; default: // default statement sequence }

switch class SampleSwitch { public static void main(String args[]) { Int i=2; switch(i) { case 0: System.out.println("i is zero."); break; case 1: System.out.println("i is one."); break; case 2: System.out.println("i is two."); break; default: System.out.println("i is greater than 2."); }

Nested switch switch(count) { case 1: switch(target) { // nested switch case 0: System.out.println("target is zero"); break; case 1: // no conflicts with outer switch System.out.println("target is one"); break; } break; case 2: //...  Switch within the switch statement

Loops/ Iteration Iteration statements are for, while, and do-while

for Two type : (1) traditional for (11) for-each for for(initialization; condition; iteration) { // body }

How Execute for 1 st initialization portion, sets value to control variable. executed only once. 2 nd, condition is evaluated. It is boolean expression. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates. Next, the iteration portion of the loop is executed. It is increments or decrements the loop control variable

for loop programs class ForTick { public static void main(String args[]) { for(int n=0; n<10; n++) System.out.println("tick " + n); }

for loop programs class FindPrime { public static void main(String args[]) { int num; boolean isPrime; num = 14; if(num < 2) isPrime = false; else isPrime = true; for(int i=2; i <= num/i; i++) { if((num % i) == 0) { isPrime = false; break; } if(isPrime) System.out.println("Prime"); else System.out.println("Not Prime"); }

Comma in for loop class Sample { public static void main(String args[]) { int a, b; b = 4; for(a=1; a<b; a++) { System.out.println("a = " + a); System.out.println("b = " + b); b--; } class Comma { public static void main(String args[]) { int a, b; for(a=1, b=4; a<b; a++, b--) { System.out.println("a = " + a); System.out.println("b = " + b); }

Infinite for loop infinite loop (a loop that never terminates) for( ; ; ) { //... } OR for( ; ; );

For-Each Version for Loop for(type itr-var : collection) statement-block int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; for(int i=0; i < 10; i++) sum += nums[i]; int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; for(int x: nums) sum += x;

Example Program1 // Use a for-each style for loop. class ForEach { public static void main(String args[]) { int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; // use for-each style for to display and sum the values for(int x : nums) { System.out.println("Value is: " + x); sum += x; } System.out.println("Summation: " + sum); }

Example Program2 // Use break with a for-each style for. class ForEach2 { public static void main(String args[]) { int sum = 0; int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // use for to display and sum the values for(int x : nums) { System.out.println("Value is: " + x); sum += x; if(x == 5) break; // stop the loop when 5 is obtained } System.out.println("Summation of first 5 elements: " + sum); }

Example Program3 // The for-each loop is essentially read-only. class NoChange { public static void main(String args[]) { int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for(int x: nums) { System.out.print(x + " "); x = x * 10; // no effect on nums } System.out.println(); for(int x : nums) System.out.print(x + " "); System.out.println(); } Output:

for loop programs

while while(condition) { // body of loop } The body of the loop will be executed as long as the conditional expression is true

while Program // Demonstrate the while loop. class While { public static void main(String args[]) { int n = 10; while(n > 0) { System.out.println("tick " + n); n--; }

do-while Execute the body of a loop at least once, even if the conditional expression is false to begin with. Loop first executes the body of the loop and then evaluates the conditional expression do { // body of loop } while (condition); do { System.out.println("tick " + n); n--; } while(n > 0);

Nested Loops one loop may be inside another. // Loops may be nested. class Nested { public static void main(String args[]) { int i, j; for(i=0; i<10; i++) { for(j=i; j<10; j++) System.out.print("."); System.out.println(); } Output:

Using break using break, you can force immediate termination of a loop, class BreakLoop { public static void main(String args[]) { for(int i=0; i<100; i++) { if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); } System.out.println("Loop complete."); }

Using break // Using break to exit a while loop. class BreakLoop2 { public static void main(String args[]) { int i = 0; while(i < 100) { if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); i++; } System.out.println("Loop complete."); }

labeled break The general form of the labeled break statement is shown here: break label; label is the name of a label that identifies a block of code.

labeled break // Using break as a civilized form of goto. class Break { public static void main(String args[]) { boolean t = true; first: { second: { third: { System.out.println("Before the break."); if(t) break second; // break out of second block System.out.println("This won't execute"); } System.out.println("This won't execute"); } System.out.println("This is after second block."); } Output: Before the break. This is after second block.

Using continue Continue running the loop but stop processing the remainder of the code in its body for this particular iteration. // Demonstrate continue. class Continue { public static void main(String args[]) { for(int i=0; i<10; i++) { System.out.print(i + " "); if (i%2 == 0) continue; System.out.println(""); } Output:

Java Programs