Sie sind auf Seite 1von 188

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

1. Start import java.util.Scanner;


2. Set sum=0 public class Sample{
3. Get the first number public static void main(String[] args){
4. Get the second number Scanner input = new Scanner(System.in);
5. Add the first number and the second double sum=0;
number and save it to sum System.out.println(“Enter two numbers”);
6. Output the sum double n1 = input.nextDouble();
7. Stop double n2= input.nextDouble();
sum = n1+n2;
System.out.println(sum);
}
}
Pseudocode
Pseudocode is one of the tools that can be used to write a
preliminary plan that can be developed into a computer program.
Pseudocode is a generic way of describing an algorithm without use
of any specific programming language syntax. It is, as the name
suggests, pseudo code —it cannot be executed on a real computer,
but it models and resembles real programming code, and is written
at roughly the same level of detail.

Example

Pseudocode for Adding Three Numbers


1. Use variables: sum, number1, number2, number3 of type
integer
2. Accept number1, number2, number3
3. Sum = number1 + number2 + number3
4. Print sum
5. End program
A Flowchart is a type of diagram (graphical or symbolic)
that represents an algorithm or process. Each step in the
process is represented by a different symbol and contains a
short description of the process step. The flow chart symbols
are linked together with arrows showing the process flow
direction.
A flowchart typically shows the flow of data in a process,
detailing the operations/steps in a pictorial format which is
easier to understand than reading it in a textual format.
Lab Activity 2

1. Write an algorithm/pseudocode and a java program that


will allow to input three numbers and display the sum of
the average of the three numbers.
2. Write an algorithm/ pseudocode and a java program that
input temperature in degree Celsius and display the
equivalent temperature in degree Fahrenheit.
Example of a flowchart.

Write (Display) the Sum, Average and Product


Advantages of using flowcharts
Flowchart Symbols & Guidelines:
The flowchart of the algorithm
import java.util.Scanner;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int big,small;
System.out.println("Enter the value of A and B:");
int A = input.nextInt();
int B = input.nextInt();
if(A<B){
big = B;
small = A;
}else{
big = A;
small = B;
}
System.out.println("The larger number is " + big);
System.out.println("The smaller number is " + small);
}
}
import java.util.Scanner;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int a,b,c;
System.out.println("Enter the value of A, B & C");
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();

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

Display Try Another


Number

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

It is used to select a certain set of instructions. It is used to decide


whether this set is to be carried out, based on the condition in the
parenthesis. Its syntax is:
if (<boolean expression>){ Boolean
false false
(radius >= 0)
Expression
//body starts
true true

<statement(s)> Statement(s) area = radius * radius * PI;


System.out.println("The area for the circle of " +
"radius " + radius + " is " + area);
//body ends
} (A) (B)

The <boolean expression> is evaluated first. If its value is true,


then the statement(s) are executed. And then the rest of the
program. Refer if_cond.java, if_cond1.java

03 August 2004 nlp-ai@cse.iitb


Note

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

It is used to provide an alternative when the expression in if


is false. Its syntax is:
if(<boolean expression>){
<statement(s)>
}
else{ true
Boolean
false
Expression
<statement(s)>
Statement(s) for the true case Statement(s) for the false case
}

The if else construct is the same. But when the expression


inside if is false then else part is executed.
Write a program that will input a number and display whether
the number is positive or negative?
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");
}else {
System.out.println(“Negative");
}
}
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");
}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("#####");
}}

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("#####");
}
}}
Program Output

public class sample{


public static void main(String[] arg){
int a = 1, b=2;
if (a>b)
System.out.println("*****");
else
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("*****");
else
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("^^^^^");
else
System.out.println("#####");
System.out.println("&&&&&");
}}
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("^^^^^");
}else{
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("^^^^^");
}else{
System.out.println("#####");
System.out.println("&&&&&");
}
}
}
Nested if Statements #1

Including one or more


if statements inside an
existing if statement is
called a nested if statement.
import java.util.Scanner;
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
if(number>=0)
if(number%2==0)
System.out.print("The number is positive and even");
}}
import java.util.Scanner;
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
if(number>=0)
if(number%2==0)
System.out.print("The number is positive and even");
else
System.out.print("The number is positive and odd");
}
}
import java.util.Scanner;
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
if(number>=0)
if(number%2==0)
System.out.print("The number is positive and even");
else
System.out.print("The number is positive and odd");
else
System.out.print("The number is negative");
}
}
Nested if Statements #2

Nested if-else after an else


statement is called nested if-
else
Multiple Alternative if Statements

if (score >= 90.0) if (score >= 90.0)


grade = 'A'; grade = 'A';
else else if (score >= 80.0)
if (score >= 80.0) Equivalent grade = 'B';
grade = 'B'; else if (score >= 70.0)
else grade = 'C';
if (score >= 70.0) else if (score >= 60.0)
grade = 'C'; grade = 'D';
else else
if (score >= 60.0) grade = 'F'; 
grade = 'D';  
else
grade = 'F';
 

49
animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

50
animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

51
animation
Trace if-else statement
Suppose score is 70.0 The condition is true

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

52
animation
Trace if-else statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

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

public class Sample{


public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a>b)
System.out.println("Hello");
if(b<c)
System.out.println("Hi");
}
}

public class Sample{


public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a<b){
System.out.println("Hello");
if(b<c)
System.out.println("Hi");
}
}
}
public class Sample{
public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a<b){
if(b<c)
System.out.println("Hi");
System.out.println("Hello");
}
}
}
Program Output

public class Sample{


public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a<b){
if(b>c)
System.out.println("Hi");
System.out.println("Hello");
}
}}

public class Sample{


public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a>b){
if(b<c)
System.out.println("Hi");
System.out.println("Hello");
}
}
}

public class Sample{


public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a>b){
if(b<c)
System.out.println("Hi");
}
System.out.println("Hello");
}
}
Program Output
public class Sample{
public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a>b)
if(b>c)
System.out.println("Hi");
else
System.out.println("World");
System.out.println(“Hello");
}}

public class Sample{


public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a<b)
if(b<c)
System.out.println("Hi");
else
System.out.println("World");
System.out.println(“Hello");
}}

public class Sample{


public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a>b)
if(b<c)
System.out.println("Hi");
else
System.out.println("World");
System.out.println(“Hello");
}}
Program Output
public class Sample{
public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a<b)
if(b>c)
System.out.println("Hi");
else
System.out.println("World");
System.out.println(“Hello");
}}

public class Sample{


public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a<b)
if(b<c)
System.out.println("Hi");
else
System.out.println("World");
else
System.out.println(“Hello");
}}
public class Sample{
public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a>b)
if(b>c)
System.out.println("Hi");
else
System.out.println("World");
else
System.out.println(“Hello");
}}
Program Output
public class Sample{
public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a>b)
if(b<c)
System.out.println("Hi");
else
System.out.println("World");
else
System.out.println(“Hello");
}}

public class Sample{


public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a<b)
if(b>c)
System.out.println("Hi");
else
System.out.println("World");
else
System.out.println(“Hello");
}}
public class Sample{
public static void main(String[] arg){
int a = 1, b=2, c=3;
if (a<b)
if(b>c)
System.out.println("Hi");
else
System.out.println("World");
else
System.out.println(“Hello");
}}
Program Output
public class Sample{
public static void main(String[] arg){
int a = 1, b=2, c=3;

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;

Ang problemang itoh ay sinadyang lagyan ng error pakiayos nalng…


Problem: An Improved Math Learning Tool
This example creates a program to teach a
first grade child how to learn subtractions.
The program randomly generates two
single-digit integers number1 and number2
with number1 > number2 and displays a
question such as “What is 9 – 2?” to the
student. After the student types the answer,
the program displays a message to indicate
whether the answer is correct.

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

Body Mass Index (BMI) is a measure of health on


weight. It can be calculated by taking your weight in
kilograms and dividing by the square of your height in
meters. The interpretation of BMI for people 16 years or
older is as follows:

BMI Interpretation

below 16 serious underweight


16-18 underweight
18-24 normal weight
24-29 overweight
29-35 seriously overweight
above 35 gravely overweight

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.

Margina Married Filing


Married Filing
l Tax Single Jointly or Qualified Head of Household
Separately
Rate Widow(er)
10% $0 – $8,350 $0 – $16,700 $0 – $8,350 $0 – $11,950

15% $8,351– $33,950 $16,701 – $67,900 $8,351 – $33,950 $11,951 – $45,500

25% $33,951 – $82,250 $67,901 – $137,050 $33,951 – $68,525 $45,501 – $117,450

28% $82,251 – $171,550 $137,051 – $208,850 $68,525 – $104,425 $117,451 – $190,200

33% $171,551 – $372,950 $208,851 – $372,950 $104,426 – $186,475 $190,201 - $372,950

35% $372,951+ $372,951+ $186,476+ $372,951+


69
Problem: Computing Taxes, cont.
if (status == 0) {
// Compute tax for single filers
}
else if (status == 1) {
// Compute tax for married file jointly
}
else if (status == 2) {
// Compute tax for married file separately
}
else if (status == 3) {
// Compute tax for head of household
}
else {
// Display wrong status
}
70
Write a program that input 5 numbers and display
the largest number among the input numbers using
nested if-else statement.
Write a program that will input your grade and determine equivalent.

Grade Eq. Grade


97.5-100
94.5-97.49
1.0
1.25
Enter Grade: 99.99
91.5-94.49 1.5 Your grade is 1.0
88.5-91.49 1.75
85.5-88.49 2.0
82.5-85.49
79.5-82.49
2.25
2.5
Enter Grade: 74.5
76.5-79.49
74.5-46.49
2.75
3.0
Your grade is 3.0
69.5-74.49 4.0
0-69.49 5.0
Enter Grade: 69.49
Your grade is 5.0
Logical Operators
Operator Name
! not
&& and
|| or
^ exclusive or

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");
}
}

Replace && with ||

if(number%2==0||number>0)
System.out.print(“The number is either positive or even or
both");
Problem: Body Mass Index

Body Mass Index (BMI) is a measure of health on


weight. It can be calculated by taking your weight in
kilograms and dividing by the square of your height in
meters. The interpretation of BMI for people 16 years or
older is as follows:

BMI Interpretation

below 16 serious underweight


16-18 underweight
18-24 normal weight
24-29 overweight
29-35 seriously overweight
above 35 gravely overweight

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(“*****");
}}

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(“*****");
}}
public class Sample{
public static void main(String[] arg){
int a = 1, b=2, c=3;
if ((a!=b&&b>c)||(a>b||a<c))
if(b<c&&a<c)
System.out.println(“#####");
else
System.out.println(“%%%%%");
else
System.out.println(“*****");
}}
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");
if (bmi < 18 && bmi >=16)
System.out.println("You are underweight");
if (bmi < 24 && bmi >=18)
System.out.println("You are normal weight");
if (bmi < 29 && bmi >=24)
System.out.println("You are overweight");
if (bmi < 35 && bmi >=29)
System.out.println("You are seriously overweight");
if (bmi>=35)
System.out.println("You are gravely overweight");
}}
Problem #1

Life Stage Age


Infancy 0-2 Years

Childhood 3-9 Years

Early Adolescence 10-14 Years

Late Adolescence 14-19 Years

Young Adult 20-29 Years

Early Adult 30-39 Years

Middle Age 40-60 Years

Late Age 60 + Years


Problem #2
Calendar Problem:

82
Problem #3

Write a program that will input your grade and determine equivalent.

Grade Eq. Grade Enter Grade: 99.99


97.5-100
94.5-97.49
1.0
1.25 Your grade is 1.0
91.5-94.49 1.5
88.5-91.49 1.75
85.5-88.49 2.0 Enter Grade: 74.5
82.5-85.49 2.25
79.5-82.49 2.5 Your grade is 3.0
76.5-79.49 2.75
74.5-46.49 3.0
69.5-74.49
0-69.49
4.0
5.0
Enter Grade: 69.49
Your grade is 5.0
Problem #4
Write a program that input 5 numbers and display
the largest number among the input numbers using
if-statement and logical operators.
Switch case statements are a substitute for long if statements that compare a
variable to several "integral" values ("integral" values are simply values that
can be expressed as an integer, such as the value of a char).

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

Execute this line

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

Execute this line

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

Execute this line

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

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

Execute this line

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

Execute this line

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

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

You want to execute some code/s 100 times.


You want to execute some code/s certain number of
times depending upon input from user.

These types of task can be solved in programming using


loops.

There are 3 types of loops in Java programming:


while loop
for loop
do-while
Opening Problem
Problem:

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

Trace while Loop


Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

106
animation

Trace while Loop, cont.


(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

107
animation

Trace while Loop, cont.

int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Print Welcome to Java

108
animation

Trace while Loop, cont.

int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Increase count by 1
count is 1 now

109
animation

Trace while Loop, cont.


(count < 2) is still
int count = 0; true since count is 1
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

110
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

111
animation

Trace while Loop, cont.

int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1
count is 2 now

112
animation

Trace while Loop, cont.


(count < 2) is
int count = 0; false since count
while (count < 2) { is 2 now
System.out.println("Welcome to Java!");
count++;
}

113
animation

Trace while Loop


The loop exits.
int count = 0; Execute the next
statement after the
while (count < 2) { loop.
System.out.println("Welcome to Java!");
count++;
}

114
do-while Loop

do {
// Loop body; Statement(s)
Statement(s);
(loop body)
} while (loop-continuation-condition);

true Loop
Continuation
Condition?

false

115
animation

Trace while Loop


Initialize count
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;

116
animation

Trace while Loop, cont.

int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;
Print Welcome to Java

117
animation

Trace while Loop, cont.

int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;

Increase count by 1
count is 1 now

118
animation

Trace while Loop, cont.

int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;

(count < 2) is true

119
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2)

120
animation

Trace while Loop, cont.

int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2)
Increase count by 1
count is 2 now

121
animation

Trace while Loop, cont.

int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;

(count < 2) is false


since count is 2

122
animation

Trace while Loop


The loop exits.
int count = 0; Execute the next
statement after the
do{ loop.
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;

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

Trace for Loop


Declare i
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

125
animation

Trace for Loop, cont.


Execute initializer
int i; i is now 0

for (i = 0; i < 2; i++) {


System.out.println("Welcome to Java!");
}

126
animation

Trace for Loop, cont.


(i < 2) is true
int i; since i is 0

for (i = 0; i < 2; i++) {


System.out.println("Welcome to Java!");
}

127
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

128
animation

Trace for Loop, cont.


Execute adjustment statement
i now is 1
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

129
animation

Trace for Loop, cont.


(i < 2) is still true
int i; since i is 1

for (i = 0; i < 2; i++) {


System.out.println("Welcome to Java!");
}

130
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

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

Trace for Loop, cont.


(i < 2) is false
int i; since i is 2

for (i = 0; i < 2; i++) {


System.out.println("Welcome to Java!");
}

133
animation

Trace for Loop, cont.


Exit the loop. Execute the next
int i; statement after the loop

for (i = 0; i < 2; i++) {


System.out.println("Welcome to Java!");
}

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

for (int i = 0, j = 0; (i + j < 10); i++, j++) {


// Do something

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

for ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }  
  (a) (b)
 

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

for (int i=0; i<10; i++);


{
System.out.println("i is " + i);
}

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

while (loop-continuation-condition) { Equivalent for ( ; loop-continuation-condition; )


// Loop body // Loop body
} }
(a) (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++;
}
}}

public class Sample {


public static void main(String[] args) {
int x=1;
do{
System.out.println(x);
x++;
}while(x<=10);
}}

public class Sample {


public static void main(String[] args) {
int x;
for(x=1; x<=10;x++)
System.out.println(x);
}}
public class Sample {
Other Solution public static void main(String[] args) {
int x=1;
while(x!=10){
System.out.println(x);
x++;
}}

public class Sample {


public static void main(String[] args) {
int x=1;
do{
System.out.println(x);
x++;
while(x<11);
}}

public class Sample {


public static void main(String[] args) {
for(int x=1; x<=10;x++)
System.out.println(x);
}}
import java.util.Scanner;
Write a program public class Sample {
that will display the public static void main(String[] args) {
all even numbers int x=2;
From 1-100. while(x<=100){
System.out.println(x);
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: EQUIVALENT TO:


count += 2; count = count + 2;
total -= discount; total = total - discount;
bonus *= 2; bonus = bonus * 2;
time /= rushFactor; time = time / rushFactor;
change %= 100; change = change % 100;
amount *= count1 + count2; amount = amount * (count1 + count2);
import java.util.Scanner;
public class Summation {
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
int sum=0;
System.out.print("Enter a number: ");
int number = input.nextInt();
for(int x=1;x<=number;x++){
sum=sum+x;
}
System.out.print("The sum of 1 to "+number+" is " +sum);
}}

Insert this statement inside the for loop


System.out.println(sum);
Reverse of a number
import java.util.Scanner;
public class Reverse {
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
int remainder=0;
System.out.print("Enter a number");
int number = input.nextInt();
while(number>0){
remainder=number%10;
System.out.print(remainder);
number/=10;
}
}}
Binary to Decimal
import java.util.Scanner;
public class BintoDec {
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
int sum=0,remainder=0, x=0;
System.out.print("Enter a number");
int number = input.nextInt();
while(number>0){
remainder=number%10;
sum=sum+(int)(remainder*(Math.pow(2,x)));
number/=10;
x++;
}
System.out.println(sum);
}}
Write a program
that will display the
First 10 of this number series.
In mathematics, the factorial of a non-negative integer n,
denoted by n!, is the product of all positive integers less than
or equal to n.

Write a program that will input a number and display the


factorial of that number.

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

Enter two numbers: 2 3


2 raised to 3 is 8

Enter two numbers: 3 3


3 raised to 3 is 27
INPUT INSIDE A LOOP

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;

public class SentinelValue {


/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);

// Read an initial data


System.out.print("Enter an int value (the program exits if the input is 0): ");
int data = input.nextInt();

// Keep reading data until the input is 0


int sum = 0;
while (data != 0) {
sum += data;

// Read the next data


System.out.print("Enter an int value (the program exits if the input is 0): ");
data = input.nextInt();
}

System.out.println("The sum is " + sum);


}
}
import java.util.Scanner;
public class Sample {
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
int total=0,number;
System.out.print("Do you want to Enter a Number? \n Press Y ");
String x;
x= input.nextLine();
while("Y".equals(x) || "y".equals(x)){
System.out.print("Enter a number? ");
number=input.nextInt();
total=total+number;
System.out.print("Press Y to enter another number: ");
x= input.next();
}
System.out.print("The sum of the numbers is " +total);
}}
Write a program that will ask how many data
will be entered and display the standard
deviation of the entered data.
Problem: Guessing Numbers
Write a program that randomly generates an integer
between 0 and 100, inclusive. The program prompts
the user to enter a number continuously until the
number matches the randomly generated number. For
each user input, the program tells the user whether
the input is too low or too high, so the user can choose
the next input intelligently. Here is a sample run:

163
import java.util.Scanner;

public class GuessNumber {


public static void main(String[] args) {
// Generate a random number to be guessed
int number = (int)(Math.random() * 101);

Scanner input = new Scanner(System.in);


System.out.println("Guess a magic number between 0 and 100");

int guess = -1;


while (guess != number) {
// Prompt the user to guess the number
System.out.print("\nEnter your guess: ");
guess = input.nextInt();

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

The Math subtraction learning tool program generates


just one question for each run. You can use a loop to
generate questions repeatedly. This example gives a
program that generates five questions and reports the
number of the correct answers after a student answers
all five questions.

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

while (count < NUMBER_OF_QUESTIONS) {


// 1. Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);

// 2. If number1 < number2, swap number1 with number2


if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
// 3. Prompt the student to answer “What is number1 – number2?”
System.out.print("What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();

// 4. Grade the answer and display the result


if (number1 - number2 == answer) {
System.out.println("You are correct!");
correctCount++;
}
else
System.out.println("Your answer is wrong.\n" + number1 + " - " + number2 + " should
be " + (number1 - number2));

// Increase the count


count++;

output += "\n" + number1 + "-" + number2 + "=" + answer +


((number1 - number2 == answer) ? " correct" : " wrong");
}
long endTime = System.currentTimeMillis();
long testTime = endTime - startTime;
System.out.println("Correct count is " + correctCount +
"\nTest time is " + testTime / 1000 + " seconds\n" + output);
}
}
Problem:
Finding the Greatest Common Divisor
Problem: Write a program that prompts the user to enter two positive
integers and finds their greatest common divisor.
Solution: Suppose you enter two integers 4 and 2, their greatest
common divisor is 2. Suppose you enter two integers 16 and 24, their
greatest common divisor is 8. So, how do you find the greatest
common divisor? Let the two input integers be n1 and n2. You know
number 1 is a common divisor, but it may not be the greatest
commons divisor. So you can check whether k (for k = 2, 3, 4, and so
on) is a common divisor for n1 and n2, until k is greater than n1 or n2.

168
import java.util.Scanner;

public class GreatestCommonDivisor {


/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter first integer: ");
int n1 = input.nextInt();
System.out.print("Enter second integer: ");
int n2 = input.nextInt();
int gcd = 1;
int k = 2;
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k;
k++;
}
System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " +
gcd);
}
}
Nested Loops

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

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();
} }
(25) (26)
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();
} }

(27) 3<3 False


(28)
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<2 False
(29) (30)
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();
} }

(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");

// Display the number title


System.out.print(" ");
for (int j = 1; j <= 9; j++)
System.out.print(" " + j);

System.out.println("\n-----------------------------------------");

// 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
System.out.printf("%4d", i * j);
}
System.out.println();
}
}
}
public class Sample {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}

public class Sample {


public static void main(String[] args) {
for (int i = 9; i>0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
public class Sample {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for(int k=9; k>i;k--)
System.out.print(" ");
for (int j = 1; j <= i; j++)
System.out.print("*");
System.out.println();
}
}
}

public class Sample {


public static void main(String[] args) {
for (int i = 9; i>0; i--) {
for (int k = 9; k>i; k--)
System.out.print(" ");
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
public class Sample {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if(i%2==0)
System.out.print("*");
else
System.out.print("#");
}
System.out.println();
}
}
}

public class Sample {


public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if(j%2==0)
System.out.print("*");
else
System.out.print("#");
}
System.out.println();
}
}
}
public class Sample {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if(i==1||j==1||i==9||j==9)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
public class Sample {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if(i==j)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
public class Sample {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if((i+j)==10)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
public class Sample {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if(i>=j)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}

public class Sample {


public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if((i+j)<=10)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
public class Sample {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if((i+j)>=10)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
public class Sample {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if(j>=i)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
public class Sample {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if((i+j)==10||i==9|j==9)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}

public class Sample {


public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if(i==j||j==9|i==1)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}

Das könnte Ihnen auch gefallen