CSEN 202 Introduction to Computer Programming

Similar documents
CSEN 202 Introduction to Computer Programming

CSI33 Data Structures

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

Condi(onals and Loops

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

CSEN 102 Introduction to Computer Science

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

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

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Full file at

Introduction to the Java Basics: Control Flow Statements

Java Basic Programming Constructs

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Programming with Java

Introduction to Programming Using Java (98-388)

ECE 122. Engineering Problem Solving with Java

Lesson 3: Accepting User Input and Using Different Methods for Output

Accelerating Information Technology Innovation

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

Language Reference Manual

Introduction to Java & Fundamental Data Types

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Programming for Engineers Iteration

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

CS 61B Data Structures and Programming Methodology. June David Sun

Pace University. Fundamental Concepts of CS121 1

PROGRAMMING FUNDAMENTALS

Important Java terminology

Type Conversion. and. Statements

COMP 202 Java in one week

3. Java - Language Constructs I

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Zheng-Liang Lu Java Programming 45 / 79

Lecture Set 4: More About Methods and More About Operators

Lecture Set 4: More About Methods and More About Operators

COMP 202. Java in one week

CSC Java Programming, Fall Java Data Types and Control Constructs

1/9/2015. Intro to CS: Java Review Assignment Due Dates Chapter 7 7.1: while Loops 7.2: for Loops Ch7 Work Time. Chapter 7 Iteration WHILE LOOPS

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

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

Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples.

CS111: PROGRAMMING LANGUAGE II

Java Coding 3. Over & over again!

Simple Java Reference

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

CS11 Java. Fall Lecture 1

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

APCS Semester #1 Final Exam Practice Problems

Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key

CMPT 125: Lecture 4 Conditionals and Loops

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

Tutorials. Inf1-OP. Learning Outcomes for this week. A Foundation for Programming. Conditionals and Loops 1

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Comments in a Java Program. Java Overview. Identifiers. Identifier Conventions. Primitive Data Types and Declaring Variables

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

CS111: PROGRAMMING LANGUAGE II

Introduction to Software Development (ISD) Week 3

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

JAVA Programming Fundamentals

CP122 CS I. Iteration

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

COMP 202 Java in one week

AP Programming - Chapter 6 Lecture

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Expressions & Flow Control

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Example: Monte Carlo Simulation 1

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

( &% class MyClass { }

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CS 112 Introduction to Programming

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Loops. CSE 114, Computer Science 1 Stony Brook University

CSEN 301 Data Structures and Algorithms

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

CSC 1214: Object-Oriented Programming

Software and Programming 1

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

Operators in java Operator operands.

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Java Notes. 10th ICSE. Saravanan Ganesh

Introduction to Computer Programming, Spring Term 2018 Practice Assignment 6 Discussion:

STUDENT LESSON A12 Iterations

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

JAVA OPERATORS GENERAL

1007 Imperative Programming Part II

Java I/O and Control Structures

Introduction to Computer Programming, Spring Term 2018 Practice Assignment 2 Discussion

Lecture 14. 'for' loops and Arrays

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

Getting started with Java

Transcription:

CSEN 202 Introduction to Computer Programming Lecture 4: Iterations Prof. Dr. Slim Abdennadher and Dr Mohammed Abdel Megeed Salem, slim.abdennadher@guc.edu.eg German University Cairo, Department of Media Engineering and Technology February 24 - March 1, 2018 1 Synopsis 1.1 What you learned so far Previous topics What is Java, how to compile and run Hello Wld! Primitive datatypes and their properties (byte, sht, int, long, float, double, boolean, char) Literals and special values Type compatibilities (explicit and implicit cast) Simple expressions (+, -, *, /, %, &,,, >>,... ), their properties, etc. Operand and result types, precedence, etc. Assignments (expression with essential side effect), memy changing expressions (++, --, +=,... ) Previous topics Blocks ({... ) f structuring the program The break-instruction f leaving a Branching and decision constructs if (), switch () { s,? expression : expression. 1

2 Loop constructs 2.1 Overview Today s topic iterative constructs What is life? Life is just one damn thing after another. Mark Twain Life isn t just one damn thing after another... it is the same damn thing over and over again. Looping Looping causes computer to execute section of code repeatedly Edna St. Vincent Millay We use boolean expressions ( and ) as loop ; when boolean is, loop equals exit and loop is terminated As with als, this section of code can be single multiple s enclosed in curly braces (s) We call the section of code executed the loop s body The loops Java offers three different iterative constructs: The while-loop, The do-while-loop, and The f-loop They differ in the relation between loop and loop body 2

3 While and do 3.1 While The while loop Fmat while () A while-loop executes the loop body (a a ) as long as the loop is. The must be of type boolean Befe every execution of the loop body, the loop is evaluated. As soon as the evaluates to, the loop terminates. Note: The loop body may not be executed at all. The while loop schema while 3

while while while 4

while How to construct a while loop 1. Fmulate the test which tells you whether the loop needs to be run again count <= 3 2. Fmulate the actions f the loop body which take you one step closer to termination { System.out.println( "count is: " + count ); count = count + 1; // add one to count 3. In general, initialization is required befe the loop and some postprocessing after the loop int count = 1; How to construct a while loop class WhileExample { public static void main (String[] args ) { int count = 1; // start count out at one while ( count <= 3 ) // loop while count is <= 3 { System.out.println( "count is: " + count ); count = count + 1; // add one to count System.out.println( "Done with the loop" ); 5

while loop example Example 1 (Investment with compound interest). Invest 10000C with 5% interest compounded annually: Year Balance 0 10,000.00 1 10,500.00 2 11,025.00 3 11,576.25 4 12,155.06 Question. When will the balance be at least 20000 Euro? while loop example while while balance< targetbalance increment years add interest to balance while loop example class InvestmentTest { public static void main (String[] args ) { double balance = 10000; 6

double rate = 5; double targetbalance = 20000; int year = 0; while (balance < targetbalance) { year++; double interest = balance * rate / 100; balance = balance + interest; System.out.println("The investment doubled after"+ year +"years"); 3.2 Do The do loop Fmat do while (); A do-while-loop executes the loop body ( ) once and then repeats as long as the is. The must be of type boolean The do loop Fmat do while (); After every execution of the loop body, the loop is evaluated. As soon as the evaluates to, the loop terminates. Note: The loop body is executed at least once. The do loop schema 7

do while do while do while 8

do while do while do while do loop example Example 2 (Validating an input). Task: Accept only a positive integer 9

do loop example do while do while read input value value <= 0 do loop example class ValidateInput { public static void main (String[] args ) throws IOException { BufferedReader userin = new BufferedReader (new InputStreamReader(System.in)); String inputdata; int value; // data entered by the user do { System.out.println( "Please enter a positive number: " ); inputdata = userin.readline(); value = Integer.parseInt( inputdata ); while (value >= 0); System.out.println( "Entered negative number: " + value ); 3.3 Comparison Comparing while and do loops 10

In both loops Stops executing body if loop is you must make sure loop becomes by some computations Infinite loop means your loop is such that it will never turn (i. e., the exit never occurs) do-while while body always executed at least once loop tested at bottom of loop may not execute at all loop tested befe body; loop variables must be set befe loop entry Comparing while and do loops while-loops and do-while-loops can be transfmed to each other do-while to while do { 1; 2; while (); 1; 2; while () { 1; 2; Comparing while and do loops while-loops and do-while-loops can be transfmed to each other do-while to while while () { 1; 2; if () do { 1; 2; while (); 4 A me comftable loop 4.1 F The f loop Fmat f (initialization; ; update) Most common loop construct: just repeats a f a fixed number of times (counting loop) 11

The initialization is an expression f setting initial value of the loop counter. The must be of type boolean The update expression modifies the loop counter Purpose: To execute an initialization, then keep executing and updating an expression while a is. The f loop schema f initialization update f initialization update 12

f initialization update f initialization update f initialization update 13

f initialization update f initialization update f loop example Example 3 (Investment with compound interest). Invest 10000 Euro with 5% interest compounded annually. Question: What will be the balance after n years? f loop example 14

f initialization update f i = 0 i < n i++ add interest to balance f loop example class Balance { public static void main (String[] args ) { double balance = 10000; double rate = 5; int year = 15; f (int i = 0; i < year; i++) { double interest = balance * rate / 100; balance = balance + interest; System.out.println("The investment after"+ year + "will be" + balance); Another f loop example Print a string backwards Recall what you have learned about strings String is not a primitive type, it is a class. The instances of a class are called objects 15

Objects provide their own functionality We can use the dot-operat. and the methods length (), and charat (position) Another f loop example Print a string backwards public class Reverse { public static void main (String[] args) { String wd = "Slim"; if (wd == null) { return; int max = wd.length (); f (int i=max-1; i >=0; i--) { System.out.print (wd.charat (i)); System.out.println (""); 4.2 Comparison Comparing while and f loops In general a while-loop has the fm initialization; while () { ce loop body update/advancement This is exactly matched by the f-loop f (initialization; ; update/advancement) { ce loop body 5 Summary 5.1 General comparison Choosing the right loop The f-loop is called definite loop because you can typically predict how many times it will loop. while- and do-loops are indefinite loops, as you do not know a prii when they will end. The f-loop is typically used f math-related loops like counting finite sums. while-loop is good f situations where the could turn at any time. 16

do is used in same kind of situation as while loop, but when the body of the loop should execute at least once. When me than one type of loop will solve problem, use cleanest, simplest one 6 Nested loops 6.1 Multiplication table Task Write an algithm that will print the multiplication table f the numbers from 1 to n. F example let n = 4: 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 Solution Loop over all rows: int i = 1; while (i <= n) {... i++; Build an individual row: int j = 1; while (j <= n) { System.out.print (i * j + " "); j++; System.out.println (""); Solution Putting the elements together: public class MultTable { public static void main(string[] args) { int n = 5; int i = 1; while (i <= n) { int j = 1; while (j <= n) { System.out.print (i * j + " "); j++; System.out.println (""); i++; 17

Solution An alternative solution: public class MultTable2 { public static void main(string[] args) { int n = 5; f (i = 1; i <= n; i++) { f (j = 1; j <= n; j++) System.out.print (i * j + " "); System.out.println (""); 6.2 Triangle pattern Task Print a triangle pattern using an increasing number of brackets. F example (5 rows): [] [][] [][][] [][][][] [][][][][] Solution Loop over all rows:... f (int i = 1; i <= n; i++) { Build an individual triangle-row: f (int j = 1; j <= i; j++) r = r + "[]"; r = r + "\n"; Solution Putting the elements together: class Triangle { public static void main (String[] args ) { String r = ""; int n = 10; f (int i = 1; i <= n; i++) { f (int j = 1; j <= i; j++) r = r + "[]"; r = r + "\n"; System.out.print (r); 18

7 Coming up 7.1 Next week Next week s events The next topic will be the concept of procedures and methods. 19