Chapter 3: Control Statements

Similar documents
MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Chapter 2 Elementary Programming

Homework/Program #5 Solutions

Chapter 2 Introduction to Java programming

Object Oriented Software Design

Introduction to Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Object Oriented Software Design

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Topic 11 Scanner object, conditional execution

Sample CSE8A midterm Multiple Choice (circle one)

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Unit 6. Loop statements

While and Do-While Loops Summer 2010 Margaret Reid-Miller

Building Java Programs

In this Chapter you ll learn:

AP Computer Science Java Subset

Iteration CHAPTER 6. Topic Summary

Statements and Control Flow

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Building Java Programs

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

J a v a Quiz (Unit 3, Test 0 Practice)

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

12-6 Write a recursive definition of a valid Java identifier (see chapter 2).

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Building Java Programs

Example of a Java program

Conditional Statements Summer 2010 Margaret Reid-Miller

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Basic Java Syntax. Program Structure

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

LOOPS CHAPTER CHAPTER GOALS

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

AP Computer Science Java Mr. Clausen Program 9A, 9B

1. Writing Simple Classes:

CS 106 Introduction to Computer Science I

Using Files as Input/Output in Java 5.0 Applications

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Basics of Java Programming Input and the Scanner class

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

While Loop. 6. Iteration

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Building Java Programs

Two-way selection. Branching and Looping

Part I. Multiple Choice Questions (2 points each):

Introduction to Programming

Java Interview Questions and Answers

AP Computer Science Static Methods, Strings, User Input

How To Use The Database In Jdbc.Com On A Microsoft Gdbdns.Com (Amd64) On A Pcode (Amd32) On An Ubuntu (Amd66) On Microsoft

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Arrays in Java. Working with Arrays

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Java Program Coding Standards Programming for Information Technology

Building Java Programs

This explanations are for absolute beginners. Skilled programmers should (and probably will) use more effective approach.

Topic 16 boolean logic

Statements and Control Flow

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Building Java Programs

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

13 File Output and Input

The different kinds of variables in a Java program

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

For live Java EE training, please see training courses

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Cloud Computing on Amazon's EC2

Software Engineering Techniques

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Moving from CS 61A Scheme to CS 61B Java

Pemrograman Dasar. Basic Elements Of Java

Section 6 Spring 2013

Java Crash Course Part I

Threads 1. When writing games you need to do more than one thing at once.

106 #3 EXAMPLE FOR SCOPE REGIONS void A() { int B; void E() { int C; { int D; #4 LARGE EXAMPLE FOR HAND SIMULATION class HS { int g1 = 100; int g2 = 2

Building Java Programs

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

JAVA ARRAY EXAMPLE PDF

Object-Oriented Programming in Java

Class : MAC 286. Data Structure. Research Paper on Sorting Algorithms

Introduction to Java Lecture Notes. Ryan Dougherty

OBJECT ORIENTED PROGRAMMING LANGUAGE

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Transcription:

Chapter 3: Control Statements Objectives: Concept of program control Selection statements Loop statements specific break and continue

Chapter 3: Control Statements Selection Statements Using if and if...else Nested if Statements Using switch Statements Conditional Operator Repetition Statements Looping: while, do, and for Nested loops Using break and continue

Selection Statements if Statements (conditional statement) switch Statements (multi conditional statement) Conditional Operators

if Statements if (booleanexpression) statement(s); Example: if ((i >= 0) && (i <= 10)) System.out.println("i is an + integer between 0 and 10");

The if...else Statement if (booleanexpression) statement(s)-for-the-true-case; else statement(s)-for-the-false-case;

if...else Example if (radius >= 0) area = radius*radius*pi; System.out.println("The area for the + circle of radius " + radius + " is " + area); else System.out.println("Negative input");

Nested if Statements Example 3.1: Using Nested if Statements This program reads in number of years and loan amount and computes the monthly payment and total payment. The interest rate is determined by number of years.

// TestIfElse.java: Test if-else statements public class TestIfElse // Main method public static void main(string[] args) double annualinterestrate = 0; int numofyears; double loanamount; // Enter number of years System.out.print( "Enter number of years (7, 15 and 30 only): "); numofyears = MyInput.readInt();

// Find interest rate based on year if (numofyears == 7) annualinterestrate = 7.25; else if (numofyears == 15) annualinterestrate = 8.50; else if (numofyears == 30) annualinterestrate = 9.0; else System.out.println("Wrong number of years"); System.exit(0); // Obtain monthly interest rate double monthlyinterestrate = annualinterestrate/1200;

// Enter loan amount System.out.print("Enter loan amount, for example 120000.95: "); loanamount = MyInput.readDouble(); // Compute mortgage double monthlypayment = loanamount*monthlyinterestrate/ (1-(Math.pow(1/(1+monthlyInterestRate), numofyears*12))); double totalpayment = monthlypayment*numofyears*12; // Display results System.out.println("The monthly payment is " + monthlypayment); System.out.println("The total payment is " + totalpayment);

Conditional Operator if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0)? 1 : -1;

switch Statements switch (year) case 7: annualinterestrate = 7.25; break; case 15: annualinterestrate = 8.50; break; case 30: annualinterestrate = 9.0; break; default: System.out.println( "Wrong number of years, enter 7, 15, or 30");

switch Statement Flow Chart 7 numofyears default 15 30 annualinterestrate=7.25 annualinterestrate=8.50 annualinterestrate=9.0 System.out.println("Wrong number of years, enter 7, 15, or 30"); Next Statement

Repetitions while Loops do Loops for Loops break and continue

while Loop Flow Chart Continue condition? false true Statement(s) Next Statement

while Loops while (continue-condition) // loop-body; Example 3.2: Using while Loops TestWhile.java

// TestWhile.java: Test the while loop public class TestWhile // Main method public static void main(string[] args) int data; int sum = 0; // Read an initial data System.out.println("Enter an int value"); data = MyInput.readInt();

// Keep reading data until the input is 0 while (data!= 0) sum += data; System.out.println( "Enter an int value, the program exits if the input is 0"); data = MyInput.readInt(); System.out.println("The sum is " + sum);

do Loops do // Loop body; while (continue-condition)

do Loop Flow Chart Statement(s) true Continue condition? false Next Statement

for Loops for (control-variable-initializer; continue-condition; adjustment-statement) //loop body; int i = 0; while (i < 100) System.out.println("Welcome to Java! + i); i++; Example: int i; for (i = 0; i<100; i++) System.out.println("Welcome to Java! + i);

for Loop Flow Chart Evaluate Control-variable Expression i Adjustment expression Continue condition? false true Statement(s) (loop-body) Next Statement

for Loop Examples Examples for using the for loop: Example 3.3: Using for Loops

// TestSum.java: Compute sum = 0.01 + 0.02 + + 1; public class TestSum // Main method public static void main(string[] args) // Initialize sum float sum = 0; // Keep adding 0.01 to sum for (float i=0.01f; i <= 1.0f ; i = i+0.01f) sum += i; // Display result System.out.println("The summation is " + sum);

for nested Loop Examples Example 3.4: Multiplication Table; Using Nested for Loops

// TestMulTable.java: Display a multiplication table public class TestMulTable // Main method public static void main(string[] args) // Get start time long starttime = System.currentTimeMillis(); // Display the table heading System.out.println(" Multiplication Table"); System.out.println("-----------------------------------"); // Display the number title System.out.print(" "); for (int j=1; j<=9; j++) System.out.print(" " + j); System.out.println(" ");

// Print table body for (int i=1; i<=9; i++) System.out.print(i+" "); for (int j=1; j<=9; j++) // Display the product and align properly if (i*j < 10) System.out.print(" " + i*j); else System.out.print(" " + i*j); System.out.println();

// Get end time long endtime = System.currentTimeMillis(); System.out.println("Elapsed time is " + (endtime - starttime) + " milliseconds");

The break Keyword Continue condition? false true Statement(s) break Statement(s) Next Statement

Using break and continue Examples for using the break keyword: Example 3.5: TestBreak.java

// TestBreak.java: Test the break keyword in the loop public class TestBreak // Main method public static void main(string[] args) int sum = 0; int item = 0; while (item < 2000) item ++; sum += item; if (sum >= 600) break; System.out.println("The sum is " + sum); System.out.println("item is " + item);

The continue Keyword Continue condition? false true Statement(s) continue Statement(s) Next Statement

Using break and continue Examples for using the continue keyword: Example 3.6: TestContinue.java

// TestContinue.java: Test the continue keyword public class TestContinue // Main method public static void main(string[] args) int sum = 0; int item = 0; while (item < 5) item++; if (item == 2) continue; sum += item; System.out.println("The sum is " + sum);

Using Statement Labels and breaking with Labels outer: for (int i=1;i<10;i++) inner: for (int j=1;j<10;j++) break outer; System.out.println(i*j);

Case Studies (1) Example: Commission using while and if statements

// FindSalesAmount.java: Find the sales amount to get the desired // commission public class FindSalesAmount // Main method public static void main(string[] args) // The commission sought final double COMMISSION_SOUGHT = 25000; double commission = 0; double salesamount = 1; while (commission < COMMISSION_SOUGHT) // Compute commission

if (salesamount >= 10001) commission = 5000*0.08 + 5000*0.1 + (salesamount-10000)*0.12; else if (salesamount >= 5001) commission = 5000*0.08 + (salesamount-5000)*0.10; else commission = salesamount*0.08; salesamount++; // Display the sales amount System.out.println("The sales amount " + salesamount + " is needed to make a commission of $" + COMMISSION_SOUGHT);

Case Studies (2) Example: Display a Pyramid using nested for loop

public class PrintPyramid // Main method public static void main(string[] args) for (int row = 1; row < 6; row++) // Print leading spaces for (int column = 1; column < 6 - row; column++) System.out.print(" "); // Print leading numbers for (int num = row; num >= 1; num--) System.out.print(num);

// Print ending numbers for (int num = 2; num <= row; num++) System.out.print(num); // Start a new line System.out.println();

Case Studies (3) Example: Calculate prime number

// PrimeNumber.java: Print first 50 prime numbers public class PrimeNumber // Main method public static void main(string[] args) int count = 1; // Count the number of prime numbers int number = 2; // A number to be tested for primeness boolean isprime = true; // If the current number is prime? System.out.println("The first 50 prime numbers are \n");

// Repeatedly test if a new number is prime while (count <= 50) // Assume the number is prime isprime = true; // Set isprime to false, if the number is prime for (int divisor = 2; divisor <= number/2; divisor++) if (number % divisor == 0) // If true, the number is prime isprime = false; break; // Exit the for loop

// Print the prime number and increase the count if (isprime) if (count%10 == 0) // Print the number and advance to the new line System.out.println(number); else System.out.print(number + " "); count++; // Increase the count // Check if the next number is prime number++;