Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Unit-1 Control statement

The document provides an overview of control statements in Java, categorizing them into selection, iteration, and jump statements. It explains selection statements like 'if' and 'switch', iteration statements such as 'for', 'while', and 'do-while', and jump statements including 'break', 'continue', and 'return'. Each type of statement is illustrated with examples to demonstrate their usage and functionality in controlling the flow of program execution.

Uploaded by

Suja Mary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit-1 Control statement

The document provides an overview of control statements in Java, categorizing them into selection, iteration, and jump statements. It explains selection statements like 'if' and 'switch', iteration statements such as 'for', 'while', and 'do-while', and jump statements including 'break', 'continue', and 'return'. Each type of statement is illustrated with examples to demonstrate their usage and functionality in controlling the flow of program execution.

Uploaded by

Suja Mary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Unit- I

Control Statements
A programming language uses control statements to cause the flow of execution to advance and
branch based on changes to the state of a program.

Java’s program control statements can be put into the following categories:

1. selection
2. iterationa
3. jump.

Java’s Selection Statements

Selection statements allow our program to choose different paths of execution based upon the
outcome of an expression or the state of a variable.

Java supports two selection statements:


1. if
2. switch
if
The if statement is Java’s conditional branch statement. It can be used to route program
execution through two different paths.
The general form of the if statement:

if (condition) statement1;

else statement2;

Here, each statement may be a single statement or a compound statement enclosed in curly
braces.
The condition is any expression that returns a boolean value.
The else clause is optional.
If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is
executed.

Example

int a, b;

if(a < b) a = 0;
else b = 0;

Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero.

To include more statements, it need to create a block

Nested ifs

A nested if is an if statement that is the target of another if or else. An else statement always
refers to the nearest if statement that is within the same block as the else and that is not already
associated with an else.

Example:

if(i == 10) {
if(j < 20)
a = b;
if(k > 100)
c = d;
else
a = c;
}
else
a = d;
The final else is not associated with if(j<20) ) because it is not in the same block

The if-else-if Ladder

A common programming construct that is based upon a sequence of nested ifs is the if-else-if
ladder.

The General Form:


if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;

The if statements are executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the rest of the ladder is
bypassed.

If none of the conditions is true, then the final else statement will be executed.

Example
switch
The switch statement is Java’s multiway branch statement.

It often provides a better alternative than a large series of if-else-if statements.

The general form of a switch statement:

switch (expression) {

case value1:

// statement sequence

break;

case value2:

// statement sequence

break;

...

case valueN:

// statement sequence

break;

default:

// default statement sequence

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.

The value of the expression is compared with each of the literal values in the case statements. If
a match is found, the code sequence following that case statement is executed.

If none of the constants matches the value of the expression, then the default statement is
executed.

The default statement is optional.


The break statement is used inside the switch to terminate a statement sequence.

Example

The output produced by this program is shown here:


i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3
If omit the break, execution will continue on into the next case.
Example
Nested switch Statements
To use a switch as part of the statement sequence of an outer switch. This is called a nested
switch.
Since a switch statement defines its own block, no conflicts arise between the case constants in
the inner switch and those in the outer switch.
Example
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
Break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...
Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the
outer switch. The count variable is only compared with the list of cases at the outer level. If
count is 1, then target is compared with the inner list cases.
Iteration Statements
Iteration statements enable program execution to repeat one or more statements (that is, iteration
statements form loops).

Java’s iteration statements are

1. For
2. While
3. do-while.

While
The while loop is Java’s most fundamental loop statement. It repeats a statement or block while
its controlling expression is true.

The general form is:

while(condition) {

// body of loop

 The condition can be any Boolean expression.


 The body of the loop will be executed as long as the conditional expression is true.
 When condition becomes false, control passes to the next line of code immediately
following the loop.
 The curly braces are unnecessary if only a single statement is being repeated
Example
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}}}
The body of the while can be empty. This is because a null statement is syntactically valid in
Java.
Example
// The target of a loop can be empty.
class NoBody {
public static void main(String args[]) {
int i, j; i = 100; j = 200; // find midpoint between i and j
while(++i<--j); //no body in this loop
System.out.println("Midpoint is " + i);
}}
This program finds the midpoint between i and j. It generates the following output:
Midpoint is 150
The value of i is incremented, and the value of j is decremented. These values are then compared
with one another.
do-while
The do-while loop always executes its body at least once, because its conditional expression is at
the bottom of the loop.
Its general form is

do {

// body of loop

} while (condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates the
conditional expression.
Example
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}}
If this expression is true, the loop will repeat. Otherwise, the loop terminates.

For
There are two forms of the for loop.
 The first is the traditional form that has been in use since the original version of Java.
 The second is the new “for-each” form
The general form of the traditional for statement is:

for(initialization; condition; iteration)


{
// body
}

When the loop first starts, the initialization portion of the loop is executed. It is important
to understand that the initialization expression is only executed once.
 Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop
control variable against a target value. If this expression is true, then the body of the loop
is executed. If it is false, the loop terminates.
 Next, the iteration portion of the loop is executed. This is usually an expression that
increments or decrements the loop control variable.
 The loop then iterates, first evaluating the conditional expression, then executing the
body of the loop, and then executing the iteration expression with each pass. This process
repeats until the controlling expression is false
Example

// Demonstrate the for loop.

class ForTick {

public static void main(String args[]) {

int n;

for(n=10; n>0; n--)

System.out.println("tick " + n);

}}

Declaring Loop Control Variables Inside the for Loop

It is possible to declare the variable inside the initialization portion of the for.
Example

for(int n=10; n>0; n--)

The scope of that variable ends when the for statement does.

Using the Comma

There will be times when you will want to include more than one statement in the initialization
and iteration portions of the for loop.

For example

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

The initialization portion sets the values of both a and b. The two commaseparated statements in
the iteration portion are executed each time the loop repeats.

Some for Loop Variations

The for loop supports a number of variations that increase its power and applicability. The
reason it is so flexible is that its three parts—the initialization, the conditional test, and the
iteration

1. One of the most common variations involves the conditional expression. Specifically, this
expression does not need to test the loop control variable against some target value.

Example

boolean done = false;


for(int i=1; !done; i++) {
// ...
if(interrupted()) done = true;
}
The for loop continues to run until the boolean variable done is set to true. It does not test the
value of i.
2. Either the initialization or the iteration expression or both may be absent
Example
int i;
boolean done = false;
i = 0; for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}
The initialization and iteration expressions have been moved out of the for. Thus, parts of the for
are empty.
3. Create an infinite loop (a loop that never terminates) if you leave all three parts of the for
empty. For example:
for( ; ; ) {
// ...
}
This loop will run forever because there is no condition under which it will terminate.
The For-Each Version of the for Loop
Java adds the for-each capability by enhancing the for statement. The advantage of this approach
is that no new keyword is required, and no preexisting code is broken. The for-each style of for is
also referred to as the enhanced for loop. The general form of the for-each version of the for is
shown here:
for(type itr-var : collection) statement-block
Here, type specifies the type and itr-var specifies the name of an iteration variable that
will receive the elements from a collection, one at a time, from beginning to end. The collection
being cycled through is specified by collection.
With each iteration of the loop, the next element in the collection is retrieved and stored
in itr-var. The loop repeats until all elements in the collection have been obtained.
The following fragment uses a traditional for loop to compute the sum of the values in an array:
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];
The for-each style for automates the preceding loop. Specifically, it eliminates the need to
establish a loop counter, specify a starting and ending value, and manually index the array.
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
sum += x;

With each pass through the loop, x is automatically given a value equal to the next element in
nums. Thus, on the first iteration, x contains 1; on the second iteration, x contains 2; and so on.

The for-each style loop iteration variable is “read-only” as it relates to the underlying array. An
assignment to the iteration variable has no effect on the underlying array.

The contents of the array can’t change by assigning the iteration variable a new value

Example

// The for-each loop is essentially read-only.


class NoChange {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int x : nums) {
System.out.print(x + " ");
x = x * 10; // no effect on nums
}
System.out.println();
for(int x : nums)
System.out.print(x + " ");
System.out.println();
}}
Iterating Over Multidimensional Arrays

The enhanced version of the for also works on multidimensional arrays.


when using the for-each for to iterate over an array of N dimensions, the objects obtained will be
arrays of N–1 dimensions.

int sum = 0;
int nums[][] = new int[3][5]; // give nums some values
for(int i = 0; i < 3; i++)
for(int j=0; j < 5; j++)
nums[i][j] = (i+1)*(j+1); // use for-each for to display and sum the values
for(int x[] : nums)
{ for(int y : x) {
System.out.println("Value is: " + y);
sum += y;
}}
System.out.println("Summation: " + sum);

Applying the Enhanced for

 The for-each style for can only cycle through an array sequentially, from start to finish.
 A large number of algorithms require exactly this mechanism.
 One of the most common is searching.
 For example, the following program uses a for loop to search an unsorted array for a
value. It stops if the value is found
// Search an array using for-each style for.
class Search {
public static void main(String args[]) {
int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;
boolean found = false; // use for-each style for to search nums for val
for(int x : nums) {
if(x == val) {
found = true; break;
}}
if(found)
System.out.println("Value found!");
}}
 The for-each style for is an excellent choice in this application because searching an
unsorted array involves examining each element in sequence.
 The benefit of for-each style loops include computing an average, finding the minimum
or maximum of a set, looking for duplicates, and so on.
Nested Loops

Java allows loops to be nested. That is, one loop may be inside another.
Example
// Loops may be nested.
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.println(“.”);
System.out.println();
}}}
Jump Statements
Jump statements allow our program to execute in a nonlinear fashion.

Java supports three jump statements:


1. Break
2. Continue
3. return.
Using break
In Java, the break statement has three uses.
1. It terminates a statement sequence in a switch statement.
2. It can be used to exit a loop.
3. It can be used as a “civilized” form of goto.
When a break statement is encountered inside a loop, the loop is terminated and program control
resumes at the next statement following the loop.
Example:
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100;i++){
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}}
The for loop is designed to run from 0 to 99, the break statement causes it to terminate early,
when i equals 10.
When used inside a set of nested loops, the break statement will only break out of the innermost
loop. For example:

Using break as a form of Goto


The break statement can also be employed by itself to provide a “civilized” form of the goto
statement
break gives you the benefits of a goto without its problems.
The general form of the labeled break statement is :
break label;
label is the name of a label that identifies a block of code.
When this form of break executes, control is transferred out of the named block. The labeled
block must enclose the break statement, but it does not need to be the immediately enclosing
block.
Example
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");
}
One of the most common uses for a labeled break statement is to exit from nested loops.
Example

Using continue
In while and do-while loops, a continue statement causes control to be transferred directly to the
conditional expression that controls the loop.
In a for loop, control goes first to the iteration portion of the for statement and then to the
conditional expression.
Example

You might also like