# Controls Structure for Repetition

Size: px
Start display at page:

Transcription

1 Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power of computers lies in their ability to repeat a set of instructions many times in a short period of time. Many algorithms contain directives to repeat a designated set of steps an arbitrary number of times. In Java we have a simple loop structure, called a while statement, which allows us to repeat a piece of code multiple times. Here is the general syntax of a while statement: while (<boolean expression>) { stmt1; stmt2;... stmtn; This statement is executed in the following manner: 1) First the boolean expression is evaluated. 2) If it is true, execute statements 1 through n in order. 3) If it is false, skip all the statements inside the while loop braces({). 4) Go back to step #1. In essence, you check your boolean condition each time before you decide whether or not to execute the statement in the loop. You continue doing so until you check the condition and it is false. What we can see from this construct is typically, for it to be effective, the boolean condition must first be true, and eventually become false. Thus, if the boolean condition was in terms of a variable, such as: while (x < 10) {... For this to be an effective loop, the value of x must change in the body of the loop. If it does not, then the condition will always evaluate to the same thing.

2 The big problem with this is if it happened to be true to begin with, it would never stop!!! This is known as an infinite loop. One of the most common problems that beginning programmers have when designing loops is having them run forever, so to speak. We will talk about how to detect these later. Now lets consider trying to write a program to do the following: 1) Prompt the user if they would like to enter a test score. 2) If so, reading it in and then asking them for another test score. 3) Continue the process above until the user says no. 4) Output the average of the test scores entered by the user. Before we get down to writing this program, let s analyze how we will need to lay everything out. To compute an average, we must know two pieces of information: 1) The sum of the numbers 2) The number of numbers being averaged. Notice that we don t actually need to know each individual number. So the idea that we have is the following: Create two variables, one to store the sum of the numbers and one to store the number of numbers. Furthermore, we will also need a variable to read in the answer of the user as to whether or not they want to enter another score. Finally, we will also need a variable to read each individual score into. In general, we want to continue reading in scores until the user says they do not want to enter any, so our general layout will look like the following: <initialize variables> while (<user says they want to enter another score>) { <ask user for score> <adjust necessary variables <check to see if they want to enter another score>

3 The process we have gone through is basically the algorithmic design process. Notice that we haven t truly written any code yet, but we have a very good idea of how we are going to solve this problem. Whenever you are given a problem to write a program for, you should always go through this algorithmic design process. You want to identify the variables you will need, as well as the general flow of execution. That way, once you actually write your program, it will be much easier to debug(which is simply a fancy word for fix) it. So, without further due, here is the program: public class Average { public static void main(string args[]) { Scanner stdin = new Scanner(System.in); // Declare and initialize all necessary variables. char answer; int sum, score, numscores; double average; numscores = 0; sum = 0; // Read in whether or not user would like to enter a score. System.out.println( Would you like to enter a score?(y/n) ); answer = (stdin.next()).charat(0); // Continue reading in scores as long as user wants. while (answer == y ) { // Get next score. System.out.println( Enter the next score. ); score = stdin.nextint(); // Update necessary variables. sum = sum + score; numscores = numscores + 1;

4 // Prompt user if they want to enter another score or not. System.out.println( Would you like to enter a score?(y/n) ); answer = (stdin.next()).charat(0); average = sum/numscores; System.out.println( The average of your scores is + average); Now, there are actually a couple subtle problems with the program above. The first is that even though the statement average = sum/numscores is mathematically correct, two things can go wrong with this statement: 1) If numscores is 0, then we are dividing by a 0, which is a big no no!!! 2) average will always be set to an integer because the quotient of two integers is defined to be an integer in Java as well. How can we solve the first problem? Notice that our English write-up of the problem looks a lot like Java code. We can simply use an if statement to check the value of numscores. How about the second problem? We know that Java will correctly divide a double by an integer, so we can change our assignment statement to: average = 1.0*sum/numscores. The expression on the right is evaluated left to right. 1.0*sum is going to give us a double as an answer, equal to sum. Then this double will get divided by numscores, also giving us a double, which will be the correct answer. So, here is our fix for the last section of our code: if (numscores > 0) { average = 1.0*sum/numscores; System.out.println( The average of your scores is + average); else

5 System.out.println( Sorry, you did not enter any numbers to average. ); Let s analyze our code to look for general types of constructs for particular solutions. First of all, the while loop we used is typically known as a sentinel-controlled loop. What this means is that the loop continues to run until some sentinel value, which is meant to indicate the end of the data, is read in. In this case, we simply prompted the user as to whether or not they wanted to enter another value each time. Our sentinel value was the character n. (Technically it was every character but y.) This is a standard technique. Often times you will have to read in several pieces of data, and will be looking for some value that signifies the end of that data. We could have written this program in such a manner that we asked the user to enter all of their scores at once, followed by a 1. Since it is impossible for 1 to be a test score, this would have been the sentinel value we were looking for. In any event, in a situation like this, you simply use a while loop that runs until there is equality with the sentinel value. The second standard technique introduced in this program is the user of an accumulator variable. Often times you will have to sum up a set of values. You can use an accumulator variable to do so. In this program the accumulator variable was sum. The way you typically use an accumulator variable is to initialize it to zero. Then, whenever you encounter a value you need to add into your sum, simply have a line with the following form: sum = sum + <value>; In essence, each time you execute a line of this type, you are taking the old value of sum, adding to it a value that you want to, and then storing that sum back into the accumulator variable. It is instructive to trace through a couple examples to convince yourself that this technique works.

### Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

Boolean Expressions Now we have the ability to read in some information, calculate some formulas and display the information to the user in a nice format. However, the real power of computer programs lies

### Repe\$\$on CSC 121 Fall 2015 Howard Rosenthal

Repe\$\$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

### Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Arrays What are they? An array is a data structure that holds a number of related variables. Thus, an array has a size which is the number of variables it can store. All of these variables must be of the

### Control Structures II. Repetition (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 to 100 The answer will be 1 + 2 + 3 + 4 + 5 + 6 + +

### Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

### CompSci 125 Lecture 11

CompSci 125 Lecture 11 switch case The? conditional operator do while for Announcements hw5 Due 10/4 p2 Due 10/5 switch case! The switch case Statement Consider a simple four-function calculator 16 buttons:

### Repe\$\$on CSC 121 Spring 2017 Howard Rosenthal

Repe\$\$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

### Iteration statements - Loops

Iteration statements - Loops : ) הוראות חזרה / לולאות ( statements Java has three kinds of iteration WHILE FOR DO... WHILE loop loop loop Iteration (repetition) statements causes Java to execute one or

### CS 101 Spring 2007 Midterm 2 Name: ID:

You only need to write your name and e-mail ID on the first page. This exam is CLOSED text book, closed-notes, closed-calculator, closed-neighbor, etc. Questions are worth different amounts, so be sure

### Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8 Handout 5 Loops. Loops implement repetitive computation, a k a iteration. Java loop statements: while do-while for 1. Start with the while-loop.

### Programming with Java

Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

### First Java Program - Output to the Screen

First Java Program - Output to the Screen These notes are written assuming that the reader has never programmed in Java, but has programmed in another language in the past. In any language, one of the

### Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

Pull Lecture Materials and Open PollEv Poll Everywhere: pollev.com/comp110 Lecture 12 else-if and while loops Once in a while Fall 2016 if-then-else Statements General form of an if-then-else statement:

### Repetition, Looping. While Loop

Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

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

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

### Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

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

1 Programming in C Looping Subtasks We will examine some basic algorithms that use the while and if constructs. These subtasks include Reading unknown quantity of data Counting things Accumulating (summing)

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

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

### Loops. CSE 114, Computer Science 1 Stony Brook University

Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

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

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

### STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

### Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

### Java Coding 3. Over & over again!

Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

### CS 101 Fall 2006 Midterm 3 Name: ID:

You only need to write your name and e-mail ID on the first page. This exam is CLOSED text book, closed-notes, closed-calculator, closed-neighbor, etc. Questions are worth different amounts, so be sure

### Repetition Structures

Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

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

Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

### CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists 1 A programming problem Consider the following task: Double values representing grades are read until the user enters a negative

### Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java

### Computer Programming I - Unit 5 Lecture page 1 of 14

page 1 of 14 I. The while Statement while, for, do Loops Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly. The while statement is one of three looping statements

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

CPS109 Course Notes 6 Alexander Ferworn Unrelated Facts Worth Remembering Use metaphors to understand issues and explain them to others. Look up what metaphor means. Table of Contents Contents 1 ITERATION...

### Handout 4 Conditionals. Boolean Expressions.

Handout 4 cs180 - Programming Fundamentals Fall 17 Page 1 of 8 Handout 4 Conditionals. Boolean Expressions. Example Problem. Write a program that will calculate and print bills for the city power company.

### C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

C212 Early Evaluation Exam Mon Feb 10 2014 Name: Please provide brief (common sense) justifications with your answers below. 1. What is the type (and value) of this expression: 5 * (7 + 4 / 2) 2. What

### CSE 1223: Exam II Autumn 2016

CSE 1223: Exam II Autumn 2016 Name: Instructions: Do not open the exam before you are told to begin. This exam is closed book, closed notes. You may not use any calculators or any other kind of computing

### Flow of Control: Loops. Chapter 4

Flow of Control: Loops Chapter 4 Java Loop Statements: Outline The while statement The do-while statement The for Statement Java Loop Statements A portion of a program that repeats a statement or a group

### Chapter 4: Control structures. Repetition

Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

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

Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

### 1007 Imperative Programming Part II

Agenda 1007 Imperative Programming Part II We ve seen the basic ideas of sequence, iteration and selection. Now let s look at what else we need to start writing useful programs. Details now start to be

### Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

كلية الحاسبات وتقنية المعلوما Exam 2 Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: November 22, 2015 Student Name: Student ID: Total Marks: 40 Obtained Marks: Instructions: Do not open this

### Midterm Examination (MTA)

M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and

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

Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative

### (A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Ch 5 Arrays Multiple Choice Test 01. An array is a ** (A) data structure with one, or more, elements of the same type. (B) data structure with LIFO access. (C) data structure, which allows transfer between

### Chapter 4: Control structures

Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

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

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition 5.2 Q1: Counter-controlled repetition requires a. A control variable and initial value. b. A control variable

### CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching 1 Flow of Control The order in which statements in a program are executed is called the flow of control So far we have only seen

### School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

### CSE 1223: Introduction to Computer Programming in Java Chapter 6 Arrays

CSE 1223: Introduction to Computer Programming in Java Chapter 6 Arrays 1 A New Problem Consider the following task: Input N real numbers representing temperature measurements and compute the following:

### Chapter 4: Control Structures I

Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore

### Darrell Bethea May 25, 2011

Darrell Bethea May 25, 2011 Yesterdays slides updated Midterm on tomorrow in SN014 Closed books, no notes, no computer Program 3 due Tuesday 2 3 A whirlwind tour of almost everything we have covered so

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

Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

### Introduction to Computer Programming

Introduction to Computer Programming Lecture 2- Primitive Data and Stepwise Refinement Data Types Type - A category or set of data values. Constrains the operations that can be performed on data Many languages

### Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Chapter 4 Loops Sections Pages Review Questions Programming Exercises 4.1 4.7, 4.9 4.10 104 117, 122 128 2 9, 11 13,15 16,18 19,21 2,4,6,8,10,12,14,18,20,24,26,28,30,38 Loops Loops are used to make a program

### More on Classes. The job of this method is to return a String representation of the object. Here is the tostring method from the Time class:

More on Classes tostring One special method in Java is the tostring method. The method (regardless of which class it s added to) has the following prototype: public String tostring(); The job of this method

### COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

COMP-202 Recursion Recursion Recursive Definitions Run-time Stacks Recursive Programming Recursion vs. Iteration Indirect Recursion Lecture Outline 2 Recursive Definitions (1) A recursive definition is

### Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Building Java Programs Chapter 2: Primitive Data and Definite Loops Copyright 2008 2006 by Pearson Education 1 Lecture outline data concepts Primitive types: int, double, char (for now) Expressions: operators,

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

Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?

### CS 101 Exam 2 Spring Id Name

CS 101 Exam 2 Spring 2005 Email Id Name This exam is open text book and closed notes. Different questions have different points associated with them. Because your goal is to maximize your number of points,

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

Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()

### Some Sample AP Computer Science A Questions - Solutions

Some Sample AP Computer Science A Questions - s Note: These aren't from actual AP tests. I've created these questions based on looking at actual AP tests. Also, in cases where it's not necessary to have

### CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Announcements Did you miss the first lecture? Come talk to me after class. If you want

### Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

Menu Driven Systems While loops, menus and the switch statement Produced by: Mairead Meagher Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Topics list while loops recap

### COMP 202 Java in one week

CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

### Chapter Goals. Contents LOOPS

CHAPTER 4 LOOPS Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30, 2011 Chapter Goals To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common

### (A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Ch 5 Arrays Multiple Choice 01. An array is a (A) (B) (C) (D) data structure with one, or more, elements of the same type. data structure with LIFO access. data structure, which allows transfer between

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

Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

### Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Motivating Examples (1.1) Selections EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG 1 import java.util.scanner; 2 public class ComputeArea { 3 public static void main(string[] args)

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

Chapter 5: Control Structures II Java Programming: Program Design Including Data Structures Chapter Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled,

### REPETITION CONTROL STRUCTURE LOGO

CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

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

Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

### Full file at

Chapter 3 Flow of Control Multiple Choice 1) An if selection statement executes if and only if: (a) the Boolean condition evaluates to false. (b) the Boolean condition evaluates to true. (c) the Boolean

### M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 Question One: Choose the correct answer and write it on the external answer booklet. 1. Java is. a. case

### CSE 114 Computer Science I

CSE 114 Computer Science I Iteration Cape Breton, Nova Scotia What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps?

### Chapter 3. Selections

Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

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

COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

### Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Nested Loops To investigate nested loops, we'll look at printing out some different star patterns. Let s consider that we want to print out a square as follows: We know we can print out one line of this

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

Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in

### 4. Java Project Design, Input Methods

4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java

### Building Java Programs

Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 1 Data and expressions reading: 2.1 self-check: 1-4 videos: Ch. 2 #1 2 Data types type: A category or set of data

### CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1 Name SOLUTION Page Points Score 2 15 3 8 4 18 5 10 6 7 7 7 8 14 9 11 10 10 Total 100 1 P age 1. Program Traces (41 points, 50 minutes)

### CMPT 125: Lecture 4 Conditionals and Loops

CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 1 Flow of Control The order in which statements are executed

### Example Program. public class ComputeArea {

COMMENTS While most people think of computer programs as a tool for telling computers what to do, programs are actually much more than that. Computer programs are written in human readable language for

### Arrays. Eng. Mohammed Abdualal

Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays

### Advanced if/else & Cumulative Sum

Advanced if/else & Cumulative Sum Subset of the Supplement Lesson slides from: Building Java Programs, Chapter 4 by Stuart Reges and Marty Stepp (http://www.buildingjavaprograms.com/ ) Questions to consider

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

The for Loop, Accumulator Variables, Seninel Values, and The Random Class CS0007: Introduction to Computer Programming Review General Form of a switch statement: switch (SwitchExpression) { case CaseExpression1:

### Building Java Programs

Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 Copyright 2009 by Pearson Education Data and expressions reading: 2.1 self-check: 1-4 videos: Ch. 2 #1 Copyright

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

C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,

### CP122 CS I. Iteration

CP122 CS I Iteration Tech News! Pix2Pix: machine learning translation of images https://affinelayer.com/pixsrv/ Tech News! Pix2Pix: machine learning translation of images https://affinelayer.com/pixsrv/

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

Linked Lists Since a variable referencing an object just holds the address of the object in memory, we can link multiple objects together to form dynamic lists or other structures. In our case we will

### Oct Decision Structures cont d

Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements

### Introduction to the Java Basics: Control Flow Statements

Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared

### Problem Solving With Loops

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

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

1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 88 / 133 Flow Controls The basic algorithm (and program) is constituted

### 1. [3 pts] What is your section number, the period your discussion meets, and the name of your discussion leader?

CIS 3022 Prog for CIS Majors I February 10, 2009 Exam I Print Your Name Your Section # Total Score Your work is to be done individually. The exam is worth 105 points (five points of extra credit are available

### AP Programming - Chapter 6 Lecture

page 1 of 21 The while Statement, Types of Loops, Looping Subtasks, Nested Loops I. The while Statement Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly.

### COMP 202. Java in one week

COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language

### Condition Controlled Loops. Introduction to Programming - Python

Condition Controlled Loops Introduction to Programming - Python Decision Structures Review Programming Challenge: Review Ask the user for a number from 1 to 7. Tell the user which day of the week was selected!

### Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations Suppose that you need to print a string (e.g., "Welcome to Java!") a