Java Programming Language Midterm
Java Programming Language Midterm
Algorithm
Algorithm – a procedure for solving a problem in terms of the actions to
execute and the order in which these actions execute
– solution to a problem
Sample Algorithm for Adding two numbers A Java Program for adding two numbers
Example
if(a>b){
if(a>c){
System.out.println("The largest is" + a);
}else{
System.out.println("The largest is" + c);
}
}else if(b>c){
System.out.println("The largest is" + b);
}else{
System.out.println("The largest is" + c);
}
}
import java.util.Scanner;
public class root{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
int a,b,c;
double D,x1,x2,rp,ip;
System.out.println("Enter the value of a,b, and c");
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
D = b*b-4*a*c;
if(D>=0){
double r1 = (-b + Math.sqrt(D))/(2*a);
double r2 = (-b + Math.sqrt(D))/(2*a);
System.out.println("The roots are "+r1 +" and "+ r2);
}else{
ip = -b/(2*a);
rp = Math.sqrt(Math.abs(D)/(2*a));
System.out.println();
System.out.println("The roots are "+ip+"+"+rp+"i" +" and "+ ip+"-"+rp+"i");
}
}
}
Start Draw a flow chart that will
input radius and selection.
If selection is equal to 1 it
Read radius will display the
Read selection circumference of the circle,
if not it will display the area
of the circle.
Selection = 1 ?
C= 2*pi*r A= pi*r*r
Write C Write A
End
import java.util.Scanner;
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("Enter the radius");
int radius = input.nextInt();
System.out.println("Enter the selection");
int selection = input.nextInt();
if(selection ==1){
double C = 2*Math.PI*radius;
System.out.println("The circumference "+ C);
}else{
double A = Math.PI*radius*radius;
System.out.println("The Area "+ A);
}
}
Draw a flow chart that will input
Start radius and selection. If selection is
equal to 1 it will display the
A
circumference of the circle, if 2 it
will display the area of the circle. If
Read radius not it will display Try Another
Read selection Number.
Selection = 2?
Selection = 1 ?
A= pi*r*r
C= 2*pi*r
A End
import java.util.Scanner;
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("Enter the radius");
int radius = input.nextInt();
System.out.println("Enter the selection");
int selection = input.nextInt();
if(selection ==1){
double C = 2*Math.PI*radius;
System.out.println("The circumference "+ C);
}
if(selection ==2){
double A = Math.PI*radius*radius;
System.out.println("The Area "+ A);
}
System.out.println("Try another number");
}
}
Chapter 3 Selection Statements
Selection Statements
performs block statements depending on the
condition.
If Statement
If-else Statement
Nested if-else Statement
Switch
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
28
The ‘ if ’ construct
if i > 0 { if (i > 0) {
System.out.println("i is positive"); System.out.println("i is positive");
} }
(a) Wrong (b) Correct
if (i > 0) { if (i > 0)
System.out.println("i is positive"); Equivalent System.out.println("i is positive");
}
(a) (b)
31
Write a program that will input a number and display whether
the number is positive, negative or zero?
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int number = input.nextInt();
if(number>0) {
System.out.println("Positive");
}
if(number<0) {
System.out.println(“Negative");
}
if(number==0) {
System.out.println(“Zero");
}
}
}
Write a program that will input a number and display
whether the number is odd or even?
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int number = input.nextInt();
if(number%2==0) {
System.out.println("Even");
}
if(number%2!=0) {
System.out.println("Odd");
}
}
}
Write a program that will input date in mm dd yyyy
format and convert it into month dd yyyy format.
import java.util.Scanner; if(month == 8)
public class date{ System.out.print("August "+ day+ ", " + year);
public static void main(String[] arg){ if(month == 9)
Scanner input = new Scanner(System.in); System.out.print("September "+ day+ ", " + year);
System.out.println("Enter month: "); if(month == 10)
int month = input.nextInt(); System.out.print("October "+ day+ ", " + year);
System.out.println("Enter day:"); if(month == 11)
int day = input.nextInt(); System.out.print("November "+ day+ ", " + year);
System.out.println("Enter year:"); if(month == 12)
int year = input.nextInt(); System.out.print("December "+ day+ ", " + year);
System.out.println(); if(month > 12)
if(month == 1) System.out.print("Enter a number from 1-12");
System.out.print("January "+ day+ ", " + year); }
if(month == 2) }
System.out.print("February "+ day+ ", " + year);
if(month == 3)
System.out.print("March "+ day+ ", " + year);
if(month == 4)
System.out.print("April "+ day+ ", " + year);
if(month == 5)
System.out.print("May "+ day+ ", " + year);
if(month == 6)
System.out.print("June "+ day+ ", " + year);
if(month == 7)
System.out.print("July "+ day+ ", " + year);
Write a program that input 5 numbers and display
the largest number among the input numbers using
if-statements.
The ‘if else’ construct
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int number = input.nextInt();
if(number%2==0) {
System.out.println("Even");
}else {
System.out.println("Odd");
}
}
}
Program Output
public class Sample{
public static void main(String[] arg){
int a = 1, b=2;
if (a>b)
System.out.println("*****");
System.out.println("#####");
}}
public class Sample {
public static void main(String[] arg){
int a = 1, b=2;
if (a<b)
System.out.println("*****");
System.out.println("#####");
}}
49
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
50
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
51
animation
Trace if-else statement
Suppose score is 70.0 The condition is true
52
animation
Trace if-else statement
Suppose score is 70.0 grade is C
53
Note
The else clause matches the most recent if clause in the
same block.
int i = 1; int i = 1;
int j = 2; int j = 2;
int k = 3; int k = 3;
Equivalent
if (i > j) if (i > j)
if (i > k) if (i > k)
System.out.println("A"); System.out.println("A");
else else
System.out.println("B"); System.out.println("B");
(a) (b)
54
Note, cont.
Nothing is printed from the preceding statement. To
force the else clause to match the first if clause, you
must add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
55
Common Errors
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0); Wrong
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation error
or a runtime error, it is a logic error.
This error often occurs when you use the next-line block style.
56
TIP
if (number % 2 == 0)
Equivalent boolean even
even = true;
else = number % 2 == 0;
even = false;
(a) (b)
57
CAUTION
Equivalent if (even)
if (even == true)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)
58
Program Output
if (a<b)
smallest = a;
largest = b;
else if(b<c)
smallest = a;
largest = c;
if (b<a)
smallest = b;
largest = a;
else if(a<c)
smallest = b;
largest = c;
if (c<a)
smallest = c;
largest = a;
else if(a<b)
smallest = c;
largest = b;
65
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Random rand= new Random();
int a = rand.nextInt(10);
int b = rand.nextInt(10);
int difference = a-b;
System.out.print("What is "+a+" - "+b+" ?");
int x = input.nextInt();
if (x == difference) {
System.out.println("Correct");
}
else {
System.out.println("Incorrect");
}
}
}
Problem: Body Mass Index
BMI Interpretation
67
import java.util.Scanner;
public class ComputeBMI {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final double KILOGRAMS_PER_POUND = 0.45359237;
final double METERS_PER_INCH = 0.0254;
System.out.print("Enter weight in pounds: ");
double weight = input.nextDouble();
System.out.print("Enter height in inches: ");
double height = input.nextDouble();
double weightInKilogram = weight * KILOGRAMS_PER_POUND;
double heightInMeters = height * METERS_PER_INCH;
double bmi = weightInKilogram /(heightInMeters * heightInMeters);
System.out.printf("Your BMI is %5.2f\n", bmi);
if (bmi < 16)
System.out.println("You are seriously underweight");
else if (bmi < 18)
System.out.println("You are underweight");
else if (bmi < 24)
System.out.println("You are normal weight");
else if (bmi < 29)
System.out.println("You are overweight");
else if (bmi < 35)
System.out.println("You are seriously overweight");
else
System.out.println("You are gravely overweight");
}}
Problem: Computing Taxes
The US federal personal income tax is calculated based
on the filing status and taxable income. There are four
filing statuses: single filers, married filing jointly,
married filing separately, and head of household. The
tax rates for 2009 are shown below.
73
Truth Table for Operator &&
p1 p2 p1 && p2 Example (assume age = 24, gender = 'F')
false false false (age > 18) && (gender == 'F') is true, because (age
false true false > 18) and (gender == 'F') are both true.
true false false (age > 18) && (gender != 'F') is false, because
(gender != 'F') is false.
true true true
74
Truth Table for Operator ||
p1 p2 p1 || p2 Example (assume age = 24, gender = 'F')
false false false (age > 34) || (gender == 'F') is true, because (gender
false true true == 'F') is true.
true false true (age > 34) || (gender == 'M') is false, because (age >
true true true 34) and (gender == 'M') are both false.
75
Sample Program #1
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Score in Exam: ");
int exam = input.nextInt();
System.out.print("Enter Score in Quiz: ");
int quiz = input.nextInt();
if (exam>60 && quiz>60)
System.out.println("Passed");
else if (exam>60 || quiz>60)
System.out.println("Removal");
else
System.out.println("Failed");
}
}
Sample Program #1
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number= input.nextInt();
if(number%2==0&&number>0)
System.out.print(“The number is both positive and even");
}
}
if(number%2==0||number>0)
System.out.print(“The number is either positive or even or
both");
Problem: Body Mass Index
BMI Interpretation
78
Program Output
public class Sample{
public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a!=b&&b>c)
if(b<c||a<c)
System.out.println(“#####");
else
System.out.println(“%%%%%");
else
System.out.println(“*****");
}}
82
Problem #3
Write a program that will input your grade and determine equivalent.
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(0);
}
85
switch Statement Flow Chart
status is 0
Compute tax for single filers break
status is 1
Compute tax for married file jointly break
status is 2
Compute tax for married file separatly break
status is 3
Compute tax for head of household break
default
Default actions
Next Statement
86
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression) {
byte, short, or int type and
must always be enclosed case value1: statement(s)1;
in parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression. case valueN: statement(s)N;
The resulting statements in the
break;
case statement are executed when
the value in the case statement default: statement(s)-for-default;
matches the value of the switch- }
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
87
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the end
of each case in order to terminate
case value1: statement(s)1;
the remainder of the switch break;
statement. If the break statement case value2: statement(s)2;
is not present, the next case
statement will be executed. break;
…
case valueN: statement(s)N;
break;
The default case, which is
default: statement(s)-for-default;
optional, can be used to perform
actions when none of the }
specified cases matches the
switch-expression.
The case statements are executed in sequential
order, but the order of the cases (including the
default case) does not matter. However, it is good
programming style to follow the logical sequence
of the cases and place the default case at the end.
88
animation
Trace switch statement
Suppose ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
89
animation
Trace switch statement
ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
90
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
91
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
92
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
93
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
Next statement;
94
animation
Trace switch statement
Suppose ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
95
animation
Trace switch statement
ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
96
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
97
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
98
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
Next statement;
99
import java.util.Scanner;
public class date{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("Enter month: ");
int month = input.nextInt();
System.out.println("Enter day:");
int day = input.nextInt();
System.out.println("Enter year:");
int year = input.nextInt();
System.out.println();
switch (month){
case 1: System.out.print("January "+ day+ ", " + year); break;
case 2: System.out.print("February "+ day+ ", " + year); break;
case 3: System.out.print("March "+ day+ ", " + year); break;
case 4: System.out.print("April "+ day+ ", " + year); break;
case 5: System.out.print("May "+ day+ ", " + year); break;
case 6: System.out.print("June "+ day+ ", " + year); break;
case 7: System.out.print("July "+ day+ ", " + year); break;
case 8: System.out.print("August "+ day+ ", " + year); break;
case 9: System.out.print("September "+ day+ ", " + year); break;
case 10: System.out.print("October "+ day+ ", " + year); break;
case 11: System.out.print("November "+ day+ ", " + year); break;
case 12: System.out.print("December "+ day+ ", " + year); break;
default: System.out.print("Enter a number from 1-12");
}}}
Chapter 4 Loops
Loops cause program to execute the certain block of code
repeatedly until test condition is false. Loops are used in
performing repetitive task in programming. Consider
these scenarios:
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100 System.out.println("Welcome to Java!");
times System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
…
…
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
103
Introducing while Loops
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
104
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s); count++;
} }
count = 0;
Loop
false false
Continuation (count < 100)?
Condition?
true true
Statement(s) System.out.println("Welcome to Java!");
(loop body) count++;
(A) (B)
105
animation
106
animation
107
animation
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Print Welcome to Java
108
animation
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1
count is 1 now
109
animation
110
animation
111
animation
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1
count is 2 now
112
animation
113
animation
114
do-while Loop
do {
// Loop body; Statement(s)
Statement(s);
(loop body)
} while (loop-continuation-condition);
true Loop
Continuation
Condition?
false
115
animation
116
animation
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;
Print Welcome to Java
117
animation
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;
Increase count by 1
count is 1 now
118
animation
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;
119
animation
120
animation
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2)
Increase count by 1
count is 2 now
121
animation
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;
122
animation
123
for Loops
for (initial-action; loop- int i;
continuation-condition; for (i = 0; i < 100; i++) {
action-after-each-iteration) { System.out.println(
// loop body; "Welcome to Java!");
Statement(s);
} }
Initial-Action i=0
Loop
false false
Continuation (i < 100)?
Condition?
true true
Statement(s) System.out.println(
(loop body) "Welcome to Java");
Action-After-Each-Iteration i++
(A) (B)
124
animation
125
animation
126
animation
127
animation
128
animation
129
animation
130
animation
131
animation
Trace for Loop, cont.
Execute adjustment statement
i now is 2
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
132
animation
133
animation
134
Note
The initial-action in a for loop can be a list of zero or
more comma-separated expressions. The action-after-
each-iteration in a for loop can be a list of zero or more
comma-separated statements. Therefore, the following
two for loops are correct. They are rarely used in
practice, however.
for (int i = 1; i < 100; System.out.println(i++));
}
135
Note
If the loop-continuation-condition in a for loop is
omitted, it is implicitly true. Thus the statement given
below in (a), which is an infinite loop, is correct.
Nevertheless, it is better to use the equivalent loop in (b)
to avoid confusion:
136
Caution
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic Error
137
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
Logic Error
while (i < 10);
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the following semicolon is
needed to end the loop.
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10); Correct
138
Which Loop to Use?
The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is,
you can write a loop in any of these three forms. For example, a while loop in (a) in the following
figure can always be converted into the following for loop in (b):
A for loop in (a) in the following figure can generally be converted into the
following while loop in (b) except in certain special cases (see Review Question
3.19 for one of them):
for (initial-action; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
139
Recommendations
Use the one that is most intuitive and comfortable for
you. In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times. A while loop may be used if
the number of repetitions is not known, as in the case
of reading the numbers until the input is 0. A do-while
loop can be used to replace a while loop if the loop
body has to be executed before testing the continuation
condition.
140
public class Sample {
Write a program public static void main(String[] args) {
int x=1;
that will display the while(x<=10){
numbers from 1-10. System.out.println(x);
x++;
}
}}
import java.util.Scanner;
public class Sample { import java.util.Scanner;
public static void main(String[] args) { public class Sample {
int x=2; public static void main(String[] args) {
do{ for(int x=2; x<=100;x=x+2)
if(x%2==0){ System.out.println(x);
System.out.println(x); }}
x++;
}else{
x++;
}
}while(x<=100);
}}
Program Output
public class Sample{
public static void main(String[] arg){
for(int i=0;i<5;i++)
System.out.println(“Hello World”);
}}
public class Sample{
public static void main(String[] arg){
for(int i=1;i<=5;i++)
System.out.println(“Hello World”);
}}
public class Sample{
public static void main(String[] arg){
for(int i=5;i>0;i--)
System.out.println(“Hello World”);
}}
public class Sample{
public static void main(String[] arg){
for(int i=5;i>=3;i--)
System.out.println(“Hello World”);
}}
public class Sample{
public static void main(String[] arg){
int x=0;
do{
System.out.println(x);
x++;
}while(x>10);
}}
public class Sample{
public static void main(String[] arg){
int x=1;
while(x>10){
System.out.println(x);
x++;
}
}}
public class Sample{
public static void main(String[] arg){
int x=10;
while(x>5){
System.out.println(x);
x--;
}
}}
Write a program
that will display the import java.util.Scanner;
First 20 even public class Sample {
numbers public static void main(String[] args) {
int x=2;
while(x<=40){
System.out.println(x);
x++;
x++;
}
}}
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
int x=2; import java.util.Scanner;
do{ public class Sample {
if(x%2==0){ public static void main(String[] args) {
System.out.println(x); for(int x=0,y=2; x!=20;x++,y=y+2)
x++; System.out.println(y);
}else{ }}
x++;
}
}while(x<=40);
}}
import java.util.*
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("How many Hello World you want to display");
int x= input.nextInt();
for(int i=0;i<x;i++)
System.out.println(“Hello World”);
}}
import java.util.*
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int x= input.nextInt();
for(int i=1;i<=x;i++)
System.out.println(i);
}}
import java.util.*
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println(“Enter a number");
int x= input.nextInt();
for(int i=1;i<=10;i++)
System.out.println(i*x);
}}
import java.util.*
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("Enter two number");
int x= input.nextInt();
int y= input.nextInt();
for(int i=x;i<y;i++)
System.out.println(i);
}}
More Assignment Statement
There is a shorthand notation that combines the assignment operator (=) and
an arithmetic operator (+ , - , * , / , %).
Syntax
Variable Op = Expression
which is equivalent to
Variable = Variable Op Expression
where Op is can be + , - , * , / , %
Example
Enter a number: 6
6! = 120
Edit the previous program so that it will produce this
output
Write a program that will input two numbers. The
first number will be the base and the second number
the exponent.
The program will display the base^exponent of the
number entered.
Note: Your program must not contain Math.pow().
import java.util.*;
public class Sample {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int sum=0,number;
System.out.print("How many numbers you want to ADD? ");
int x = input.nextInt();
while(x>0){
System.out.print("Enter a number: ");
number= input.nextInt();
sum=sum+number;
x--;
}
System.out.println("The sum of the numbers is:" + sum);
}}
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to signify
the end of the loop. Such a value is known as a sentinel
value.
159
import java.util.Scanner;
163
import java.util.Scanner;
if (guess == number)
System.out.println("Yes, the number is " + number);
else if (guess > number)
System.out.println("Your guess is too high");
else
System.out.println("Your guess is too low");
} // End of loop
}
}
Problem: An Advanced Math Learning Tool
165
import java.util.Scanner;
public class SubtractionQuizLoop {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5; // Number of questions
int correctCount = 0; // Count the number of correct answers
int count = 0; // Count the number of questions
long startTime = System.currentTimeMillis();
String output = ""; // output string is initially empty
Scanner input = new Scanner(System.in);
168
import java.util.Scanner;
170
import java.util.Scanner;
public class Sample {
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
for(int i =0; i<2;i++){
for(int j=0; j<3;j++)
System.out.print("*");
System.out.println();
}
}}
OUTPUT
0<2 True
(1) (2)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
0<3 True
(3) (4)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
(5) (6)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
1<3 True
(7) (8)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
2<3 True
(9) (10)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
(11) (12)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
3<3 False
(13) (14)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
1<2 True
(15) (16)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
0<3 True
(17) (18)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
(19) (20)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
1<3 True
(21) (22)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
(23) (24)
2<3 True
(31)
for(int i =0; i<2;i++){
for(int j=0; j<3;j++)
System.out.print("*");
System.out.println();
}
Next Statement
public class MultiplicationTable {
/** Main method */
public static void main(String[] args) {
// Display the table heading
System.out.println(" Multiplication Table");
System.out.println("\n-----------------------------------------");