You are on page 1of 289

Java Programming Language

History of Java

Java The Complete Reference 8th Ed


Why Java?
The answer is that Java enables users to develop and
deploy applications on the Internet for servers, desktop
computers, and small hand-held devices. The future of
computing is being profoundly influenced by the Internet,
and Java promises to remain a big part of that future. Java
is the Internet programming language.

Java is a general purpose programming language.


Java is the Internet programming language.

3
Java, Web, and Beyond
• Java can be used to develop Web
applications.
• Java Applets
• Java Web Applications
• Java can also be used to develop
applications for hand-held devices such as
Palm and cell phones

4
https://www.invensis.net/blog/applications-java-p
ogramming-language/
https://spectrum.ieee.org/the-top-programming-languages-2023#toggle-gdpr
http://www.tiobe.com/tiobe-index/
What will you need to create a java program

Text editor - is a text editor program designed specifically


for editing source code of computer programs by
programmers

Compiler – is a program that translates a program written


in a high-level language, into a program simpler language
that the computer can more or less directly understand

Integrated Development Environment (IDE) - is a software


application that provides comprehensive facilities to
computer programmers for software development. An IDE
normally consists of a source code editor, build
automation tools and a debugger.
Creating and Editing Using NotePad
To use NotePad, type
notepad Welcome.java
from the DOS prompt.

11
Creating and Editing Using WordPad
To use WordPad, type
write Welcome.java
from the DOS prompt.

12
Creating, Compiling, and Running Programs

Create/Modify Source Code

Source code (developed by the programmer)


Saved on the disk
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!"); Source Code
}
}

Compile Source Code


Byte code (generated by the compiler for JVM i.e., javac Welcome.java
to read and interpret, not for you to understand)

Method Welcome() If compilation errors
0 aload_0 stored on the disk

Bytecode
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
5 invokevirtual #4 …
8 return Run Byteode
i.e., java Welcome

Result

13
If runtime errors or incorrect result
animation

Trace a Program Execution


Enter main method

//This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

15
animation

Trace a Program Execution


Execute statement

//This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

16
animation

Trace a Program Execution

//This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

print a message to the


console

17
How to compile in java :

Compiling using IDE

https://netbeans.org/kb/docs/java/quickstart.html

Compiling in CLI (Command Line Interface)


http://docs.oracle.com/javase/tutorial/getStarted/cupojava/win32.html
Kinds of Program Error

Syntax Error – result error in code construction, such as


mistyping a keyword, omitting some necessary
punctuation or using an opening brace without a
corresponding close brace.

Run Time Error – are errors that cause a program to


terminate abnormally when the environment detects
an operation that is impossible to carry out.

Logic Error – occurs when a program does not perform


the way it was intended to.
Programming Errors
• Syntax Errors
– Detected by the compiler
• Runtime Errors
– Causes the program to abort
• Logic Errors
– Produces incorrect result

20
Layout of a Simple Java Program

import <name_of_package>;

public class <name_of_class> {


public static void main(String[] arg){
variable declarations;
………………………….
statements_1;
statements_2;
…………………………..
}
}
Sample Java Program
import java.util.Scanner;

public class FirstProgram{


public static void main(String[] arg){
Scanner input = new Scanner(System.in);
int n1,n2;
System.out.println("Enter two numbers:");
n1 = input.nextInt();
n2 = input.nextInt();
System.out.print("The sum of the two numbers is " );
System.out.println(n1+n2);
}
} Output:
Elements of a Java Program
import java.util.Scanner
import - tells the compiler to the Scanner class from the
package(library) java.util

public class FirstProgram


public – means that methods/fields of the class can be access
by other classes.
class - is a blueprint for the attributes and behaviours of a
group of objects.
Firstprogram – is the name of the class

public static void main (String[] args) –


public – means that this method can be called from outside
the instances of the class.
static – Indicates that a variable or method belongs to a class,
rather than to any object created from the class.
void(none) - the method does not return anything significant
at the end of its execution.
main – it says that the main method of the program starts
here.

{ } – mark the beginning and end of the main class or method.


Output Statement
System.out.println();
System.out – is an object used to send output to the screen
println – is the method of the object that send what’s within its
parenthesis to the screen

Anything inside the double quote is printed exactly as given when the
program is run.
Ex. System.out.println(“Hello World”);
When a variable name appear inside the parenthesis after println and not in
double quote the content of the variable is printed.
Ex. System.out.println(sum);

SYNTAX
System.out.println(Item_1 + Item_2 + ... + Last_Item);
EXAMPLE
System.out.println("Welcome to Java.");
System.out.println(“The sum of two numbers is = " +
(firstnumber+secondnumber);
Sample Program #1

public class FirstProgram{


public static void main(String[] arg){
System.out.println(“Hello World”);
}
}

Output:

Hello World
Sample Program #2
public class word{
public static void main(String[] args){
System.out.println(" J A V V A ");
System.out.println(" J A A V V A A ");
System.out.println(" J J A A A V V A A A ");
System.out.println(" J J A A V A A ");
}
}

Lab Activity 1:

Write your full names using only four System.out.println()


statement
Escape Sequences for Special
Characters

28
Program Output

public class Sample {


public static void main(String[] arg){
System.out.println("Hello World");
}}

public class Sample {


public static void main(String[] arg){
System.out.println("Hello\nWorld");
}}

public class Sample {


public static void main(String[] arg){
System.out.print("Hello");
System.out.print("World");
}}

public class Sample {


public static void main(String[] arg){
System.out.println("Hello");
System.out.print("World");
}}

public class Sample {


public static void main(String[] arg){
System.out.println("Hello\tWorld");
System.out.println("Hello\rWorld");
}}
Variable Names / Identifiers
Variables - are used to store values to be used later in a program
ex. n1,n2 and sum

Identifiers - are used for naming variables, constants, methods, classes, and
packages
ex. main, input, n1,n2, and sum

Rules in naming identifiers and variables


- must start with a letter, an underscore (_), or a dollar sign ($). It
cannot start with a digit.
- you must not used keywords (reserve words).
Ex. double, float, class, etc…
- java is case-sensitive that it distinguishes upper-case and lower case
Variable Declaration
Variable declaration - creates a location in the computer’s memory where a
value can be stored for use later in a program. In declaring multiple variables you
can use commas to separate them.
Syntax:
Single variable declaration
data_type variable_name;
ex. int number;
Multiple variable declaration
data_type variable_name1, variable_name2,…;
ex. double number1, number2, sum;

Initializing variables
Syntax:
Single variable declaration
data_type variable_name = expression;
ex. int number = 3;
Multiple variable declaration
data_type variable_name1, variable_name2,…;
ex. double number1 =3, number2=4 , sum=0;
Determine whether statement is a valid variable Write Valid if the statement is a valid
declaration. variable declaration and if the it is
invalid give the reason why it is not a
valid variable declaration.
int x;

float double;

int _abc;

double 1num;

Int $abc;

double abc-def;
Assignment Statement
Assignment Statement is a way to change the value of a variable. In java, the
used equal sign as an assignment operator. An assignment statement always
consists of a variable on the left-hand side of the assignment operator (the
equal sign) and an expression on the right-hand side. An assignment
statement ends with a semicolon. The expression on the right-hand side of
the equal sign may be a variable, a number, or a more complicated expression
made up of variables, numbers, operators, and method invocations. An
assignment statement instructs the computer to evaluate (that is, to compute
the value of) the expression on the right-hand side of the equal sign and to set
the value of the variable on the left-hand side equal to the value of that
expression.

SYNTAX
Variable = Expression;

EXAMPLE
distance = rate * time;
count = count + 2;
Data Types
animation

Trace a Program Execution


public class ComputeArea { allocate memory
/** Main method */ for radius
public static void main(String[] args) {
double radius; radius no value
double area;

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius
"+
radius + " is " + area);
}
}

35
animation

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius no value
double area; area no value

// Assign a radius
radius = 20;
allocate memory
// Compute area for area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius
"+
radius + " is " + area);
}
}

36
animation

Trace a Program Execution


public class ComputeArea { assign 20 to radius
/** Main method */
public static void main(String[] args) {
double radius; radius 20
double area;
area no value
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius
"+
radius + " is " + area);
}
}

37
animation

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area;
area 1256.636
// Assign a radius
radius = 20;

// Compute area compute area and assign


area = radius * radius * 3.14159; it to variable area

// Display results
System.out.println("The area for the circle of radius
"+
radius + " is " + area);
}
}

38
animation

Trace a Program Execution


public class ComputeArea {
memory
/** Main method */
public static void main(String[] args) {
radius 20
double radius;
double area; area 1256.636

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
System.out.println("The area for the circle of radius
"+
radius + " is " + area);
}
}

39
Concatenation

Plus sign is an operator to concatenate (connect) two strings.


However, if the variable is not a string. If one of the two
operands to + is a string, Java will convert the other operand,
such as the value of variable , to a string.

Ex. System.out.println(“The sum of two numbers is” +


(num1+num2);

The first plus sign is used to concatenate the first string (the
sum of two numbers is) to the sum of num1 and num2.
Program Output

public class Sample{


public static void main(String[] arguments) {
char ch1,ch2,ch3,ch4;
ch1 = 'a';
ch2 = 'b';
ch3 = ' ';
ch4 = '%';
System.out.println("characters are " + ch1 + ch2 + ch3 + ch4 );
System.out.println("characters are " + ch4 + ch3 + ch2 + ch1 );
}
}
public class Sample {
public static void main(String[] arguments)
{
int a , b = 0;
a = 4;
System.out.println("a = " + a + " b = " + b );
b = 7;
System.out.println("a = " + a + " b = " + b );
a = b;
System.out.println("a = " + a + " b = " + b );
b = a;
System.out.println("a = " + a + " b = " + b );
a = 5;
System.out.println("a = " + a + " b = " + b );
}
}
public class string1 {
public static void main(String[] arguments) {
String name = “Yuri";
System.out.println("my name is " + name );
}}
public class Sample {
public static void main(String[] arg){
int number=1;
System.out.println("number");
System.out.println(number);
}}
public class Sample {
public static void main(String[] arguments) {
int a;
double b = 0.0;
a = 4;
System.out.println("a = " + a + " b = " + b );
b = 7;
System.out.println("a = " + a + " b = " + b );
a = (int) b;
System.out.println("a = " + a + " b = " + b );
b = a;
System.out.println("a = " + a + " b = " + b );
a = 5;
System.out.println("a = " + a + " b = " + b );
}}
Naming Conventions
• Choose meaningful and descriptive names.
• Variables and method names:
– Use lowercase. If the name consists of several
words, concatenate all in one, use lowercase for the
first word, and capitalize the first letter of each
subsequent word in the name. For example, the
variables radius and area, and the method
computeArea.

43
Naming Conventions, cont.
• Class names:
– Capitalize the first letter of each word in
the name. For example, the class name
ComputeArea.

• Constants:
– Capitalize all letters in constants, and use
underscores to connect words. For
example, the constant PI and
MAX_VALUE

44
Proper Indentation and Spacing
• Indentation
– Indent two spaces.

• Spacing
– Use blank line to separate segments of the code.

45
Block Styles
Use end-of-line style for braces.

Next-line public class Test


style {
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}

End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}

46
Arithmetic Operations
Precedence of Arithmetic Operator

Sample Expression Output

System.out.println(5+4-3*2/1); 3
System.out.println(5-4+6/2*1); 4
System.out.println((5+(4-3))*(2/1)); 12
System.out.println(5%3+(4/2*1)); 4
Arithmetic and Java Expression

𝟐
Algebra: Area = 𝝅 𝒓
Java: Area = 3.1416*r*r ;

Algebra: c=
Java: c = Math.sqrt(a*a-b*b);

Algebra: opposite = hypotenuse·sin(ɵ)


Java: opposite = (Math.sin(*3.1416/180))
Write the equivalent java statement of the following arithmetic expression

volume_of_sphere =
4.0/3.0*Math.pi*r*r*r;

root = ((-b)+ Math.sqrt(b*b-4*a*c))/(2*a)


a=

a = Math.sqrt(b*b+c*c-2*b*c*Math.cos(angle*Math.PI/180);
1. Write a program that convert a temperature in
Degree Celsius to Degree Fahrenheit. Given
temperature = 37°.

F=

public class CeltoFah {


public static void main(String args[]) {
double temperature=37;
double fahrenheit = (9.0*temperature/5.0)+32;
System.out.println(temperature+" ° celsius is
"+fahrenheit+"° fahrenheit");
}
}
2. Write a program that swap the content of two
numbers.

public class Swap{


public static void main(String[] arg){
double num1= 100;
double num2= 200;
System.out.println(" Before Swapping");
System.out.println(" Num1 = "+ num1);
System.out.println(" Num2 = "+ num2);
num1 = num1 +num2;
num2 = num1 - num2;
num1 = num1 - num2 ;
System.out.println(" After Swapping");
System.out.println(" Num1 = "+ num1);
System.out.println(" Num2 = "+ num2);
}}
1. Write a program that get the volume of a
sphere. Given the radius=10.

2. Write a program that will get the roots of a


quadratic equation. Given the value of a=1, b=4
and c=4.

3. Write a program determine the value of “a” in


a triangle. Given two adjacent sides “b=26” and
“c=19”, and an included angle “A=42°”.
Formatting Numbers
double n1=1234.5678; Output
System.out.println(n1); 1234.5678
System.out.printf("%.1e\n",n1); 1.2e+03
System.out.printf("%.1f\n",n1); 1234.6
System.out.printf("%.1g\n",n1); 1e+03
System.out.printf("%.2e\n",n1); 1.23e+03
System.out.printf("%.2f\n",n1); 1234.57
System.out.printf("%.2g\n",n1); 1.2e+03
System.out.printf("%.3e\n",n1); 1.235e+03
System.out.printf("%.3f\n",n1); 1234.568
System.out.printf("%.3g\n",n1); 1.23e+03
System.out.printf("%.4e\n",n1); 1.2346e+03
System.out.printf("%.4f\n",n1); 1234.5678
System.out.printf("%.4g\n",n1); 1235
System.out.printf("%.5e\n",n1); 1.23457e+03
System.out.printf("%.5f\n",n1); 1234.56780
System.out.printf("%.5g\n",n1); 1234.6
Sample Java Program
import java.util.Scanner;

public class FirstProgram{


public static void main(String[] arg){
System.out.println("Enter two numbers:");
int n1,n2;
Scanner input = new Scanner(System.in);
n1 = input.nextInt();
n2 = input.nextInt();
System.out.print("The sum of the two numbers is " );
System.out.println(n1+n2);
}
} Output:
Input Statement using Scanner
import java.util.Scanner;
The Scanner class can be used to obtain input from files as well as from
the keyboard.

Scanner input = new Scanner(System.in);


Scanner - enables a program to read data (e.g., numbers and strings)
for use in a program
= - indicates that the Scanner variable should be initialize in its
declaration with the result of the expression to the right of the equals sign—
new Scanner(System.in)
new - create a Scanner object (input) that reads characters typed by the
user at the keyboard
System.in – a standard input object enables applications to read bytes
of information typed by the user

n1= input.nextInt();
nextInt is method that reads one int value typed on the keyboard.
Aside form the method nextInt() you can also use the
methods next(), nextByte(), nextShort(), nextLong(),
nextFloat(), nextDouble(), or nextBoolean() to obtain
to a string, byte, short, int, long, float, double, or
boolean value. For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();

57
Program Example 1

import java.util.Scanner;
public class AreaCircle{
public static void main(String[] args){
double pi=3.1416;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number for radius");
double radius = input.nextDouble();
double area = radius * radius * pi;
System.out.println("The area for circle of the radius " + radius + " is " +
area);
}
}

Enter a number for radius


10
The area for circle of the radius 10.0 is 314.16
Program Example 2

import java.util.Scanner;
public class AreaRectangle{
public static void main(String[] args){
double length=0, width=0, area=0;
Scanner input = new Scanner(System.in);
System.out.println("Enter the length and width");
length = input.nextDouble();
width = input.nextDouble();
area = length * width;
System.out.println("The area of the rectangle is” + area);
}
}

Enter the length and width


52
The area of the rectangle is 10
Application for CE
Write a program that will input two forces and two angle. The
program should display the value of the magnitude and direction of
the resultant force.
import java.util.Scanner;
public class Civil {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double force1, force2, angle1, angle2;
double magnitude, direction;
System.out.println("Enter force1 and angle1");
force1 = input.nextDouble();
angle1 = input.nextDouble();
System.out.println("Enter force2 and angle2");
force2 = input.nextDouble();
angle2 = input.nextDouble();
double sumofx=(force1*Math.sin(angle1*Math.PI/180)-force2*Math.cos(angle2*Math.PI/180));
double sumofy=(force1*Math.cos(angle1*Math.PI/180)+force2*Math.sin(angle2*Math.PI/180));
magnitude=Math.sqrt(Math.pow(sumofx,2)+Math.pow(sumofy,2));
direction = (Math.atan(sumofy/sumofx))*180/Math.PI;
System.out.println("The magnitude is: " + magnitude);
System.out.println("The direction is: " + direction);
}
}
Application for EE/ECE

Write a program that will input the values of each resistor in


the given circuit and display the total resistance of the it.

Series Rt = R1+R2+R3

Parallel
import java.util.Scanner;
public class Electrical {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double r1,r2, r3,r4, r5, r6;
double totalresistance;
System.out.println("Enter the value of each resitor:");
r1=input.nextDouble();
r2=input.nextDouble();
r3=input.nextDouble();
r4=input.nextDouble();
r5=input.nextDouble();
r6=input.nextDouble();
totalresistance = r1+r2+((r4+r5+r6)*r3)/(r3+r4+r5+r6);
System.out.println("The total resistance is: "+ totalresistance);

}
}
More Sample for ME
import java.util.Scanner;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double density,height, pressure;
System.out.print("Enter the density of the water: ");
density = input.nextDouble();
System.out.print("Enter the height of the cylindrical tank: ");
height = input.nextDouble();
pressure=density*height/144.0;
System.out.println("The pressure at the bottom of the tank is: "+pressure);
}
}
More Sample for IE

Write a program that lets the user enter the


interest rate, number of years, and loan
amount and computes monthly payment
and total payment.

loanAmount  monthlyInt erestRate


monthlyPayment 
1 1
numberOfYe ars12
(1  monthlyInt erestRate )

66
import java.util.Scanner;

public class ComputeLoan {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter yearly interest rate, for example 8.25: ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = annualInterestRate / 1200;
System.out.print( “Enter number of years as an integer, for example 5: ");
int numberOfYears = input.nextInt();
System.out.print("Enter loan amount, for example 120000.95: ");
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 /
Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
double totalPayment = monthlyPayment * numberOfYears * 12;
System.out.println("The monthly payment is " + monthlyPayment);
System.out.println("The total payment is " + totalPayment);
}
}
Application of Modulus(%)

Write a program that will input a 3 digit number and display the digits together with
their digit location.
import java.util.Scanner;
public class data{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.print("Enter a 3-digit number: ");
int number = input.nextInt();
int hdreds = number/100;
int tens = (number-hdred*100)/10;
int ones = (number-hdred*100 – tens*10);
System.out.println("the hundreds digit is " + hdreds);
System.out.println("the tens digit is " + tens);
System.out.println("the ones digit is " + ones);
}
}
import java.util.Scanner;
public class data{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.print("Enter a 3-digit number: ");
int number = input.nextInt();
int ones = number%10;
int tens = number/10%10;
int hdreds = number/100;
System.out.println("the hundreds digit is " + hdreds);
System.out.println("the tens digit is " + tens);
System.out.println("the ones digit is " + ones);
}
}
Write a program that will input hours and display its
equivalent in Years, Days and Hours.

Sample Output:

import java.util.Scanner;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter hours: ");
int hours = input.nextInt();
int years = hours/8766;
int yearsremain = hours%(8766);
int days = yearsremain/24;
int daysremain = yearsremain%(24);
System.out.println("There are " + years + " years, " + days + " days and " +
daysremain + " hours in " + hours + " hours");
}
}
import java.util.Scanner;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter hours: ");
int hours = input.nextInt();
int years = hours/8766;
int yearsremain = hours%(8766);
int days = yearsremain/24;
int daysremain = yearsremain%(24);
System.out.println("There are " + years + " years, " + days + "
days and " + daysremain + " hours in " + hours + " hours");
}
}
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);

System.out.println("The largest number is" +


System.out.println("The larger number is " + big);
System.out.println("The smaller number is " + small);
}
}
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

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

103
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.
import java.util.Scanner;
public class highest {
public static void main(String[] args){
Scanner input = new Scanner(System.in); if(num3>largest){
int largest = -999999; largest = num3;
System.out.println(); }
System.out.print("Enter 5 numbers:"); if(num4>largest){
int num1 = input.nextInt(); largest = num4;
int num2 = input.nextInt(); }
int num3 = input.nextInt(); if(num5>largest){
int num4 = input.nextInt(); largest = num5;
int num5 = input.nextInt(); }
if(num1>largest){ System.out.println("The largest number is "+
largest = num1; largest);
} }
if(num2>largest){ }
largest = num2;
}
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 false case
} Statement(s) for the true 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';

121
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';

122
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';

123
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';

124
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';

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

126
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.

127
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.

128
TIP
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)

129
CAUTION

Equivalent if (even)
if (even == true)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)

130
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.

137
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

139
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+


141
Sample output

Enter Your Status:


0 - for single
1 - married file jointly
2 - married file separately
3 - head of household

Your Status: 0
Enter your salary: 8000

Your salary 8000


Your tax is 800
You’ll receive 7200
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
}
143
Problem: Computing Taxes, cont.
if (status == 0) {
if(salary<8350){
.. .. .. .. ..
}else if(salary<33950){
.. .. .. .. ..
}else if(salary<82250){
.. .. .. .. ..
}else if(salary<171550){
.. .. .. .. ..
}
}else if(status == 1){
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

146
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

147
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.

148
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

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

155
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);
}
158
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

159
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.

160
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the end
case value1: statement(s)1;
of each case in order to
terminate the remainder of the break;
switch statement. If the break case value2: statement(s)2;
statement is not present, the
next case statement will be break;
executed. …
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.

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

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

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

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

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

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

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

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

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

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

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

172
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!");
176
Introducing while Loops
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}

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

178
animation

Trace while Loop


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

179
animation

Trace while Loop, cont.


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

180
animation

Trace while Loop, cont.

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

181
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

182
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++;
}

183
animation

Trace while Loop, cont.

int count = 0; Print Welcome to Java

while (count < 2) {


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

184
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

185
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++;
}

186
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++;
}

187
do-while Loop

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

true Loop
Continuation
Condition?

false

188
animation

Trace while Loop


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

189
animation

Trace while Loop, cont.

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

190
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

191
animation

Trace while Loop, cont.

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

(count < 2) is true

192
animation

Trace while Loop, cont.

int count = 0; Print Welcome to Java

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

193
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

194
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

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

196
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)
197
animation

Trace for Loop


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

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

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

200
animation

Trace for Loop, cont.


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

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

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

203
animation

Trace for Loop, cont.


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

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

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

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

207
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

}
208
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)

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

210
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

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

212
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.

213
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! = 720
6!=6*5*4*3*2*1
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.

232
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("Yes".equals(x) || "yes".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);
}}
Edit slide the program on slides
231,233 and 234. To display average
and largest number.
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:

236
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.

238
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.

241
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

243
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();
} }
(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
Edit Slide 244 by replacing for-for by
dowhile-dowhile.
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();
}
}
}
Chapter 5 Methods

262
Opening Problem

Find the sum of integers from 1 to 10, from 20 to 30, and


from 35 to 45, respectively.

263
Problem

int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);

264
Problem

int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);

265
Solution
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}

public static void main(String[] args) {


System.out.println("Sum from 1 to 10 is " + sum(1, 10));
System.out.println("Sum from 20 to 30 is " + sum(20, 30));
System.out.println("Sum from 35 to 45 is " + sum(35, 45));
}

266
Defining Methods

A method is a collection of statements that are


grouped together to perform an operation.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

267
Method Signature

Method signature is the combination of the method name and the


parameter list.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

268
Formal Parameters

The variables defined in the method header are known as


formal parameters.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

269
Actual Parameters

When a method is invoked, you pass a value to the parameter. This


value is referred to as actual parameter or argument.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

270
Return Value Type
A method may return a value. The returnValueType is the data type
of the value the method returns. If the method does not return a
value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

271
animation

Calling Methods, cont.

pass the value of i


pass the value of j

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

272
animation

Trace Method Invocation


i is now 5

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

273
animation

Trace Method Invocation


j is now 2

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

274
animation

Trace Method Invocation


invoke max(i, j)

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

275
animation

Trace Method Invocation


invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

276
animation

Trace Method Invocation


declare variable result

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

277
animation

Trace Method Invocation


(num1 > num2) is true since num1
is 5 and num2 is 2

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

278
animation

Trace Method Invocation


result is now 5

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

279
animation

Trace Method Invocation


return result, which is 5

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

280
Write a program that will ask how many data
will be entered and display the standard
deviation of the entered data.
Factorial
Sum of 1 to N
•public class ReverseNumber {

• public static void main(String[] args) {

• //original number
• int number = 1234;
• int reversedNumber = 0;
• int temp = 0;

• while(number > 0){

• //use modulus operator to strip off the last digit
• temp = number%10;

• //create the reversed number
• reversedNumber = reversedNumber * 10 + temp;
• number = number/10;

• }

• //output the reversed number
• System.out.println("Reversed Number is: " + reversedNumber);
• }
•}
import java.util.*;
public class Sample {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int z=0,number,x=1,y=0;
System.out.print("enter a number");
number= input.nextInt();
do{
z=y+x;
x=x+y;
Lab Activity System.out.print(z) ;
Factors y++;
1x12=12 }while(y<number);
2X6=12 }}
base

Fibonacci
Cells
And investment

You might also like