Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining.

Slides:



Advertisements
Similar presentations
Lecture 10.2 Different Types of Loops, including for and do.
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Introduction to Flowcharting A Supplement to Starting Out with C++, 4th Edition by Tony Gaddis Published by Addison-Wesley.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Introduction to Java Programming, 4E Y. Daniel Liang.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Java Programming: From the Ground Up
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 4 Objectives  Learn about repetition (looping) control structures.
Jaeki Song ISQS6337 JAVA Lecture 04 Control Structure - Selection, and Repetition -
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Programming Logic and Design Fifth Edition, Comprehensive
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 5 Loops.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
6 Chapter 61 Looping Programming Logic and Design, Second Edition, Comprehensive 6.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Flow of Control Chapter 3 Flow of control Branching Loops
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Application development with Java Lecture 6 Rina Zviel-Girshin.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
COMP Loop Statements Yi Hong May 21, 2015.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Looping Increment/Decrement Switch. Flow of Control Iteration/Switch Statements.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Loops, Part II IT108 George Mason University. Indefinite Loop Don’t always have access to the number of iterations ahead of time If a condition (user-response,
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Chapter 5: Control Structures II
Chapter 4 C Program Control Part I
Lecture 6 Repetition Richard Gesick.
Chapter 5: Control Structures II
Chapter 5: Control Structures II
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Repetition-Counter control Loop
Chapter 5: Control Structures II
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
3 Control Statements:.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Control Structures

2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining instruction flow.  Two main types  Selection  Repetition  Others later

3  Sometimes need to make a choice  If the amount of an Amazon.com purchase is less than 25 then add shipping  If a bank withdrawal would yield a negative balance then don’t allow the withdrawal  If a user enters a SSN that is not consist of exactly 9 digits then print an error message.

4  The single-branch (one way) if statement is the simplest selection. if( some_condition ) { then_clause } if( some_condition ) { then_clause }  some_condition: Any expression that has boolean type  then_clause: A statement sequence  the ‘{}’ is not needed if the then clause is a single statement but should be used

5 PROBLEM: Write a code fragment that prints the message "Overtime" if an employee has worked more than 40 hours in the past week.. double hoursWorked; // assume that hoursWorked // has been initialized.

6  The if-else statement is a two-way conditional. if( some_condition ) { then_clause } else { else_clause } if( some_condition ) { then_clause } else { else_clause }  some_condition: Any expression that has boolean type  then_clause: A statement sequence  else_clause: A statement sequence

7 PROBLEM: Write a code fragment that determines the total cost of an internet purchase. The company charges a flat fee of $5 shipping if the purchase amount is less than $30 otherwise they charge $5 plus 5% of the purchase for shipping. All values are in pennies. int totalCost, purchaseAmount; //assume purchaseAmount is initialized

8 PROBLEM: Write a code fragment that takes two ints (variables ‘a’ and ‘b’) and computes the largest of the two values as variable ‘max’. PROBLEM: Write a code fragment that takes three ints and computes the largest of the three values.

9  The if statement can be ‘multi-way’ if( condition1 ) { clause1 } else if( condition2 ) { clause2 } else if( condition3) { clause3 } else { default } if( condition1 ) { clause1 } else if( condition2 ) { clause2 } else if( condition3) { clause3 } else { default }

10 PROBLEM: Write a code fragment that determines the final cost for an internet purchase. If the purchase amount exceeds $100 the discount is 15%. If the amount is more than $75 up to $100 the discount is 10% else if the amount is more than $50 up to $75 the discount is 5% else the discount is 2.5%. int finalCost, purchaseAmount; //assume purchaseAmount is initialized

11  Sometime need to execute a code fragment more than once.  Loops can be classified as either ‘definite’ or ‘indefinite’  Definite – the number of repetitions is known by the programmer immediately prior to execution of the loop.  Indefinite – the number of repetitions is not known by the programmer.

12  Assume the following problems are to be solved with loops. Identify as either definite or indefinite.  Print the first ten letters of the alphabet.  Print the alphabet up to and including the letter “R”  Calculate the first integer power of 83 that is greater than one billion  Starting with distance d1 and d2 repeatedly divide them both in half until the resulting lengths are within 1 inch of each other.

13  While loop  Best used to solve indefinite looping problems while( condition ) { loopBody } while( condition ) { loopBody }

14 int sum, count; sum = 0; count = 1; while (count < 6 ) { sum = sum + count; count++; } System.out.println(sum);

15  Every loop has four parts  Initialization – establish the state prior to entering the loop  Primary work – the code that is to be repeatedly executed  Condition – a boolean criteria that controls when the loop stops  Make progress – code that moves the loop toward termination. int sum, count; sum = 0; count = 1; while (count < 6 ) { sum = sum + count; count++; } System.out.println(sum);

16  Original: sum ==  What changes are needed to cause the following postconditions?  sum == …+25  sum == …+25  sum == …+11 int sum, count; sum = 0; count = 1; while (count < 6 ) { sum = sum + count; count++; } System.out.println(sum);

17  Write code to print the circumference and area of circles with radius of 10, 20, …, 100.  Sam earns $100 per day with a daily raise of $100. Sue earns $0.01 per day with a salary that doubles every day. How many days pass before Sue’s total income exceeds Sam’s?

18 totalSam = 0; totalSue = 0; perDaySam = 10000; perDaySue = 1; dayCount = 0; while ( totalSue <= totalSam ) { dayCount++; totalSam = totalSam + perDaySam; totalSue = totalSue + perDaySue; perDaySam = perDaySam ; perDaySue = perDaySue * 2; }

DayperDaySueperDaySamtotalSuetotalSam

20  Write a code fragment to compute N!  Factorial definition  N! = 1*2*3*…*N  By convention we define 0! = 1  N must be non-negative int n = Keyboard.readInt(); int result = 1; while( n > 0) { result = result * n; n--; } int n = Keyboard.readInt(); int result = 1; while( n > 0) { result = result * n; n--; }

21  Write a code fragment to compute X raised to the Y power.  X can be any real value  Y must be a non-negative integer double x = Keyboard.readDouble(); int y = Keyboard.readInt(); double result = 1; while( y > 0) { result = result * x; y--; } double x = Keyboard.readDouble(); int y = Keyboard.readInt(); double result = 1; while( y > 0) { result = result * x; y--; }

22  An infinite loop occurs when termination is never reached. The loop never ends! int x = Keyboard.readInt(); int sum = 0; while( x != 0) { sum = sum + x; x = x - 2; } int x = Keyboard.readInt(); int sum = 0; while( x != 0) { sum = sum + x; x = x - 2; } int x = Keyboard.readInt(); while( x > 0) { x = Math.round( x/ 2.0); } int x = Keyboard.readInt(); while( x > 0) { x = Math.round( x/ 2.0); }

23  Infinite loops are not always ‘bad’! int n = Keyboard.readInt(); int result = 1; while(n != 0) { result = result * n; n--; } int n = Keyboard.readInt(); int result = 1; while(n != 0) { result = result * n; n--; } Computes n! but what about the logic of n=-1? int n = Keyboard.readInt(); int result = 1; while(n > 0) { result = result * n; n--; } int n = Keyboard.readInt(); int result = 1; while(n > 0) { result = result * n; n--; } Which is more logically correct?

24 int k = 1; while( k != 100 ) { // main work k++; } int k = 1; while( k != 100 ) { // main work k++; } int k = 100; while( k >= 0 ) { // main work k--; } int k = 100; while( k >= 0 ) { // main work k--; } int k = 0; while( k < 99 ) { // main work k++; } int k = 0; while( k < 99 ) { // main work k++; } int k = 1; while( k < 100 ) { // main work k++; } int k = 1; while( k < 100 ) { // main work k++; } Which of these executes the main work 100 times? int k = 99; while( k > 0 ) { // main work k--; } int k = 99; while( k > 0 ) { // main work k--; }

25  Premise: A loop is a Java statement  Premise: The body of a loop contains a sequence of Java statements  Conclusion: The body of a loop may contain a loop. int x = 1; while(x < 4) { int y = 1; while(y < 5) { System.out.print(x*y); System.out.print(“ “); y++; } System.out.println(); x++; } int x = 1; while(x < 4) { int y = 1; while(y < 5) { System.out.print(x*y); System.out.print(“ “); y++; } System.out.println(); x++; }

26  A repetition statement that executes the body 1 or more times. do { loopBody } while( condition );

27  Write a code fragment that reads input from the keyboard asking the user repeatedly for input until the input is valid. int minValue = 10, maxValue = 100; int result; do { result = Keyboard.readInt(); } while( ?? ); int minValue = 10, maxValue = 100; int result; do { result = Keyboard.readInt(); } while( ?? );

28  Best used for ‘definite’ looping  Typically uses a counter for( init ; condition ; make_progress) { main_work }

29  Print all whole numbers between 5 and 10 for( int n=1; n <= 5; n++) { System.out.println(n + 4); } for( int n=0; n < 5; n++) { System.out.println(n + 5); } for( int n=5; n <= 10; n++) { System.out.println(n); }

30  Print all odd numbers between 1 and 100 for( int n=1; n <= 100; n+=2) { System.out.println(n); }

31  Write code to print the first 5 powers of each integer value between 1 and N where N is a positive integer read from the keyboard. Print each values power on a single line int n = Keyboard.readInt(); for(int base=1; base<=n; base++) { for(int exp=1; exp<=5; exp++) { System.out.print(((int)Math.pow(base,exp)) + “ “); } System.out.println(); }

32  A specialized conditional  Use when there are many cases  Can be more efficient switch( expression ) { case CONSTANT1: statements1; break; case CONSTANT2: statements2; break; … case CONSTANTN: statements3; break; default: statementsDefault; }

33  Write a code fragment to determine the interest rate for a mortgage. The bank allows customers to take 3, 5, 7, 20, and 30 year mortgages with annual interest rates of 9%, 8.3%, 7.8%, 7.4% and 6.2% respectively. double interestRate; System.out.print(“Enter the number of years (3,5,7,20,30): “); int years = Keyboard.readInt(); switch( years ) { case 3: interestRate =.09; break; case 5: interestRate =.083; break; case 7: interestRate =.078; break; case 20: interestRate =.074; break; case 30: interestRate =.062; break; default: System.out.println(“invalid year selection”); }