Upload
natalie-keith
View
213
Download
1
Tags:
Embed Size (px)
Citation preview
22 February 2013 Birkbeck College, U. London 1
Introduction to Programming
Lecturer: Steve Maybank
Department of Computer Science and Information Systems
[email protected] 2013
Week 7: loops
Overview
Java Lab 6, Exercises 2 and 3 while statement for statement See Java for Everyone, Ch. 4
22 February 2013 Birkbeck College, U. London 2
JavaLab 6, Qu. 2
22 February 2013 Birkbeck College, U. London 3
Score Grade
90-100
A
80-89 B
70-79 C
60-69 D
<60 E
Obtain a score of type int fromthe keyboard and print out thecorresponding letter grade.
Solution to Qu. 2: first partimport java.util.Scanner;public class QuizGrading{
public static void main(String[] args){
Scanner in = new Scanner(System.in);System.out.print("Please type in the score: ");int score = in.nextInt();… // more code here
System.out.print("The grade is: "+grade);
}}
22 February 2013 Birkbeck College, U. London 4
Solution to Qu. 2: second part
char grade = ' ';if (score >= 90)
{grade = 'A';}else if (score >= 80)
{grade = 'B';}else if (score >= 70)
{grade = 'C';}else if (score >= 60)
{grade = 'D';}else
{grade = 'E';}
22 February 2013 Birkbeck College, U. London 5
Diagram for Question 2
22 February 2013 Birkbeck College, U. London 6
50 807060 10090
>=A
>= D
>= C
>= B
E
JavaLab 6, Qu. 3 Obtain a year of type int from the
keyboard. Print true if it is a leap year, otherwise print false.
Usually years that are divisible by 4 are leap years. However, years that are divisible by 100 are not leap years, unless the year is also divisible by 400.
22 February 2013 Birkbeck College, U. London 7
Decision Tree
22 February 2013 Birkbeck College, U. London 8
divisibleby 4?
yesno
not a leapyear
divisibleby 100
?leapyear
no yes
divisibleby 400
?not a leapyear
no yes
leapyear
Two Paths through the Decision Tree
a: (year%4 == 0); b: (year%100 !=0); c: (year%100 == 0) && (year%400 ==
0); First path: a && b; Second path: a && c;
22 February 2013 Birkbeck College, U. London 9
Boolean Test for a Leap Year
Solution: (a && b)||(a && c) Equivalent solution: a && (b||c) Proof of equivalence:
check a = false (both are false)check a = true (both reduce to b||c)
22 February 2013 Birkbeck College, U. London 10
Solution to Qu. 3: first partimport java.util.Scanner;public class LeapYear{
public static void main(String[] args){
Scanner in = new Scanner(System.in);System.out.print("Please type in the year: ");int year = in.nextInt();… // more code here
}}
22 February 2013 Birkbeck College, U. London 11
Solution to Qu. 3: second part
boolean a = year%4 == 0;boolean b = year%100 != 0;boolean c = (year%100==0) && (year%400==0);if (a && (b||c)){
System.out.println("Leap year");}else{
System.out.println("Not a leap year");}
22 February 2013 Birkbeck College, U. London 12
Syntax for the while Loop
while (boolean condition){
statements}/* The statements are carried out
while the condition tests true. */
22 February 2013 Birkbeck College, U. London 13
Flowchart for the while Loop
22 February 2013 Birkbeck College, U. London 14
testcondition
true
false
executestatements
Example: compound interest
double balance = 10000;int year = 0;while (balance < TARGET){
year++;double interest = balance*RATE/100;balance = balance+interest;
}
22 February 2013 Birkbeck College, U. London 15
Access to Variablesdouble balance = 10000;…while (balance < TARGET){
double interest = balance*RATE/100;…
}/* The variable balance is declared outside the loop and is
available inside and outside the loop. The variable interest is declared inside the loop and is only available inside the loop. A new version of the variable interest is created on each iteration. */
22 February 2013 Birkbeck College, U. London 16
Compute Time to Double an
Investment public class DoubleInvestment{
public static void main(String[] args){
final double RATE = 5;final double INITIAL_BALANCE = 10000;final double TARGET = 2*INITIAL_BALANCE;double balance = INITIAL_BALANCE;int year = 0;/* while loop here */System.out.println("Investment doubled after "+year+" years");
}}
22 February 2013 Birkbeck College, U. London 17
Test Cases Use very simple test data to check that the
while loop is correct. Eg. if
RATE = 100.1%,TARGET = 2*INITIAL_BALANCEthen the balance is slightly more than doubled at the end of the first year.
Check the value of year on exiting the loop.
22 February 2013 Birkbeck College, U. London 18
while Loop Example 1
int i = 0, sum = 0;while(sum < 10){
i++; sum = sum+i;System.out.print(i+" "+sum+", ");
}/* output: 1 1, 2 3, 3 6, 4 10, */
22 February 2013 Birkbeck College, U. London 19
while Loop Example 2
int i = 0, sum = 0;while(sum < 10){
i++; sum = sum-i;System.out.print(i+" "+sum+", ");
}/* output: 1 -1, 2 -3, 3 -6, 4 -10, … */
22 February 2013 Birkbeck College, U. London 20
The for Loop
for(int i = 1; i <=10; i++){
System.out.println(i);}/* Use a for loop when the number of
iterations is known in advance.The for loop is count controlled.The while loop is event controlled. */
22 February 2013 Birkbeck College, U. London 21
Parts of the for Statement
for (int i = 0; i <= 10; i++){
…}/* i = 0: initialisation, executed once on entering the loop.
i <= 10: condition to be checked before each iteration.i++: update executed after each iteration. */
22 February 2013 Birkbeck College, U. London 22
Examples of for Loops
22 February 2013 Birkbeck College, U. London 23
Loop values of I comment
for(int i = 0; i <= 5; i++) 0 1 2 3 4 5 The loop is executed 6 times
for(int i = 5; i >= 0; i--) 5 4 3 2 1 0 The value of i can decrease
for(int i = 0; i < 9; i = i+2) 0 2 4 6 8 Step size not equal to 1
for(int i = 0; i != 9; i = i+2) 0 2 4 6 8 … Infinite loop
for(int i = 1; i <= 20; i = i*2) 1 2 4 8 6 Any rule for modifying i can be used
for(int i = 0; i<str.length(); i++)
0 1 … str.length()-1
Step through the characters in a string
Avoid Confusing for Loops
double x, sum = 0;
for(System.out.print(“Input: ”); in.hasNextDouble(); sum += x)
{
x = in.nextDouble();
}
/* The compiler does not check whether the initialisation, condition and update are related.
in.hasNextDouble() tests to see if the next input is a number. */
22 February 2013 Birkbeck College, U. London 24
Sum and Average Valuedouble total = 0;int count = 0;while (in.hasNextDouble()){
double input = in.nextDouble();total = total+input;count++;
}double average = 0;if (count > 0){average = total/count;}
22 February 2013 Birkbeck College, U. London 25
Counting Matches
int upperCaseLetters = 0; // initialise a counterfor (int i = 0; i < str.length(); i++){
char ch = str.charAt(i); //obtain the ith character in strif (Character.isUpperCase(ch)) //test for upper case{
upperCaseLetters++;}
}/* Character.isUpperCase is a method in the class Character
which is in the package java.lang. */
22 February 2013 Birkbeck College, U. London 26