Problem Solving With Loops

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

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Over and Over Again GEEN163

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

Repetition, Looping. While Loop

REPETITION CONTROL STRUCTURE LOGO

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

What two elements are usually present for calculating a total of a series of numbers?

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Java Coding 3. Over & over again!

Repetition. Chapter 6

Repetition. Chapter 6

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

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

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

Iteration statements - Loops

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

ECE 122. Engineering Problem Solving with Java

Loops. GEEN163 Introduction to Computer Programming

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

STUDENT LESSON A12 Iterations

Flow of Control: Loops. Chapter 4

Accelerating Information Technology Innovation

Top-Down Program Development

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

Example: Monte Carlo Simulation 1

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

3 The L oop Control Structure

int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop.

CMPT 125: Lecture 4 Conditionals and Loops

Computer Programming I - Unit 5 Lecture page 1 of 14

switch-case Statements

Why Is Repetition Needed?

Introduction. C provides two styles of flow control:

5) (4 points) What is the value of the boolean variable equals after the following statement?

Flow of Control: Loops

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

COP 2000 Note Framework Chapter 5 - Repetition Page 1

Last Class. While loops Infinite loops Loop counters Iterations

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

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

Controls Structure for Repetition

Chapter 2: Functions and Control Structures

Scope of this lecture. Repetition For loops While loops

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Arithmetic Compound Assignment Operators

4. Flow of Control: Loops

4. Flow of Control: Loops. Objectives. Java Loop Statements 10/10/12. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Chapter 4 Introduction to Control Statements

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

Arrays. Eng. Mohammed Abdualal

Programming with Java

General Information About Iteration (Loops)

Control Statements. Musa M. Ameen Computer Engineering Dept.

Repetition, Looping CS101

Control Structures II. Repetition (Loops)

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

Flow of Control: Loops. Objectives. Java Loop Statements: Outline 6/27/2014. Chapter 4

Loops. Repeat after me

More on control structures

Assignment 2.4: Loops

Full file at

Chapter 6. Repetition. Asserting Java. Rick Mercer

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

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

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

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

CS1004: Intro to CS in Java, Spring 2005

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

CS112 Lecture: Repetition Statements

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Lecture Transcript While and Do While Statements in C++

Subject: PIC Chapter 2.

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

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I

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

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

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

The for Loop. Lesson 11

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

COMP 202 Java in one week

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

Chapter 4 Lab. Loops and Files. Objectives. Introduction

Technical Questions. Q 1) What are the key features in C programming language?

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Transcription:

To appreciate the value of loops, take a look at the following example. This program will calculate the average of 10 numbers input by the user. Without a loop, the three lines of code that prompt the user for input, get the input, and add the input to the running sum would need to be repeated 10 times for a total of 30 lines of code. This is only for getting the input and does not include any of the other necessary lines of code. Average Ten Numbers: int sum = 0; System.out.println("Enter number: "); number = keyboard.nextint(); sum = sum + number; System.out.println("Enter number: "); number = keyboard.nextint(); sum = sum + number; //...[ 28 statements deleted ]... System.out.println("Enter number: "); number = keyboard.nextint(); sum = sum + number;... average = sum / 10; The following code example has exactly the same functionality as the previous example; however, it only uses three lines of code to accomplish the same task. The code begins with i equal to 0. While i is less than 0, the code block within the brackets runs. With each iteration of the code, i is incremented by 1 (i ++ is shorthand for I equals I plus 1). The code will be repeated unit i equals 9 (10 times). Once i equals 10, the loop test is false. Ten is not less than 10. When the test is false, the code moves to the next 1

line following the loop block. In this example, the next line run is average = sum / 10; for (i=0; i<10; i++) System.out.println("Enter number: ); number = keyboard.nextint(); sum = sum + number; } average = sum / 10; Using a looping structure is more efficient and less prone to errors created by having to repeat lines of code over and over again. The While Loop Following is the basic structure of the while loop. Within the parentheses following the keyword while is an expression that evaluates to true or false. The lines of code that should be repeated are enclosed in curly brackets. while( loop-test ) //answer is true or false, repeats on True //Statements to be repeated }f Here is the flowchart for the while loop. The loop test expression is entered in a diamond or decision shape. From the true exit path are the steps that are to be repeated as part of the loop. After the steps are processed, the loop test is repeated. The false path leads to the lines of code, and the program continues. 2

In the following example, n equals the number of intended iterations. It is essential that this variable have a starting value before the loop test is encountered the first time. Counter is given a starting value of 1. While counter is less than or equal to n, the code in the brackets will run. The first time this test is processed, counter has the value of 1, and n has the value of 6. The user will be asked to enter a number. The input number is added to the running sum, then the counter is incremented by 1. The counter must be incremented to move the loop one step closer to termination. The condition is tested again. Counter is now 2. Two is less than 10, so the loop is run again. Eventually, the counter will become 11. Eleven is not less than or equal to n. The loop will stop, and the program will continue with the next line of code following the loop block. 3

(Answer: This code will display 1, 2, 3, and 4 each on its own line) Do-While Loop This is the basic structure for the do-while loop. Notice the loop test is at the bottom following the block of code. The code will always be run at least once 4

with a do-while loop because the code is run before the condition is tested. do iterative-part } while ( loop-test ) ; The flowchart for the do-while is very similar to the while flowchart, except the steps are listed before the loop test. In the following code example, a menu is displayed to the user. The do-while loop is used here because the menu should always be displayed at least once. Based on the user s choice, it may be displayed again. This loop is used for error handling. If the user does not enter one of the offered choices, the menu is displayed again, and the user is given another opportunity to enter 5

an appropriate choice. public char MenuOptionSelection() Scanner keyboard = new Scanner(System.in); char Option = ; do System.out.println("Enter N)ew, O)pen, S)ave: ); Option = keyboard.nextchar(); } while (Option!= 'N' && Option!= 'O' && Option!= 'S'); return Option; } For Loop The for loop structure consists of a start, a test, an action, and the code block of statements to be repeated. When the for loop is executed, the initial statement is executed. The loop test is then executed. If the loop test is false, the loop is terminated. If the loop test is true, the code block is executed, then the action is processed. The test is then executed again. for( start; test; action) //the for loop statements to be repeated 6

} Following is the general flowchart for the for loop. The initial statement is processed only once and before the loop test is encountered. Following the loop test, the true path includes the code block and the repeated statement or action. The false path continues the program. In the following example, the user is prompted for the number of iterations to be performed and sum is initialized to zero. When the for loop is first encountered, a counter variable is declared and given the starting value of 0. Counter is then compared to n as the loop test. Assuming the user entered a number greater than 0, the user will be prompted to enter a number that is stored in the variable Value. Value is added to the running sum. The action is then performed: Counter is increased by 1, and the new value is stored in counter. The condition is then tested again. Counter, which is now one higher, is compared to n. As long as it is still less than n, the user is again asked to enter a number that is added to the running sum. Counter is again increased by one before the condition is tested again. Once counter is not less than n, the loop terminates. The next lines of code to be executed 7

calculate the average and output it to the screen. //Example of a for loop that produce an average of user-supplied values: Infinite Loops One of the most important steps in loop design is bringing the loop one step closer to termination. This must be included to avoid an infinite loop-a-loop that never terminates. Examples include incrementing a counter by 1 or using 8

a decision within the code block to set the loop condition to false. The final step in designing a loop is to prime for the initial test as necessary. This means making sure all variables used in the loop test have valid data before the test is performed. In the following example, the variables j and n need to be initialized before the loop is executed: i nt j; int n; float x; float sum; while(j <= n) System.out.println( Enter a number: ); x = keyboard.nextint(); sum = sum + j; j++ } An infinite loop is one that never terminates. In the example, below the output "Do we ever get here?" will never be printed. Counter is not changed in the code block. J is incremented, but j is not used in the loop test. The only way to terminate an infinite loop is Control-Alt-Delete and end the task. int counter = 1; 9

int j = 0; int n = 3; while(counter <= n) j = j + 1; System.out.println(counter); } System.out.println("Do we ever get here? ); The following code example is another example of producing an endless loop: int Count = 1; while(count > 0) System.out.println( Enter your answer ); Ans = keyboard.nextint(); Count++; } For each of the following code examples, study the code and determine what the output is or what the code is supposed to be doing. The answers are at the end of the document. 10

11

12

13