Control Statements Loops.

Slides:



Advertisements
Similar presentations
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Advertisements

1 ICS103 Programming in C Lecture 7: Repetition Structures.
COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 6, 2005.
COMP 14 Introduction to Programming Miguel A. Otaduy May 21, 2004.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
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.
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
Chapter 5: Control Structures II (Repetition)
Java Programming: From the Ground Up
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 4 Objectives  Learn about repetition (looping) control structures.
Chapter 5 Loops.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 5: Control Structures II (Repetition)
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
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:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
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 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
CHAPTER 4 REPETITION STRUCTURES 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Asma Alosaimi.
Chapter 4 Repetition Structures
Java Fundamentals 4.
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Control Structures II (Repetition)
Repetition-Counter control Loop
CiS 260: App Dev I Chapter 4: Control Structures II.
Java Programming: Guided Learning with Early Objects
Repetition-Sentinel,Flag Loop/Do_While
Chapter 2.2 Control Structures (Iteration)
Chapter 5: Control Structures II
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Chapter 4 Repetition Structures
Chapter 4 Repetition Structures
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Control Statements Loops.
Lab5 PROGRAMMING 1 Loop chapter4.
Chapter 5: Control Structures II (Repetition)
Repetition Statements
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Chapter 4 Repetition Structures
Control Statements:.
Presentation transcript:

Control Statements Loops

Types of Control Structures

Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas used to find average grades for students in a class. Loop Group of instructions that a computer executes repeatedly while some condition remains true

while for do…while Repetition Java has three repetition, or looping, structures that let you repeat statements over and over again until certain conditions are met: while for do…while

counter-controlled loop The loop shown below in pseudo code is called a counter-controlled while loop because its repetition is managed by a loop control variable whose value represents a count. Set loop control variable to an initial value While loop control variable < final value ... //Do something multiple times Increase loop control variable by 1 (or step size).

The while Looping (Repetition) Structure Syntax: while (expression) statement Statements must change value of expression to false. A loop that continues to execute endlessly is called an infinite loop (expression is always true).

Example 1 This slide shows a program fragment that computes and displays the gross pay for seven employees. The loop body is the compound statements (those between { and }) count_emp = 1; while (count_emp <= 7) count_emp = 0; while (count_emp < 7) { System.out.print("Hours:“); hours = input.nextInt(); System.out.print("Rate:“); rate = input.nextInt(); pay = hours * rate; System.out.print(“Pay is:”+ pay); count_emp = count_emp + 1; //or count_emp++; } System.out.print("\n All employees processed\n“);

Syntax of the while Statement: Initialization. i.e. count_emp = 0; Testing(condition). i.e. count_emp < 7 Updating i.e. count_emp = count_emp + 1; The above steps must be followed for every while loop. If updating is skipped, it produce an infinite loop

Example 2: Computing Sum If we want to compute , we need to do 1+2+3+...+100 int sum =0, i = 1; while (i <= 100) { sum = sum + i; //or sum+=i; i = i + 1; //or i++; ++i; i+=1; } System.out.print(“Sum is :“+sum );

The for Looping (Repetition) Structure Specialized form of while loop. Its primary purpose is to simplify the writing of counter-controlled loops. For this reason, the for loop is typically called a counted or indexed for loop. . Syntax: for (initial statement; loop condition; update statement) statement Rewrite the previous examples using for loop

The for Looping (Repetition) Structure The following for loop outputs the word Hello and a star (on separate lines) five times: for (i = 1; i <= 5; i++) { System.out.println("Hello"); System.out.println("*"); } 2. The following for loop outputs the word Hello five times and the star only once:

The for Looping (Repetition) Structure Does not execute if loop condition is initially false. Update expression changes value of loop control variable, eventually making it false. If loop condition is always true, result is an infinite loop. Infinite loop can be specified by omitting all three control statements.

Conditional Loops In many programming situations, we will not be able to determine the exact number of loop repetitions before loop execution begins. Sentinel-Controlled loops Flag-Controlled loop

Sentinel-Controlled while Loop Used when exact number of entry pieces is unknown, but last entry (special/sentinel value) is known. General form: Input the first data item into variable; while (variable != sentinel) { . . input a data item into variable; }

Example :Program to compute the product of entered numbers import java.util.*; public class SentinelControlledWhileLoop{ static Scanner console = new Scanner(System.in); static final int SENTINEL = -999; public static void main (String[] args){ int number, prod= 0; SSystem.out.println("Enter positive integers ending with " + SENTINEL); number = console.nextInt();// Initialization while (number != SENTINEL) //testing { prod= prod * number; System.out.println("Enter positive integers ending with " + SENTINEL); number = console.nextInt(); //updating } System.out.println(“the product is “ + prod);}} Read input before loop

Flag-Controlled while Loop Boolean value used to control loop. General form: boolean found = false; while (!found) { . if (expression) found = true; }

bool found = false; int num =0;   while(!found) {         num++;         if (num == 3) { found = true;             System.out.println("value of flag is:“ +found ); }          }

The do…while Loop (Repetition) Structure Syntax: do statement while (expression); Statements are executed first and then expression is evaluated. Statements are executed at least once and then continued if expression is true.

do…while Loop (Post-Test Loop)

do…while Loop (Post-Test Loop) Example : i = 0 ; do { System.out.print(i + “ “ ) ; i = i + 5 ; } while ( i <= 30 ) ; output : 0 5 10 15 20 25 30

break Statements Used to Can be placed within if statement of a loop. exit early from a loop. (while, for, and do...while) skip remainder of switch structure. Can be placed within if statement of a loop. If condition is met, loop is exited immediately. After the break statement executes, the program continues to execute with the first statement after the structure

Output 1 2 3 4 break Statements Example : int count ; for ( count = 1 ; count <= 10 ; count ++ ) { if ( count == 5) break ; System.out.print(count + “ ” ); } Output 1 2 3 4

continue Statements Used in while, for, and do...while structures. When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop. When executed in a while/do…while structure, expression is evaluated immediately after continue statement. In a for structure, the update statement is executed after the continue statement; the loop condition then executes.

Output 1 2 3 4 6 7 8 9 10 continue Statements Example : int count ; for ( count = 1; count <= 10 ; count ++ ) { if ( count == 5) continue; System.out.print(count + “ ” )}; } Output 1 2 3 4 6 7 8 9 10

Nested Control Structures Provides new power, subtlety, and complexity. if, if…else, and switch structures can be placed within while loops. for loops can be found within other for loops. Nested loops consist of an outer loop with one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered Their loop control expressions are reevaluated All required iterations are performed again

Example: Sum of Scores of 3 sections calculate the total scores in each section for 3 sections. Each section's scores are terminated by the sentinel -99.

int sec, score, sum; System.out.print ("sum of scores for each section\n“); for (sec= 1 ; sec <= 3 ; ++sec) { sum = 0; for (score=input.nextInt(); score != -99; score=input.nextInt()) {sum += score; } System.out.print("Section: " +sec+ " sum of scores :” +sum); }

Nested Control Structures for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) System.out.print(" *"); System.out.println(); } Output: * ** *** **** *****