Control Structures. Decision Making Structures The if and if…else are all selection control structures that introduce decision-making ability into a program.

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
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.
July 13 th.  If/ Else if / Else  Variable Scope  Nested if/else's  Switch statements  Conditional Operator.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loops – While, Do, For Repetition Statements Introduction to Arrays
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 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 Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Java Programming: From the Ground Up
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Chapter 5 Loops.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Chapter 3- Flow Control. Overview n Why flow control n Branches vs. Loops n Branch statements n Loop Statements n Complex loops n Boolean variables n.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
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.
Java Prepared by Gary Langner Types of Loops u for loop (entrance controlled) –do an action for a definite number of times u while loop (entrance controlled.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
Control Flow Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
The for loop.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
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.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
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)
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Chapter 4 Repetition Statements (loops)
Loops.
Chapter 3: Decisions and Loops
Chapter 4: Making Decisions.
Chapter 5: Control Structures II
Loop Structures.
Chapter 4: Making Decisions.
Repetition-Sentinel,Flag Loop/Do_While
Flow Control in Java.
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Control Statements Loops.
Control Statements Loops.
Presentation transcript:

Control Structures

Decision Making Structures The if and if…else are all selection control structures that introduce decision-making ability into a program. Based on the truth value of a boolean expression, the computer will decide which path to follow.

The if Statement if (boolean expression) { statements } Here the statements will be executed only if the boolean expression is true. If it is false, control passes immediately to the first statement following the if statement.

Nested if Statement If the statement of an if statement is itself an if statement, the result is a nested if statement. Example 1 if (boolean expression 1) if (boolean expression 2) statement; if(boolean expr1 && boolean expr2) statement

Example 2 int n = I0.readInt(); //read user input if (n > 0) if (n % 2 == 0) System.out.println(n); else System.out.println (n + “ is not positive”); A user enters 7 and is surprised to see the output. 7 is not positive.

The reason 7 is not positive is that else always gets matched with the nearest unpaired if, not the first if as the indented would suggest. We can fix the preceding code: int n = I0.readInt(); //read user input if (n > 0) { if (n % 2 == 0) System.out.println(n); } else System.out.println (n + “ is not positive”);

int n = I0.readInt(); //read user input if (n <= 0) System.out.println(n + “ is not positive”); else if (n % 2 == 0) System.out.println(n);

Extended if Statement String grade = IO.readString(); if (grade.equals(“A”)) System.out.println(“Excellent”); else if (grade.equals(“B”)) System.out.println(“Good”)); else if (grade.equals(“C”)||grade.equals(“D”)) System.out.println(“Poor”);

Iteration Java has three different control structures that allow the computer to perform iterative tasks: the for loop, while loop and the do … while loop. You are not responsible for the do…while loop on the AP exam.

The for Loop The general form for the for loop is for (initialization; termination condition; update statement) { statements //body of loop } The termination condition is tested at the top of the loop; the update statement is performed at the bottom.

Example 1 //outputs for (i = 1; i < 5: i++) System.out.println(i + “ “); The loop variable i is initialized to 1, and the termination condition i =5), control passes to the first statement following the loop.

Example 2 //outputs for (k = 20; k>= 15; k--) System.out.print(k + “ “);

Example 3 //outputs for (j=2; j<=10; j +=2) System.out.print(j+ “ “);

Notes 1.The loop variable should not have its value changed inside the loop body. 2.The initializing and update statements can use any valid constants, variables, or expressions. 3.The scope of the loop variable can be restricted to the loop body by combining the loop variable declaration with the initialization. Definition of scope – the region in which that variable or method is visible and can be accessed.

Example for(int k = 0; k < 3; k++) { }

4.The following loop is syntactically valid: for(int k = 1; k <=0; k++) { } The loop body will not be executed at all, since the exiting condition is true before the first execution.

for-each loop This is used to iterate over an array or collection. The general form of the loop is for(SomeType element: collection) { statements } This is read as “For each element of type SomeType in collection…”)

Example //Outputs all elements of arr, one per line for (int element : arr) System.out.println(element);

Note: 1.The for-each loop cannot be used for replacing or removing elements as you traverse. 2.The loop hides the index variable that is used with arrays.

The while loop The general form of the while loop is while (boolean test) { statement }

The boolean test is performed at the beginning of the loop. If true, the loop body is executed. Otherwise, control passes to the fist statement following the loop. After execution of the loop body, the test is performed again. If true, the loop is executed again, and so on.

Example 1 int k = 1, mult3 = 3; while (mult3 < 20) { System.out.print(mult3 + “ “); k++; mult3 *= k; }//outputs

Example 2 int power2 = 1; while (power2 != 20) { System.out.println(power2); power2 *= 2; } Since power2 will never exactly equal 20, the loop will grind merrily along eventually causing an integer overflow.

Note: 1.It is possible for the body of the while loop never to be executed. This will happen if the test evaluates to false the first time. 2.Disaster will strike in the form of an infinite loop if the test can never be false. Don’t forget to change the loop variable in the body of the loop in a way that leads to termination.

/*Screen out bad data. *The loop won’t allow execution to continue until a valid integer is entered.*/ System.out.println(“Enter a positive integer from 1 to 100”); int num = IO.readInt(); while (num 100) { System.out.println(“Number must be from 1 to 100.”); System.out.println(“Please reenter”); num = IO.readInt(); }

/*Uses a sentinel to terminate data entered at *the keyboard. The sentinel is a value that *cannot be part of the data. It signals the end *of the list. */ final int SENTINEL = -999; System.out.println (“Enter list of positive integers, “ + “ end list with “ + SENTINEL); int value = IO.readInt(); while (value != SENTINEL) { value = IO.readInt(); }

Nested Loops You create a nested loop when a loop is a statement in the body of another loop. for (int k = 1; k <= 3; k++) { for(int r = 1; r <= 4; r++) System.out.print(“*”); System.out.println(); }

for (int k = 1; k <= 3; k++) { for(int r = 1; r <= 4; r++) System.out.print(“*”); System.out.println(); } for each of 3 rows { print 4 stars go to next line }

This example has two loops nested in an outer loop. for (int r = 1; r <=6; r++) { for (int j = 1; j <= r; j++) System.out.print(“+”); for (int j = 1; j <= 6 -1; j++) System.out.print(“*”); System.out.println(); }

Tracing int num1 = 0; int num2 = 0; for (int i = 0; i <=4; i++) { num1 = i * i; num2 += num1; System.out.print(num1 + “ “); } System.out.println(num2);