4 Conditional IO Loop
4 Conditional IO Loop
1
Decision Making
Statements
2
Introductio
n
Java compiler executes the code from top to
bottom.
The statements in the code are executed
according to the order in which they
appear.
Statements that can be used
to control the flow of code called
Control Flow Statements.
– These statements provide a smooth flow in
program execution.
3
Types of Control Flow
Statements
• Decision Making
Statements
– if statements
– switch statement
• Loop
Statements
– do while loop
– while loop
– for loop
– for-each
loop
• Jump 4
Decision Making
Statements
• Decide which statement to execute and
when.
• Evaluate the Boolean expression and
control the program flow depending
upon the result of the condition
provided.
• Two types of decision-making
statements in Java:
– if statement 5
Decision Making Statements
… Contd.
‘if’ Statement
• Used to evaluate a condition.
• Control of the program is diverted depending upon the
specific condition.
• Condition of if statement gives a Boolean value, either
true or false.
• Types of ‘if’ statement
– Simple if statement
– if-else statement
– if-else-if ladder
– Nested if statement 6
Decision Making Statements
… Contd.
Simple if statement
• Basic statement among all control flow
statements in Java.
• Evaluates a Boolean expression and enables
the program to enter a block of code if the
expression evaluates to true.
• Syntax of simple if statement
if(condition) {
statement 1; //executes when condition is true
} 7
Decision Making Statements
… Contd.
public class Demo1 {
public static void main(String[] args) {
int x = 10; int y
= 12; if(x>y) {
System.out.print
ln("x is greater
than y");
}
}
} 8
Decision Making Statements
if-else Statement
… Contd.
• Extension to the if-statement, which uses another block
of code, i.e., else block.
• The else block is executed if the condition of the if-
block is evaluated as false.
• Syntax of if-else statement
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
} 9
Decision Making Statements
…
public class Demo2 {
Contd.
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y<10) {
System.out.println("x is lesser than y");
}
else {
System.out.println("x is greater than y");
}
}
}
10
Decision Making Statements
… Contd.
if-else-if Ladder
Contains the if-statement followed by multiple
else-if statements.
It is the chain of if-else statements that create
a decision tree where the program
may enter in the block of code where the
condition is true.
An else statement can be defined at the end of
the chain.
11
Decision Making Statements
… Contd.
Syntax of if-else-if ladder
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 3; //executes when all the conditions are false
}
12
Decision Making Statements
… Contd.
public class Demo3 {
public static void main(String[] args)
{
int i = 20;
// condition 1
if (i == 10)
System.out.println("i is 10\n");
// condition 2
else if (i == 15)
System.out.println("i is 15\n");
// condition 3
else if (i == 20)
System.out.println("i is 20\n");
else {
System.out.println("i is not present\n");
System.out.println("Outside if-else-if");
}
}
13
}
Decision Making Statements
… Contd.
Nested if Statement
• The if statement can contain a if or if-else statement inside
another if or else-if statement.
• Syntax of nested if statement
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 3; //executes when condition 2 is false
}
}
14
Decision Making Statements
… Contd.
public class Demo4 {
public static void main(String[] args)
{
int x = 30;
int y = 10;
if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y
= 10");
}
}
} 15
Decision Making Statements
… Contd.
switch Statement
• Similar to if-else-if statements.
– Contains multiple blocks of code called cases and a single case is
executed based on the variable which is being switched.
– Easy to use instead of if-else-if statements.
– Enhances the readability of the program.
• The case variables can be int, short, byte, char, or enumeration.
String type is also supported since version 7 of Java.
• Default statement is executed when any of the case doesn't match the value of
expression.
It is optional.
• break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
• While using switch statements, the case expression will be of the same type as
the variable.
It will also be a constant value. 16
Decision Making Statements
… Contd.
Syntax of switch statement
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default
statement;
}
17
Decision Making Statements
… Contd.
public class Demo5 {
public static void main(String[] args) {
int num = 1;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
18
Practice
Programs
1) Write a Java program that checks if a given number is positive. If it
is positive, print "Positive number," otherwise, print "Negative
number.“
2) Write a Java program that determines whether a given number is
even or odd. Print "Even" if it's even, and "Odd" if it's odd.
3) Write a Java program to determine the grade of a student based on
the marks obtained. The grading system is as follows:
1) 90 and above: "A"
2) 80-89: "B"
3) 70-79: "C"
4) Below 70: "Fail“
4) Write a Java program that uses a switch statement to print the name
of the day of the week based on a given number (1-7). 19
Practice Programs
5. Write a Java program that determines the shipping cost
based on the weight of a package and the destination zone.
The cost is calculated as follows:
5. Weight less than or equal to 2 kg: $5 per kg
6. Weight between 2 kg (exclusive) and 5 kg (inclusive): $4 per kg
7. Weight between 5 kg (exclusive) and 10 kg (inclusive): $3 per
kg
8. Weight above 10 kg: $2 per kg
The destination zones are represented by integers:
9. Zone 1: Domestic
10. Zone 2: International
Print the shipping cost for a given weight and destination zone.
20
Java Input / Output
21
Java Input / Output
25
Java Input / Output
• // 1. Create a Scanner using the InputStream available.
Scanner scanner = new Scanner( System.in );
• // 4. Now, you can do anything with the input string that you
need to.
• // Like, output it to the user.
System.out.println( "input = " + input );
26
Java Input / Output
• Integer input:
• Here's one way to do this:
• Get a String of characters that is in an integer format, e.g., "123".
• String input = scanner.nextLine(); // from console input example
above.
• Use the Integer class to parse the string of characters into an integer.
• int number = Integer.parseInt( input ); // converts a String into an
int value
• The Integer class contains conversion methods for changing String data
into int values and vice versa. The Integer class is one of several
wrapper classes that are defined in the standard Java API. Wrapper
classes have class methods for parsing and are also used when you
need to store a primitive value as an object. 27
Java Input / Output
• Integer input:
• Here's another way to do this:
• Read the next available input as an int value.
• int number = scanner.nextInt(); // from console
input example above.
• As you can see, the Scanner class contains a
method named nextInt that returns the next input
data available as an int value, that is, if the next
input in the input stream is a valid integer format.
If the next input is not a valid integer format, an
InputMismatchException is thrown.
28
Java Input / Output
• Console Output:
• We have used System.out.print(...) and System.out.println(...)
statements for displaying simple text messages to the user.
• This is an important output alternative, since graphic user interface
(GUI) objects are not readily available in some programming
environments.
• You may of course write your own GUI classes if they're not
available, but that is beyond the scope of this course.
• It is much more likely that you will simply use the available output
options of the programming environment that you are working in.
• Most programming languages have the ability to display a string of
characters to the screen or some other standard display device. We
call this console output because the string of characters appears in a
console window. The System.out object is an instance of the
PrintStream class, which is a type of OutputStream.
29
Keyboard
//Integer Input Input
import java.util.Scanner;
public class KeyInputDemo {
public static void main(String args[])
{
int a;
Scanner s = new Scanner(System.in);
System.out.println("Enter an integer:");
a=s.nextInt();
System.out.println("The entered integer is
"+a);
}
}
30
Keyboard Input …
Contd.
//Float Input
import java.util.Scanner;
public class KeyInputDemo {
public static void main(String args[])
{
float a;
Scanner s = new Scanner(System.in);
System.out.println("Enter an integer:");
a = s.nextFloat();
System.out.println("The entered integer is "+a);
}
}
31
Keyboard Input …
Contd.
//Double Input
import java.util.Scanner;
public class KeyInputDemo {
public static void main(String args[])
{
double a;
Scanner s=new Scanner(System.in);
System.out.println("Enter an integer:");
a = s.nextDouble();
System.out.println("The entered integer is "+a);
}
}
32
Keyboard Input …
Contd.
//String Input
import java.util.Scanner;
public class KeyInputDemo {
public static void main(String args[])
{
String a;
Scanner s=new Scanner(System.in);
System.out.println("Enter an integer:");
a=s.nextLine();
System.out.println("The entered integer is
"+a);
}
} 33
Keyboard Input …
Contd.
//Char Input
import java.util.Scanner;
public class KeyInputDemo {
public static void main(String args[])
{
char a;
Scanner s=new Scanner(System.in);
System.out.println("Enter an integer:");
a=s.next().charAt(0);
System.out.println("The entered integer is "+a);
}
}
34
Loop
Statements
35
Loop
Statements
for Loop
• Used to iterate a part of the program several times.
• If the number of iteration is fixed, it is
recommended to use for loop.
36
Loop
Initialization Statements
• It is the initial condition which is executed once when the loop starts.
• We can initialize the variable, or we can use an already initialized
variable.
• It is optional.
Condition
• It is the second condition which is executed each time to test the
condition of the loop.
• It continues execution until the condition is false.
• It must return Boolean value either true or false.
• It is optional.
Increment/Decrement
• It increments or decrements the variable value.
• It is optional.
Statement 37
Loop
Statements
// Print from 1 to 10 public class
Demo1{
public static void main(String[]
args)
{
int i;
for(i=1; i<=10; i++)
{
System.out.println(i);
}
} 38
Loop
Nested for Loop Statements
• for loop inside the another loop.
• The inner loop executes completely whenever outer loop
executes.
Syntax 43
Loop
Statements
public class Demo4 {
public static void main(String[]
args)
{
int arr[]={12,23,44,56,78};
for(int i:arr)
{ System.out.pri
ntln(i);
}
}
44
Loop
Statements
Infinitive for Loop
• Use two semicolons ;; in the for loop.
• Press ctrl+c to exit from the program.
Syntax
for(;;){
//code to be executed
}
45
Loop
Statements
public class Demo6
{
public static void main(String[] args)
{
//Using no condition in for loop
for(;;)
{
System.out.println("infinitive
loop");
}
}
46
}
Loop
Statements
while Loop
• Used to iterate a part of the program repeatedly until the speci
Boolean condition is true.
• As soon as the Boolean condition becomes false, the loop automatically
• The while loop is considered as a repeating if statement.
• If the number of iteration is not fixed, it is recommended to use the whi
loop.
Syntax
while (condition){
//code to be executed
Increment /decrement
statement 47
Loop
Statements
public class Demo7 {
public static void main(String[] args)
{ int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
48
Loop
Statements
Infinitive while Loop
• Pass true in the while loop.
• Enter Ctrl + C command to terminate
the infinite loop.
Syntax
while(true){
//code to be executed
}
49
Loop
Statements
do-while Loop
• Used to iterate a part of the program repeatedly, until
the specified condition is true.
• If the number of iteration is not fixed and you must
have to execute the loop at least once, it is
recommended to use a do-while loop.
• Exit control loop.
• Unlike while loop and for loop, the do-while check the
condition at the end of loop body.
• The do-while loop is executed at least once because
condition is checked after loop body.
50
Syntax Loop
//code to be executed / loop Statements
do{
body
//update statement
}while (condition);
Condition
• It is an expression which is tested.
• If the condition is true, the loop body is executed and control goes
to update expression.
• As soon as the condition becomes false, loop breaks automatically.
Update expression
• Every time the loop body is executed, this expression increments
or decrements loop
variable.
• The do block is executed at least once, even if the 51
Loop
Statements
public class Demo9 {
public static void main(String[]
args)
{
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
} 52
Loop
Statements
Infinitive do-while Loop
• Pass true in the do-while loop.
• Enter Ctrl + C command to terminate the
infinite loop.
Syntax
do{
//code to be executed
}while(true);
53
Loop
Statements
public class Demo10 {
public static void main(String[] args)
{
do{
System.out.println("infinitive do
while loop");
}while(true);
}
}
54
Jump
Statements
break Statement
• When a break statement is encountered inside a loop, the
loop is immediately terminated and the program control
resumes at the next statement following the loop.
• Used to break loop or switch statement.
• Breaks the current flow of the program at specified
condition.
• In case of inner loop, it breaks only inner loop.
Syntax
jump-statement;
55
break;
Jump
Statements
public class Demo11 {
public static void main(String[]
args) {
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
56
}
Jump
Statements
continue Statement
• Used in loop control structure when you need to
jump to the next iteration of the loop
immediately.
• Used with for loop or while loop.
• Used to continue the loop.
• It continues the current flow of the program and
skips the remaining code at the specified
condition.
• In case of an inner loop, it continues the inner
loop only.
Syntax 57
Jump
Statements
public class Demo12 {
public static void main(String[]
args) { for(int
i=1;i<=10;i++){ if(i==5){
continue;//it will skip the rest
statement
}
System.out.println(i);
}
}
} 58
DIY
Write a Java program that prompts
the user to input an integer between 0
and 35. If the number is less than
equal to 9, the program should output
the number; otherwise, it should
output A for 10, B for 11, C for 12,
…, and Z for 35.
59
import java.util.Scanner;
public class NumberConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer between 0 and 35: ");
int inputNumber = scanner.nextInt();
if (inputNumber >= 0 && inputNumber <= 9) {
System.out.println("Output: " + inputNumber);
} else if (inputNumber >= 10 && inputNumber <= 35) {
char outputChar = (char) ('A' + (inputNumber - 10));
System.out.println("Output: " + outputChar);
} else {
System.out.println("Invalid input. Please enter a
number between 0 and 35.");
}
}
}
60
Practice
Programs
1) Write a Java program to calculate the sum of first 10 natural
number.
2) Write a Java program that prompts the user to input a positive
integer. It should then print the multiplication table of that
number.
3) Write a Java program to find the factorial value of any
number entered through the keyboard.
4) Write a Java program that prompts the user to input an
integer and then outputs the number with the digits reversed.
5) Write a Java program to print out all Armstrong numbers
between 1 and 500.
6) A bank collects an interest of 6% for loans given upto
Rs.7000, 8% for loans between Rs.7001 and Rs.10000,
61
References
Herbert Schildt, The Complete Reference – java, Tata
McGraw-Hill Education, 10th Edition, 2017
Paul J. Deitel, Harvey Deitel, Java SE8 for programmers
(Deitel Developer Series) 3rd Edition, 2014
Y. Daniel Liang, Introduction to Java Programming-
Comprehensive Version-10th Edition, Pearson Ltd, 2015
Kathy Sierra, Bert Bates , Head First Java, 2nd Edition 2nd
Edition , O'Reilly Media; 2nd edition (February 19, 2005)
Cay S. Horstmann, Core Java Volume I—Fundamentals 9th
Edition, Prentice Hall; 9 edition (December 7, 2012) Joshua
Bloch, Effective Java-2nd Edition, Addison-Wesley; (May
28, 2008).
https://www.javatpoint.com/java-tutorial
200