Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus.

Slides:



Advertisements
Similar presentations
08 Deterministic iteration1May Deterministic iteration CE : Fundamental Programming Techniques.
Advertisements

Loops (Part 1) Computer Science Erwin High School Fall 2014.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Loops and Files.
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.
Objectives You should be able to describe:
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
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
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
Chapter 5 Loops.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
Control Structures By Shyam Gurram. Control Structure In this chapter we have two different types of structures. Conditional Structure Iterative Control.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
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.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Fundamental Programming Fundamental Programming for Loops.
JavaScript, Fourth Edition
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
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.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Application development with Java Lecture 6 Rina Zviel-Girshin.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Loops Tonga Institute of Higher Education. Introduction Programs need to be able to execute tasks repeatedly. Use loops to repeat actions  For Loop 
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
ECE122 Feb 10, Unary Operator An operator that takes only a single operand Plus: + Minus: – Cast: (type). E.g. (double)
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied. Suppose you want to execute some code/s 10 times.
UCT Department of Computer Science Computer Science 1015F Iteration
Lecture 4b Repeating With Loops
Chapter 5: Control Structures II
JavaScript: Control Statements.
Chapter 5: Control Structures II
Arrays, For loop While loop Do while loop
Control Statements Loops.
Lab5 PROGRAMMING 1 Loop chapter4.
2.6 The if/else Selection Structure
Control Statements Paritosh Srivastava.
Control Statements Loops.
PROGRAM FLOWCHART Iteration Statements.
Presentation transcript:

Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus

Where are we? The 6 Coding Concepts Input – getting things into the program Output – passing things to the outside world Assignment – pass a value from one part of the program to another Sequence - do each thing in the order specified Decision-making -check something then do the appropriate action depending on that condition Repetition - do the set of commands several times

Deterministic loops (for loop)‏ Use if you know how many times the loop should execute (deterministic loop)‏ int num = Console.readInt("How many lines?"); for (int i = 0; i < num; i++)‏ {System.out.println("I must stay awake in class"); }

Breakdown of the for Loop for (int i = 0; i < num; i++)‏ What does this mean? The for loop consists of 3 items: The initialiser (int i = 0)‏ The terminating condition (i < num)‏ The incrementor (i++)‏ These items are separated by a semicolon ; Like the if statement, you can omit the {} that follow it if there is only one statement to be repeated

Nested for loops You have seen how if-else statements can be nested inside each other: if(condition )‏ { if(condition )‏ {// do something } else {// do something different } else {// other stuff }

Nested for loops Well you can do the same with for loops: for( int i = 0; i < 10; i++ )‏ {System.out.println(“Outer loop”); for( int j = 0; j < 5; j++ )‏ {System.out.println(“Inner loop”); }  Why use i and j as loop counters?

Loop examples for( int i = 0; i < 10; i++ ) – will repeat 10 times by incrementing i for( int i = 0; i <= 10; i++ ) – will repeat 11 times for( int i = 0; i < 10; i+=2 ) – will repeat 5 times for( int i = 10; i > 0; i-- ) – will repeat 10 times by decrementing i for(;;) – will repeat infinitely! Hint: there may be a way out…

Alternative syntax: For-Each There is another way of specifying the Java for loop when using arrays and collections. int [] myArray; // or you could write int myArray[]; for(int nValue : myArray)‏ // foreach in other languages sum += nValue; instead of: for(int i=0; i < myArray.length; i++)‏ sum += myArray[i];

A short digression – reading ints If we need to read an integer value from the keyboard, we might do this: import java.util.*; private int getConsoleInt(String sPrompt) {System.out.print(sPrompt); Scanner scan = new Scanner(System.in); try{ return scan.nextInt(); } catch (InputMismatchException ex){ return Integer.MIN_VALUE; } catch (NoSuchElementException ex){ return Integer.MIN_VALUE; } catch (IllegalStateException ex){ return Integer.MIN_VALUE; } } // note that a return of –2,147,483,648 means an error occurred!

Non-deterministic loops (while)‏ use if you want the loop to execute until a condition is false (non-deterministic loop)‏ must allow tested variable to change within the loop, otherwise you’ll have an infinite loop! int num = getConsoleInt ("How many lines?"); while (num > 0)‏ {System.out.println("I love Java!!!"); num--; }

Non-deterministic loops (do-while)‏ There is a similar while loop called the do-while loop: int num = getConsoleInt ("How many lines?"); do {System.out.println("I love Java!!!"); num--; } while (num > 0); Note the semi-colon!

Non-deterministic loops (do-while)‏ So what’s the difference between while and do- while? The contents of a while loop is not executed if the test condition fails at the start. The contents of a do-while loop is guaranteed to execute at least once. The test condition is only performed after the first iteration through the loop.

Exiting a loop The normal way to exit a loop is for the condition that is tested to become false. This is true of all three types of loops in Java: for, while, and do-while. However, there might be times when you want a loop to end immediately, even if the condition being tested is still true. You can do this with a break statement, as shown in the following code:

The break statement int index = 0; while (index <= 1000)‏ {index = index + 5;// or index+=5; if (index == 400) break; System.out.println("The index is " + index); } The break statement is especially handy if you need to search a list and then exit the search loop code if you found what you are looking for

Menus Can use a combination of a while loop and a switch statement to implement a menu NB may be better to have “[0] Exit” - why? What would you like to do? [1]Register student [2]Register student on program [3]Exit ?

Simple menu display public int showMenu()‏ { int choice; System.out.println("\nWhat would you like to do?"); System.out.println("\t[1]\tRegister student"); System.out.println("\t[2]\tChange student's program"); System.out.println("\t[3]\tExit"); choice = getConsoleInt ("? "); return choice; }

Simple menu control int choice = showMenu(); while (choice != 3)‏ { switch (choice)‏ {case 1: registerStudent(); break; case 2: changeProgram(); break; default: System.out.print(“Invalid, please try again"); } choice = showMenu(); }

Implementing a menu-based interface Would have to write appropriate methods showMenu()‏ registerStudent()‏ changeProgram()‏ Look at StudentInterface.java listingStudentInterface.java

Summary We have looked at: for loops Nested for loops while loops do-while loops break We have put them together into a menu-driven interface for the Student class (see tutorial).

Further work Practical Read to go over all the main blocks of Java code you’ve seen so far.