Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

Size: px
Start display at page:

Download "Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of"

Transcription

1 Basic Problem solving Techniques Top Down stepwise refinement If & if.. While.. Counter controlled and sentinel controlled repetition Usage of Assignment increment & decrement operators 1

2 ECE 161 WEEK 7 Control Statements Part Prof Dr. Ziya B. Güvenç Res. Asst. Barbaros Preveze IF single selection statement If we want to write a program that decides whether the student passes or not, our program has to decide for this by checking if the grade is greater than 60 or not. Thus we need the word if to decide whether the grade is greater that 60 or not. If the grade is greater than or equal to 60, print to the screen that the student passes. This sentence can easily be coded in Java programming language as seen below. if (studentgrade >= 60) System.out.println( passed ); IF. ELSE.. statement After the decision we may want to write a code print passed if the grade is greater or equal to 60 and we may want to print failed if the grade is less than 60. In this case we use if. if (studentgrade >= 60) System.out.println( passed ); System.out.println( failed ); Here the word stands for if the grade not greater or equal to. Conditional Operator System.out.println(studentGrade>=60? Passed : Failed ); The statement above is equivalent to if (studentgrade >= 60) System.out.println( passed ); System.out.println( failed ); Nested if and Nested if structure is used for blocking the part as a separated if statement that will work if and only if the if statement is not provided i.e. 2

3 if (studentgrade >= 90) System.out.println( AA ); if (studentgrade >= 85) System.out.println( BA ); if (studentgrade >= 75) System.out.println( BB ); if (studentgrade >= 70) System.out.println( CB ); if (studentgrade >= 60) System.out.println( CC ); System.out.println( Failed ); if (studentgrade >= 90) System.out.println( AA ); if (studentgrade >= 85) System.out.println( BA ); if (studentgrade >= 75) System.out.println( BB ); if (studentgrade >= 70) System.out.println( CB ); if (studentgrade >= 60) System.out.println( CC ); System.out.println( Failed ); Dangling Problem If (a> 2) If (b<5) System.out.println( a is greater than 2 and b is less than 5 ); System.out.println( a is greater than 2 but b is greater than or equal to 5 ); System.out.println( a is less than or equal to 2 ); 3

4 If (a> 2) If (b<5) System.out.println( a is greater than 2 and b is less than 5 ); System.out.println( a is greater than 2 but b is greater than or equal to 5 ); System.out.println( a is less than or equal to 2 ); Blocks If (a> 2) If (b<5) System.out.println( a is greater than 2 ); System.out.println( a is less than 5 ); } Else System.out.println( a is greater than 2 but b is greater than or equal to 5 ); System.out.println( a is greater than or equal to 2 ); Counter controlled While Repetition Statement Repetition loop Some times we want to make something until some other thing happens or stops happening. In this case we use while statement for this purpose. E.g If you have a shopping list and if you want to purchase everything in your shopping list You will write a code which says; While the shopping list is not empty,purchase the first item in the list and cross it off This way the things that you ve already purchased will not be purchased again. Or if you want to add the numbers retrieved from the user, you want the program to stop when the sum of these numbers reaches to 1000 and display the number of entries,i.e the code will be; 4

5 import java.util.scanner; // program uses Scanner public class Product public static void main( String args[] ) int sum; int number; int person; Scanner input = new Scanner(System.in); sum=0; person=0; System.out.println("Enter the numbers below"); while(sum<1000) number = input.nextint(); sum=sum + number; person=person + 1; } System.out.printf("The total number of users = %d,with the total of %d\n", person, sum); } // end method main Output : In this program programmer is not aware of how many entry will be entered. 5

6 Implementing Counter Controlled repetition in Class GradeBook import java.util.scanner; // program uses class Scanner public class GradeBook private String coursename; // name of course this GradeBook represents // constructor initializes coursename public GradeBook( String name ) coursename = name; // initializes coursename } // end constructor // method to set the course name public void setcoursename( String name ) coursename = name; // store the course name } // end method setcoursename // method to retrieve the course name public String getcoursename() return coursename; } // end method getcoursename // display a welcome message to the GradeBook user public void displaymessage() // getcoursename gets the name of the course System.out.printf( "Welcome to the grade book for\n%s!\n\n", getcoursename() ); } // end method displaymessage // determine class average based on 10 grades entered by user public void determineclassaverage() // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int total; // sum of grades entered by user int gradecounter; // number of the grade to be entered next int grade; // grade value entered by user int average; // average of grades // initialization phase total = 0; // initialize total gradecounter = 1; // initialize loop counter // processing phase 6

7 while ( gradecounter <= 10 ) // loop 10 times System.out.print( "Enter grade: " ); // prompt grade = input.nextint(); // read grade from user total = total + grade; // add grade to total gradecounter = gradecounter + 1; // increment counter by 1 } // end while // termination phase average = total / 10; // integer division yields integer result // display total and average of grades System.out.printf( "\ntotal of all 10 grades is %d\n", total ); System.out.printf( "Class average is %d\n", average ); } // end method determineclassaverage } // end class GradeBook public class GradeBookTest public static void main( String args[] ) // create GradeBook object mygradebook and // pass course name to constructor GradeBook mygradebook = new GradeBook( "CS101 Introduction to Java Programming" ); mygradebook.displaymessage(); // display welcome message mygradebook.determineclassaverage(); // find average of 10 grades } // end main } // end class GradeBookTest OUTPUT 7

8 FORMULATING ALGORITHMS: SENTINEL CONTROLLED REPITATION Assume that the user wants to calculate the average grade of any class, but the user doesn t have any idea about the number of students in the class. In this case you want to write a program which continuously retrieve inputs from the user and stops when the grade is entered as -1. if -1 is entered it will stop, calculate the average and display the result on the screen. Here -1 (which we have arbitrarily chosen) is sentinel value (flag value, dummy value, signal value) you may chose any number as sentinel value to stop the execution of the program. The program codes implementing this is given below; import java.util.scanner; // program uses class Scanner public class GradeBook private String coursename; // name of course this GradeBook represents // constructor initializes coursename public GradeBook( String name ) coursename = name; // initializes coursename } // end constructor // method to set the course name public void setcoursename( String name ) coursename = name; // store the course name } // end method setcoursename // method to retrieve the course name public String getcoursename() return coursename; } // end method getcoursename // display a welcome message to the GradeBook user public void displaymessage() // getcoursename gets the name of the course System.out.printf( "Welcome to the grade book for\n%s!\n\n", getcoursename() ); } // end method displaymessage // determine the average of an arbitrary number of grades public void determineclassaverage() // create Scanner to obtain input from command window 8

9 Scanner input = new Scanner( System.in ); int total; // sum of grades int gradecounter; // number of grades entered int grade; // grade value double average; // number with decimal point for average // initialization phase total = 0; // initialize total gradecounter = 0; // initialize loop counter // processing phase // prompt for input and read grade from user System.out.print( "Enter grade or -1 to quit: " ); grade = input.nextint(); // loop until sentinel value read from user while ( grade!= -1 ) total = total + grade; // add grade to total gradecounter = gradecounter + 1; // increment counter // prompt for input and read next grade from user System.out.print( "Enter grade or -1 to quit: " ); grade = input.nextint(); } // end while // termination phase // if user entered at least one grade... if ( gradecounter!= 0 ) // calculate average of all grades entered average = (double) total / gradecounter; // display total and average (with two digits of precision) System.out.printf( "\ntotal of the %d grades entered is %d\n", gradecounter, total ); System.out.printf( "Class average is %.2f\n", average ); } // end if // no grades were entered, so output appropriate message System.out.println( "No grades were entered" ); } // end method determineclassaverage } // end class GradeBook 9

10 public class GradeBookTest public static void main( String args[] ) // create GradeBook object mygradebook and // pass course name to constructor GradeBook mygradebook = new GradeBook( "CS101 Introduction to Java Programming" ); mygradebook.displaymessage(); // display welcome message mygradebook.determineclassaverage(); // find average of grades } // end main } // end class GradeBookTest OUTPUT: NESTED CONTROL STRUCTURES While. If. Sometimes we may need these control structures one in the other (nested). Here is an example in which we need the usage of these statements in nested structure. 10

11 The program below retrieves 10 inputs from the user, (1 -> passed, 2 -> failed); import java.util.scanner; // class uses class Scanner public class Analysis public void processexamresults() // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // initializing variables in declarations int passes = 0; // number of passes int failures = 0; // number of failures int studentcounter = 1; // student counter int result; // one exam result (obtains value from user) // process 10 students using counter-controlled loop while ( studentcounter <= 10 ) // prompt user for input and obtain value from user System.out.print( "Enter result (1 = pass, 2 = fail): " ); result = input.nextint(); // if... nested in while if ( result == 1 ) // if result 1, passes = passes + 1; // increment passes; // result is not 1, so failures = failures + 1; // increment failures // increment studentcounter so loop eventually terminates studentcounter = studentcounter + 1; } // end while // termination phase; prepare and display results System.out.printf( "Passed: %d\nfailed: %d\n", passes, failures ); // determine whether more than 8 students passed if ( passes > 8 ) System.out.println( "Raise Tuition" ); } // end method processexamresults } // end class Analysis 11

12 public class AnalysisTest public static void main( String args[] ) Analysis application = new Analysis(); // create Analysis object application.processexamresults(); // call method to process results } // end main } // end class AnalysisTest OUTPUT: Compound Assignment Operator Initially c=3, d=5, e=4, f=6, g=12 Assignment operator Sample Expression Explanation Assigns += C+=7 C=C+7 10 to C -= D-=4 D=D-4 1 to D *= E*=5 E=E*5 20 to E /= F/=3 F=F/3 2 to F %= G%=9 G=G%9 3 to G Increment and Decrement Operators Sample expression Called Explanation ++a Prefix increment Inc. by 1 then use new value a++ Postfix increment Use old value then inc. by 1 --b Prefix decrement Dec. by 1 then use new value b-- Postfix decrement Use old value then dec. by 1 12

13 For understanding better,lets write a program which uses these expressions public class Increment public static void main( String args[] ) int c; // demonstrate postfix increment operator c = 5; // assign 5 to c System.out.println( c ); // print 5 System.out.println( c++ ); // print 5 then postincrement System.out.println( c ); // print 6 System.out.println(); // skip a line // demonstrate prefix increment operator c = 5; // assign 5 to c System.out.println( c ); // print 5 System.out.println( ++c ); // preincrement then print 6 System.out.println( c ); // print 6 } // end main } // end class Increment OUTPUT : 13

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M Control Structures Intro. Sequential execution Statements are normally executed one

More information

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 3- Control Statements: Part I Objectives: To use the if and if...else selection statements to choose among alternative actions. To use the

More information

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program.

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program. 1 Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program. public class Welcome1 // main method begins execution of Java application System.out.println( "Welcome to Java Programming!" ); } //

More information

Object Oriented Programming. Java-Lecture 1

Object Oriented Programming. Java-Lecture 1 Object Oriented Programming Java-Lecture 1 Standard output System.out is known as the standard output object Methods to display text onto the standard output System.out.print prints text onto the screen

More information

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1 CSE123 LECTURE 3-1 Program Design and Control Structures Repetitions (Loops) 1-1 The Essentials of Repetition Loop Group of instructions computer executes repeatedly while some condition remains true Counter-controlled

More information

ECE 161 WEEK 4 Introduction to Programing in Java

ECE 161 WEEK 4 Introduction to Programing in Java 1 ECE 161 WEEK 4 Introduction to Programing in Java 26.10.05 Prof Dr. Ziya B. Güvenç Res. Asst. Barbaros Preveze Java creator and Software Development Kit J(2S)DK is used for compiling any portion of the

More information

Lecture 7: Classes and Objects CS2301

Lecture 7: Classes and Objects CS2301 Lecture 7: Classes and Objects NADA ALZAHRANI CS2301 1 What is OOP? Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly

More information

Structured Program Development in C

Structured Program Development in C 1 3 Structured Program Development in C 3.2 Algorithms 2 Computing problems All can be solved by executing a series of actions in a specific order Algorithm: procedure in terms of Actions to be executed

More information

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Chapter 3 Structured Program Development

Chapter 3 Structured Program Development 1 Chapter 3 Structured Program Development Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 - Structured Program Development Outline 3.1 Introduction

More information

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 2- Arithmetic and Decision Making: Equality and Relational Operators Objectives: To use arithmetic operators. The precedence of arithmetic

More information

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 1 2 Introduction to Classes and Objects You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Structured Program Development

Structured Program Development Structured Program Development Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Introduction The selection statement if if.else switch The

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 3 Nothing can have value without being an object of utility. Karl Marx Your public servants serve you right. Adlai E. Stevenson Knowing how to answer one who speaks, To reply to one who sends a message.

More information

Chapter 3 Structured Program Development in C Part II

Chapter 3 Structured Program Development in C Part II Chapter 3 Structured Program Development in C Part II C How to Program, 8/e, GE 2016 Pearson Education, Ltd. All rights reserved. 1 3.7 The while Iteration Statement An iteration statement (also called

More information

Control Statements. Musa M. Ameen Computer Engineering Dept.

Control Statements. Musa M. Ameen Computer Engineering Dept. 2 Control Statements Musa M. Ameen Computer Engineering Dept. 1 OBJECTIVES In this chapter you will learn: To use basic problem-solving techniques. To develop algorithms through the process of topdown,

More information

Programming with Java

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

More information

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

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Before writing a program to solve a problem, have a thorough understanding of the problem and a carefully planned approach to solving it. Understand the types of building

More information

CS141 Programming Assignment #6

CS141 Programming Assignment #6 CS141 Programming Assignment #6 Due Sunday, Nov 18th. 1) Write a class with methods to do the following output: a) 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 b) 1 2 3 4 5 4 3 2 1 1 2 3 4 * 4 3 2 1 1 2 3 * * * 3 2 1

More information

Control Structures (Deitel chapter 4,5)

Control Structures (Deitel chapter 4,5) Control Structures (Deitel chapter 4,5) 1 2 Plan Control Structures ifsingle-selection Statement if else Selection Statement while Repetition Statement for Repetition Statement do while Repetition Statement

More information

Fundamentals of Programming Session 7

Fundamentals of Programming Session 7 Fundamentals of Programming Session 7 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

JAVA- PROGRAMMING CH2-EX1

JAVA- PROGRAMMING CH2-EX1 http://www.tutorialspoint.com/java/java_overriding.htm package javaapplication1; public class ch1_ex1 JAVA- PROGRAMMING CH2-EX1 //main method public static void main(string[] args) System.out.print("hello

More information

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases. Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Repetition In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability.

More information

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

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

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure

More information

Control Statements: Part 1

Control Statements: Part 1 4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 3 Introduction to Classes and Objects OBJECTIVES In this chapter you will learn: What classes, objects, methods and instance variables are. How to declare a class and use it to create an object. How to

More information

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Copyright 1992-2012 by Pearson Copyright 1992-2012 by Pearson Before writing a program to solve a problem, have

More information

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. 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

More information

Dr.Ammar Almomani. Dept. of Information Technology, Al-Huson University College, Al- Balqa Applied University. Dr. Ammar Almomani-2017-BAU Page 1

Dr.Ammar Almomani. Dept. of Information Technology, Al-Huson University College, Al- Balqa Applied University. Dr. Ammar Almomani-2017-BAU Page 1 Dr.Ammar Almomani Dept. of Information Technology, Al-Huson University College, Al- Balqa Applied University Dr. Ammar Almomani-2017-BAU Page 1 Java Programming Syllabus First semester/ 2017 Course Title:

More information

Supplementary Test 1

Supplementary Test 1 Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2009 Supplementary Test 1 Question

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 5&6: Loops Lecture Contents Why loops?? While loops for loops do while loops Nested control structures Motivation Suppose that you need

More information

2.8. Decision Making: Equality and Relational Operators

2.8. Decision Making: Equality and Relational Operators Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

More information

Midterm Examination (MTA)

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

More information

Introduction to Computer Science I

Introduction to Computer Science I Introduction to Computer Science I Classes Janyl Jumadinova 5-7 March, 2018 Classes Most of our previous programs all just had a main() method in one file. 2/13 Classes Most of our previous programs all

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

More information

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved. Internet & World Wide Web How to Program, 5/e Sequential execution Execute statements in the order they appear in the code Transfer of control Changing the order in which statements execute All scripts

More information

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 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

More information

In this chapter you will learn:

In this chapter you will learn: 1 In this chapter you will learn: Essentials of counter-controlled repetition. Use for, while and do while to execute statements in program repeatedly. Use nested control statements in your program. 2

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

Chapter 4: Control structures. Repetition

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

More information

Example: Monte Carlo Simulation 1

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

More information

Controls Structure for Repetition

Controls Structure for Repetition 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

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure 2.8 Formulating

More information

Chapter 4: Control structures

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

More information

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise

More information

Control Statements: Part Pearson Education, Inc. All rights reserved.

Control Statements: Part Pearson Education, Inc. All rights reserved. 1 5 Control Statements: Part 2 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William Shakespeare The used key is

More information

download instant at

download instant at 2 Introduction to Java Applications: Solutions What s in a name? That which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would

More information

ITERATION WEEK 4: EXMAPLES IN CLASS

ITERATION WEEK 4: EXMAPLES IN CLASS Monday Section 2 import java.util.scanner; public class W4MSection2 { ITERATION WEEK 4: EXMAPLES IN CLASS public static void main(string[] args) { Scanner input1 = new Scanner (System.in); int CircleCenterX

More information

Iteration statements - Loops

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

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Suppose you want to drive a car and make it go faster by pressing down on its accelerator pedal. Before you can drive a car, someone has to design it and build it. A car typically begins as engineering

More information

CS141 Programming Assignment #8

CS141 Programming Assignment #8 CS141 Programming Assignment #8 Due Sunday, April 14th. 1- Write a class with methods to do the following output: a) 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 b) 1 2 3 4 5 4 3 2 1 1 2 3 4 * 4 3 2 1 1 2 3 * * * 3 2

More information

Object Oriented Programming. Java-Lecture 6 - Arrays

Object Oriented Programming. Java-Lecture 6 - Arrays Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e Before writing a program to solve a particular problem, it s essential to have a thorough understanding of the problem and a carefully planned approach to solving the problem. The

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure

More information

Lab 2: Structured Program Development in C

Lab 2: Structured Program Development in C Lab 2: Structured Program Development in C (Part A: Your first C programs - integers, arithmetic, decision making, Part B: basic problem-solving techniques, formulating algorithms) Learning Objectives

More information

Activity 6: Loops. Content Learning Objectives. Process Skill Goals

Activity 6: Loops. Content Learning Objectives. Process Skill Goals Activity 6: Loops Computers are often used to perform repetitive tasks. Running the same statements over and over again, without making any mistakes, is something that computers do very well. Content Learning

More information

Java Coding 3. Over & over again!

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

More information

AP Computer Science Unit 1. Programs

AP Computer Science Unit 1. Programs AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated

More information

Introduction to Computer Science Unit 2. Exercises

Introduction to Computer Science Unit 2. Exercises Introduction to Computer Science Unit 2. Exercises Note: Curly brackets { are optional if there is only one statement associated with the if (or ) statement. 1. If the user enters 82, what is 2. If the

More information

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

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

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 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:

More information

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 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

More information

A A B U n i v e r s i t y

A A B U n i v e r s i t y A A B U n i v e r s i t y Faculty of Computer Sciences O b j e c t O r i e n t e d P r o g r a m m i n g Week 4: Introduction to Classes and Objects Asst. Prof. Dr. M entor Hamiti mentor.hamiti@universitetiaab.com

More information

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition

More information

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

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18 Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical

More information

Arrays Pearson Education, Inc. All rights reserved.

Arrays Pearson Education, Inc. All rights reserved. 1 7 Arrays 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 Case Study: Card Shuffling and Dealing Simulation 7.6 Enhanced for Statement 7.7 Passing Arrays to

More information

CS110 Programming Language I. Lab 6: Multiple branching Mechanisms

CS110 Programming Language I. Lab 6: Multiple branching Mechanisms CS110 Programming Language I Lab 6: Multiple branching Mechanisms Computer Science Department Fall 2016 Lab Objectives: In this lab, the student will practice: Using switch as a branching mechanism Lab

More information

COMP 202 Java in one week

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

More information

Control Structures II. Repetition (Loops)

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 + +

More information

Bjarne Stroustrup. creator of C++

Bjarne Stroustrup. creator of C++ We Continue GEEN163 I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone. Bjarne Stroustrup creator

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware

More information

Computer Programming C++ Classes and Objects 6 th Lecture

Computer Programming C++ Classes and Objects 6 th Lecture Computer Programming C++ Classes and Objects 6 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline

More information

Repetition, Looping. While Loop

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

More information

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 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

More information

How to engineer a class to separate its interface from its implementation and encourage reuse.

How to engineer a class to separate its interface from its implementation and encourage reuse. 1 3 Introduction to Classes and Objects 2 OBJECTIVES In this chapter you ll learn: What classes, objects, member functions and data members are. How to define a class and use it to create an object. How

More information

Loops. Repeat after me

Loops. Repeat after me Loops Repeat after me Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements repeat is determined by the value of a control variable,

More information

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

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October

More information

CS110: PROGRAMMING LANGUAGE I

CS110: PROGRAMMING LANGUAGE I CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 4: Java Basics (II) A java Program 1-2 Class in file.java class keyword braces {, } delimit a class body main Method // indicates a comment.

More information

Repetition Structures

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

More information

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

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

More information

C Programming for Engineers Structured Program

C Programming for Engineers Structured Program C Programming for Engineers Structured Program ICEN 360 Spring 2017 Prof. Dola Saha 1 Switch Statement Ø Used to select one of several alternatives Ø useful when the selection is based on the value of

More information

Introduction to Computer Programming

Introduction to Computer Programming Introduction to Computer Programming Lecture 3 Counting Loops Repetition with for Loops So far, repeating a statement is redundant: System.out.println("Homer says:"); System.out.println("I am so smart");

More information

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. 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()

More information

Chapter 3. Selections

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

More information

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

More information

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation. Chapter 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop

More information

Over and Over Again GEEN163

Over and Over Again GEEN163 Over and Over Again GEEN163 There is no harm in repeating a good thing. Plato Homework A programming assignment has been posted on Blackboard You have to convert three flowcharts into programs Upload the

More information

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks: Mid Term Exam 1 Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Student Name: Total Marks: 50 Obtained Marks: Instructions: Do not open this exam booklet until you

More information

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

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

AP CS A Exam Review Answer Section

AP CS A Exam Review Answer Section AP CS A Exam Review Answer Section TRUE/FALSE 1. ANS: T TOP: Declaring Variables 2. ANS: T TOP: Generating Random Numbers 3. ANS: F TOP: The String Class 4. ANS: F TOP: Method Parameters 5. ANS: F TOP:

More information

Program Control Flow

Program Control Flow Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Program Control Flow

Program Control Flow Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Fundamentals of Programming Session 25

Fundamentals of Programming Session 25 Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

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 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

More information