0% found this document useful (0 votes)
9 views41 pages

Java Module 1 Chapter 5

The document summarizes various control statements in Java including selection statements (if-else, switch), iteration statements (for, while, do-while loops), and jump statements. It provides examples of using if-else, if-else ladders, nested if statements, switch statements, while loops, do-while loops, and for loops. It also compares switch and if statements and discusses practical applications of do-while loops.

Uploaded by

2022becs190
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
9 views41 pages

Java Module 1 Chapter 5

The document summarizes various control statements in Java including selection statements (if-else, switch), iteration statements (for, while, do-while loops), and jump statements. It provides examples of using if-else, if-else ladders, nested if statements, switch statements, while loops, do-while loops, and for loops. It also compares switch and if statements and discusses practical applications of do-while loops.

Uploaded by

2022becs190
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 41

Module 1 – Chapter 5

Control statements
● Selection statements allow your program to choose different
paths of execution based on the outcome of an expression or the
state of a variable.
● Iteration statements enable program execution to repeat one or

more statements.
● Jump statements allow your program to execute in a nonlinear

fashion.
if is Java’s conditional branching
if (condition) { // block not needed for a single statement but recommended
statement/statements;
}
else { // block not needed for a single statement but recommended
statement/statements;
}
● Condition is a boolean value unlike C.
Simple Example
int a, b;
if (a < b) a = 0; // the expression should be boolean
else b = 0;
Always Block if and else
● If we have more than one statement, then write all statements within a block.

int bytesAvailable;

if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
} else
waitForMoreData();
Lab Activity/Exercise 9
Research on how to find out if the given year is a leap
year or not. For example, 2023 is a non-leap year, 2024
is a leap year as well as 2000. Using a simple if-else
statement write a program to print if the given year
(stored in an integer variable) is a leap year or not. Run
the program repeatedly for different inputs – test your
program for one leap year and one non-leap year at the
least.
Nested if
●A nested if is an if that is the target of another if or else.
if (i == 10) {
if (j < 20)
a = b;
if (k > 100) // this if is
c = d;
else a = c; // associated with the closest if
}
else a = d; // this else refers to if (i == 10)
if( condition1) {
if(condition 2)
statement ;
if (condition 3)
statement ;
……
……….
else
statement ;
}
else
statement;
The if-else-if Ladder
if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
.
.
.
else
statement;
// Demonstrate if-else-if statements.

class IfElse {

public static void main(String args[]) {

int month = 4; // April

String season;

if(month == 12 || month == 1 || month == 2)

season = "Winter";

else if(month == 3 || month == 4 || month == 5)

season = "Spring";

else if(month == 6 || month == 7 || month == 8)

season = "Summer";

else if(month == 9 || month == 10 || month == 11)

season = "Autumn";

else

season = "Bogus Month";

System.out.println("April is in the " + season + ".");

What is the output?


Lab Activity/Exercise 10
Research using the internet, the latest tax structure of
the Government of India. Using nested if-else
statements, write a program to display the annual tax
for the given income (you can store the income in a
variable of suitable data type). Run the program for all
possible different incomes.
● Java’s multiway branch statement
Switch statement
switch (expression) {

case value1:

// statement sequence

break;

case value2:

// statement sequence

break;

● .

● .

case valueN:

// statement sequence

break;

default:

// default statement sequence

}
Switch…
● Duplicate case values are not allowed.
●The expression must be of type byte, short, int, or
char.
●each of the values specified in the case statements
must be of a type compatible with the expression.
● Each case value must be a unique literal.
What is the output?
class SampleSwitch {

public static void main(String args[]) {

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

switch(i) {

case 0:

System.out.println("i is zero.");

break;

case 1:

System.out.println("i is one.");

break;

case 2:

System.out.println("i is two.");

break;

case 3:

System.out.println("i is three.");

break;

default:

System.out.println("i is greater than 3.");

}
Switch v/s If
●The switch differs from the if. Switch can only test for equality,
whereas if can evaluate any type of Boolean expression. I.e., the
switch looks only for a match between the value of the expression and
one of its case constants.
●No two case constants in the same switch can have identical values.
Of course, a switch statement and an enclosing outer switch can have
case constants in common.
• A switch statement is usually more efficient than a set of nested ifs.
Lab Activity/Exercise 11
Write a Java program to declare an integer variable
called day whose value represents one of the values 1
through 7. The program should display the name of the
day, based on the value of the day, using the switch
statement. 1- Monday, 2-Tuesday, … 7 - Sunday
Iteration Statements
● iteration statements are for, while, and do-while.
● These statements create what we commonly call loops.
While loop – top tested
●It repeats a statement or block while its controlling
expression is true.
while (condition) { // condition should be boolean
// body of loop
}
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;

while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
do-while loop – bottom tested
do {
// body of loop
} while (condition); // condition should be boolean
What is the output?
class DoWhile {
public static void main(String args[]) {
int n = 10;

do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
Practical application of do-while
●The do-while loop is especially useful when you
process a menu selection, because you will usually
want the body of a menu loop to execute at least once.
for loop – top tested
for(initialization; condition; iteration) {
// body
}
What is the output?
What is the output?
class ForTick {
public static void main(String args[]) {
for (int n=10; n>0; n--) {
System.out.println("tick " + n);
}
}
}
loop control variable, i, is declared inside the for
/What is the output?
class FindPrime {

public static void main(String args[]) {

int num;

boolean isPrime = true;

num = 14;

for (int i = 2; i <= num/i; i++) {

if((num % i) == 0) {

isPrime = false;

break;

if (isPrime) System.out.println("Prime");

else System.out.println("Not Prime");

}
Using Comma
class Sample {
public static void main(String args[]) {
int a, b;
b = 4;

for (a = 1; a < b; a++) {


System.out.println("a = " + a);
System.out.println("b = " + b);
b--;
}
}
}
Example of Comma
class Comma {
public static void main(String args[]) {
int a, b;

for(a=1, b=4; a<b; a++, b--) {


System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}
For-Each Version of the for Loop
●no new keyword is required. Instead of for, we can
write foreach.
● no pre-existing code is broken.
● General form:
for(type itr-var : collection) statement-block
Using for
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for (int i = 0; i < 10; i++)
sum += nums[i];
Using for-each
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for (int x: nums)
sum += x;
What is the output?
Nested Loops
class Nested {
public static void main(String args[]) {
int i, j;

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

for(j=i; j<10; j++)


System.out.print(".");
System.out.println();
}
}
}
Jump Statements
●Java supports three jump statements: break, continue,
and return.
● Uses of break statement
● it terminates a statement sequence in a switch statement.
● it can be used to exit a loop.
● it can be used as a “civilized” form of goto
fWhat is the output?
class BreakLoop {
public static void main(String args[]) {
for(int i = 0; i < 100; i++) {
if (i == 10) break; // terminate if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
What is the output?
class BreakLoop2 {
public static void main(String args[]) {
int i = 0;

while(i < 100) {

if(i == 10) break; // terminate loop if i is 10


System.out.println("i: " + i);
i++;
}
System.out.println("Loop complete.");
}
}
What is the output?
class BreakLoop3 {
public static void main(String args[]) {
for (int i = 0; i < 3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if (j == 10) break; // terminate loop if j is 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}
}
Using break as a Form of Goto
● break label;
● label is the name, that identifies a block of code.
●labeled break statement to exit from a set of nested
blocks.
What is the output?
class Break {

public static void main(String args[]) {

boolean t = true;

First: :{

second: {

third: {

System.out.println("Before the break.");

if(t) break second; // break out of second block

System.out.println("This won't execute");

System.out.println("This won't execute");

System.out.println("This is after second block.");

}
About break statement
●more than one break statement may appear in a loop.
Too many break statements tend to destructure your
code.
●The break that terminates a switch statement affects
only that switch statement and not any enclosing loops.
Using Continue
●A continue statement causes control to be transferred
directly to the conditional expression that controls the
loop.
What is the output?
public static void main(String[] args) {
for (int i=1; i<=10; i++) {

if (i==5) {
// using continue statement
continue;//it will skip the current statement
}
System.out.println(i);
}
}
Return statement
● The return statement transfers control to the caller.
What is the output?
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");

if(t) return; // return to caller


System.out.println("This won't execute.");
}
}

You might also like