All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Similar documents
Introduction. C provides two styles of flow control:

Computer Programming I - Unit 5 Lecture page 1 of 14

REPETITION CONTROL STRUCTURE LOGO

C++ Programming: From Problem Analysis to Program Design, Third Edition

Loops. CSE 114, Computer Science 1 Stony Brook University

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Problem Solving With Loops

STUDENT LESSON A12 Iterations

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Chapter 4: Control structures. Repetition

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

3 The L oop Control Structure

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Repetition CSC 121 Fall 2014 Howard Rosenthal

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Chapter 4: Control structures

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

ECE 122. Engineering Problem Solving with Java

Unit 3 Decision making, Looping and Arrays

CHAPTER 5 FLOW OF CONTROL

Lecture 7 Tao Wang 1

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Flow Control. CSC215 Lecture

Scope of this lecture. Repetition For loops While loops

CS1004: Intro to CS in Java, Spring 2005

Loops / Repetition Statements

Introduction to the Java Basics: Control Flow Statements

CS1150 Principles of Computer Science Loops (Part II)

Subject: PIC Chapter 2.

Chapter 2: Functions and Control Structures

CS110D: PROGRAMMING LANGUAGE I

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Iteration statements - Loops

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

n Group of statements that are executed repeatedly while some condition remains true

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Conditionals and Loops

AP Programming - Chapter 6 Lecture

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

CS111: PROGRAMMING LANGUAGE II

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

YOLOP Language Reference Manual

CS112 Lecture: Repetition Statements

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-Oriented Programming in Java

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Repetition, Looping. While Loop

Accelerating Information Technology Innovation

Java Control Statements

Control Structures in Java if-else and switch

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Conditionals, Loops, and Style

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

DELHI PUBLIC SCHOOL TAPI

Repetition, Looping CS101

CMPT 125: Lecture 4 Conditionals and Loops

LOOPS. Repetition using the while statement

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The for Loop. Lesson 11

CT 229 Java Syntax Continued

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Control Structures II. Repetition (Loops)

3chapter C ONTROL S TATEMENTS. Objectives

Structured Programming. Dr. Mohamed Khedr Lecture 9

LECTURE 5 Control Structures Part 2

Why Is Repetition Needed?

LESSON 3. In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script.

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

1007 Imperative Programming Part II

CS112 Lecture: Loops

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Dept. of CSE, IIT KGP

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Chapter 5: Loops and Files

Chapter Goals. Contents LOOPS

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Java Coding 3. Over & over again!

MODULE 2: Branching and Looping

Looping. Arizona State University 1

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Topics. Chapter 5. Equality Operators

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Transcription:

All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do.. while loops Examples Exiting For loops Definition Examples Readability Nesting Break - Continue Looping Examples Decreasing powers of 2 Reading Characters Increasing and Decreasing Integers All copyrights reserved - KV NAD, Aluva

Introduction In the programs we have written so far, the statements in the program have been executed in sequence, from the start of the program to the end, omitting sections of "if" and "switch" constructs which have not been selected. The real power of computers comes from their ability to execute given sets of statements many times, commonly known as looping. In Java we have three types of loops : The while loop The do while loop The for loop

Why Looping? (i) To automate the repetition of calculations. (ii) To iterate through data and test for certain condition. (iii).to keep attempting for some operation

"while" loops condition false A while statement has the following syntax: while (condition) statement; true statement If the condition is true, the statement is executed; then the condition is evaluated again The statement is executed over and over until the condition becomes false

"while" loops int Number = 10; while ( Number >= 0 ) { System.out.println( "Number is " + Number ); Number--; // end while Number >= 0 System.out.println( "Loop ended"); The condition to be tested is contained in parentheses (round brackets) after the word "while", and the body of the loop is in curly braces after the condition. There is no semicolon after the closing curly brace.

"while" loops The sequence of operations in the loop (after the initialisation of the value of "Number" to 10, for example) is : (i) Test whether "Number >= 0". (ii) If it is FALSE, abandon the loop, and continue with the statements after the closing curly brace. In this case, the next statement to be executed would print out the "Loop ended" message. (iii) If the result of "Number >= 0" is TRUE, execute the statements in the body of the loop (between the curly braces, in this case first print a message, and then decrement the value of "Number" by 1 ), and then return to step (i) above.

Program for calculation of factorial of any no. int Number = Integer.parseInt(jTextField1.getText()); int fact=1; while ( Number >= 1 ) { fact=fact*number; Number--; jtextfield2.settext( ""+fact);

Examples of while loops counting from 1 to 10 // version 1 // version 3 int Number = 1; while ( Number <= 10 ) { System.out.println( Number ); Number++; int Number = 0; while ( Number < 10 ) { Number++; System.out.println(Number); // version 2 // version 4 int Number = 0; while ( Number < 10 ) { Number++; System.out.println( Number ); int Number = 0; while ( ++Number <= 10 ) { System.out.println(Number);

Infinite Loops The body of a while loop must eventually make the condition false If not, it is an infinite loop, which will execute until the user interrupts the program This is a common type of logical error -- always double check that your loops will terminate normally int counter = 1 while (counter>0) { System.out.println("Counter:" + counter); counter++;

Examples of "while" loops To add together the sequence 1 + 1/2 + 1/3 + 1/4 What will be the output of following line of code float t,s=0; int i=1; while(i<=10){ t=1/i; s+=t; i++; System.out.println(""+s);

do loops Syntax: [initialization] do { [statements] [iteration] while ( boolean-expression )

do loops The "while" loops above performed the test first, and then executed the loop. Sometimes you may wish to test at the end of the loop, after the execution of the statements in the body of the loop (and hence to execute the loop body always at least once). In JAVA we use what is referred to as a "do" loop, written as follows : int Number = 1; do { Number++; while ( Number <= 10 ); In this case the value of "Number" would be 1 the first time round the loop, and 10 the last time. The condition (exactly as in a "while" loop) is still contained in round brackets, and is still TRUE to continue with another execution of the loop body, and FALSE to leave the loop. Remember that there is a semicolon after the condition, terminating the whole statement. We have one more semicolon overall than the equivalent "while" loop.

do loops The pattern of execution in this case can be summarised as follows. loop; test loop; test; loop; test loop; test; loop; test; loop; test The code in the above programming example could also be written int Number = 1; do { while ( ++Number <= 10 ); This is the form of combined "increment and test" that most C++ programmers that write JAVA would use. The "++" must, of course, be in front of the "Number" in this case. It is generally safer to test at the start of a loop; "while" loops are generally safer and more common than "do" loops.

Examples of do loops To read in positive numbers until a zero is encountered, and print the biggest one. int NextNumber, Biggest = 0; do { NextNumber = Integer.parseInt( JOptionPane.showInputDialog("Enter any no )); if ( Biggest < NextNumber ) { Biggest = NextNumber; while ( NextNumber!= 0 ); System.out.println( "Biggest " + Biggest );

"for" loops Syntax: for ([ initialization ]; [ boolean-expression ]; [iteration]) { [statements] Examples : for ( Num = 10; Num > 0; Num-- ) { for ( Count = 0; Count < 10; Count++ ) {

"for" loops It is common to declare and initialize the loop variable at the start of the for loop itself : for ( int Count = 0; Count < 10; Count++ ) { The general form of a "for" loop is : for ( initialise; test; execute after loop ) {

"for" loops The initialise statement is carried out once only, at the start of the first time that the loop is entered. The test is executed before each execution of the body of the loop, including a test before the very first execution of the loop. The first time will be immediately after the initialisation, and hence there will be perhaps no executions of the loop body if the test fails at this stage. The third expression is a statement executed after every execution of the loop body, before the next test. It typically increments a counter. The sequence is now : init; test; init; test; loop; incr; test; init; test; loop; incr; test; loop; incr; test; Again note that the increments in the examples above could be written with the "++" before or after the variable identifier; in this case it does not matter.

"for" loops - Readability One of the important advantages of a "for" loop is its readability. All of the essential loop control is grouped together at the top of the loop. We can see at a glance the initial values which are set up, the test to be satisfied for loop exit, and the main variable increments. You should make maximum use of this readability. The "for" loop could be written as a "while" loop in the form : declaration; initialise;... while ( test ) { incr; In this layout, the loop control is not so clearly seen.

Defaults Defaults are obvious; any or all of the three control statements can be omitted. The construct for ( ; ; ) { gives no initialisation, assumes a TRUE test result, and performs no incrementing. You may find the comma "operator" useful in the initialisation and increment parts of the loop control. for ( this = 10, that = 0; this > that; this--, that++ ){

General points on loops - Nesting of loops Loops may, of course, be nested to any depth in any combination as required. for ( int year = 1900; year < 2000; year++ ) { for ( int month = 0; month < 12; month++ ) { // execute 1200 times... // end month loop for each year // end year loop The loop executes with "month" and "year" taking the pairs of values [1900,0], [1900,1], [1900,2],..., [1900,11], [1901,0], [1901,1],..., [1901,11],..., [1999,11] in turn in that order.

The "break" statement In any of the above loops, the special statement "break" causes the loop to be abandoned, and execution continues following the closing curly brace. while ( i > 0 ) { if ( j ==... ) { break; // abandon the loop // end of the loop body System.out.println( "continues here..."); The program continues after the end of the loop. Within a nested loop, "break" causes the inner most loop to be abandoned.

The "continue" statement In any of the above loops, the statement "continue" causes the rest of the current round of the loop to be skipped, and a "while" or "do" loop moves directly to the next test at the head or foot of the loop, respectively; a "for" loop moves to the increment expression, and then to the test. Note that labelled break and continue are available but beyond the scope of this course.

Example of "break" and "continue" We wish to write a loop processing integer values which we have read in. If the value we have read is negative, we wish to print an error message and abandon the loop. If the value read is greater than 100, we wish to ignore it and continue to the next value in the data. If the value is zero, we wish to terminate the loop. while ( ( value = UserInput.readInt() )!= 0 ) { if ( value < 0 ) { System.out.println( "Illegal value"); break; // Abandon the loop if ( value > 100 ) { System.out.println( "Invalid value"); continue; // Skip to start loop again // Process the value read // guaranteed between 1 and 100 // end while value!= 0

Sum of squares To sum the square of all the integer values from 1 squared up to 99 squared. int sum = 0; // add squares up to 99 squared for ( int nextval = 1; nextval < 100; nextval++ ) { sum = sum + nextval * nextval; System.out.println( "Sum of 1*1+2*2+..+99*99=" + sum); Sum of 1*1+2*2+..+99*99=: 328350

Summary Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do.. while loops Examples Exiting For loops Definition Examples Readability Nesting Break - Continue Looping Examples Decreasing powers of 2