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

Module 5 Part Three

Uploaded by

No Name
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Module 5 Part Three

Uploaded by

No Name
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Java Fundamentals

The while Statement


 A while statement is another iteration (or, loop) statement, which is used to execute a
statement repeatedly as long as a condition is true.
 A while statement is also known as a while-loop statement.
 The general form of a while-loop statement is
while (condition-expression)
Statement
 Unlike the for-loop statement, the condition-expression in a while-loop statement is not
optional.

Infinite loop
 To make a while statement infinite loop, you need to use the boolean literal true as the
condition-expression.
while (true)
System.out.println ("This is an infinite loop");

 The conversion between a for-loop and a while-loop statement is shown below.

for (initialization; condition-expression; expression-list)


Statement

Equivalent while-loop Statements:

Initialization
while (condition-expression)
{
Statement
Expression-list
}

Example - print all integers between 1 and 10 using a while-loop

int i = 1;
while (i <= 10)
{
System.out.println(i);
i++;
}
The above code can also be rewritten as
int i = 0;
while (++i <= 10)
{
System.out.println(i);
}
Or
int i = 1;
while (i <= 10)
{
System.out.println(i++);
}

DTTH Page 1
Java Fundamentals

 A break statement is used to exit the loop in a while-loop statement.


int i = 1;
while (true)
{
// Cannot exit the loop from here
if (i <= 10)
{
System.out.println(i);
i++;
}
else
{
break; // Exit the loop
}
}

Example 1: find the summation of numbers from 1 to 10.


class WhileSum {
public static void main(String args[])
{
int x = 1, sum = 0;

while (x <= 10) {


sum = sum + x;
x++;
}
System.out.println("Summation: " + sum);
}
}
Example 2: While loop to compare two numbers
class WhileTest2
{
public static void main(String[] args) {
int large = 2345;
int small = 3;
while (large > small){
System.out.println("Large = " + large + " and
" + "Small = " + small);
large = large / 2;
small = small * 2;
}
System.out.println("Outside of Loop");
System.out.println("Large Value=" + large);
System.out.println("Small Value=" + small);
}
}
To display fibonancci sequence like this : 0 1 1 2 3 5 8 13 21
class Fibonancci
{
public static void main(String[] args)
{
int a=0, b=1, c=0;
int counter =1;
System.out.print(a+ " " + b);

DTTH Page 2
Java Fundamentals

while(counter<=7)
{
c=a+b;
System.out.print(" " +c);
a=b;
b=c;
counter++;
}
}
}

Using While Loop With Unknown Times


Example 1
import java.io.*;
class WhileUnknownTimes
{
public static void main(String[] args)
{
int count=0;
try
{
//int count = 0;
InputStreamReader ir= new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
System.out.println("Press 1 to start : ");
String str = br.readLine();
int code = Integer.parseInt(str);
while(code==1)
{
System.out.println("Processing in Loop");
count++;
System.out.println("Press 1 to continue." +
"If you want to quit, press 9");
str = br.readLine();
code=Integer.parseInt(str);
}

}catch(IOException ie){

System.out.println(ie.getMessage());
}
System.out.println("You tried "+ count + " times.");

}
}

DTTH Page 3
Java Fundamentals

Example 2
import java.io.*;
class WhileUnknownTimesChar
{
public static void main(String[] args)
{
int count=0;
try
{
//int count = 0;
InputStreamReader ir= new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
System.out.println("Will you start?[Y/N] : ");
String str = br.readLine();
char code = str.charAt(0);
code = Character.toUpperCase(code);
//code = Character.toLowerCase(code);
//while(code=='y')
while(code=='Y')
{
System.out.println("Processing in Loop");
count++;
System.out.println("Will you continue?[Y/N]
:");
str = br.readLine();
code = str.charAt(0);
code = Character.toUpperCase(code);
}

}catch(IOException ie){

System.out.println(ie.getMessage());
}
System.out.println("You tried "+ count + " times.");
}
}

The do-while Statement


 The do-while statement is another loop statement.
 It is similar to the while-loop statement with one difference.
 The statement associated with a while loop statement may not be executed even once if the
condition-expression evaluates to false for the first time.
 However, the statement associated with a do-while statement is executed at least once.
 The general form of a do-while statement is

do
Statement
while (condition-expression);

 The statement can be a simple statement or a block statement.


 Note that the do-while statement ends with a semicolon.
 Like in a for loop and a while loop, a break statement may be used to exit a do-while loop.

DTTH Page 4
Java Fundamentals

Example - compute the sum of integers between 1 and 10


int i = 1;
int sum = 0;
do
{
sum = sum + i; // Better to use
sum += i
i++;
} while (i <= 10);
// Print the result
System.out.println("Sum = " + sum);

The break Statement


 A break statement is used to exit from a block.
 There are two forms of the break Statements:
• Unlabeled break statement
• Labeled break statement
 An example of an unlabeled break statement is
break;
 An example of a labeled break statement is
break label;
 You have already seen the use of the unlabeled break statement inside switch, for-loop, while-
loop, and do-while statements.
 It transfers control out of a switch, for-loop, while-loop, and do-while statement in which it
appears.
Example - print the lower half of the 3x3 matrix

11
21 22
31 32 33

for(int i = 1; i <= 3; i++)


{
for(int j = 1; j <= 3; j++)
{
System.out.print ( i + "" + j);
if (i == j)
{
break; // Exit the inner for loop
}
System.out.print("\t");
}
System.out.println();
}

 If you want to exit from the outer for-loop statement from inside the inner for-loop statement,
you have to use a labeled break statement.
 A label in Java is any valid Java identifier followed by a colon.
 The following are some valid labels in Java:
label1:
alabel:
Outer:
Hello:
IamALabel:

DTTH Page 5
Java Fundamentals

Example - use a labeled break statement for outer loop


outer: // Defines a label named outer
for(int i = 1; i <= 3; i++ )
{
for(int j = 1; j <= 3; j++ )
{
System.out.print(i + "" + j);
if (i == j)
{
break outer; // Exit the outer for loop
}
System.out.print("\t");
}
System.out.println();
} // The outer label ends here

 Note that the outer label appears just before the outer for-loop statement.
 A labeled statement can be used not only inside switch, for-loop, while-loop, and do-while
statements.
 Rather it can be used with any type of a block statement.

blockLabel:
{
int i = 5;
//int i = 10;
if (i == 5)
{
break blockLabel; // Exits the block
}
if (i == 10)
{
System.out.println("i is not five");
}
}

 The label used with the break statement must be the label for the block in which that labeled
break statement is used.

lab1:
{
int i = 10;
if (i == 10)
break lab1; // Ok. lab1 can be used here
}
lab2:
{
int i = 10;
if (i == 10)
break lab1; //compile error
}

DTTH Page 6
Java Fundamentals

The continue Statement


 A continue statement can only be used inside the for-loop, while-loop, and do-while
statements.
 There are two forms of the continue Statements:
• Unlabeled continue statement
• Labeled continue statement
 An example of an unlabeled continue statement is
continue;
 An example of a labeled continue statement is
continue label;

When a continue statement is executed inside a for loop, the rest of the statements in the body of the
loop are skipped and the expressions in the expression-list are executed.

Example - print all odd integers between 1 and 10 using a for-loop statement,
for (int i = 1; i < 10; i += 2)
{
System.out.println(i);
}

for(int i=1;i<10;i++)
{
if(i%2==0)
{
continue;
}
System.out.println(i);
}
Example - print all odd integers between 1 and 10, using a continue statement inside a while
loop
int i =1;
while (i<10)
{
if(i%2==0)
{
i++;
continue;
}
System.out.println(i);
i++;
}
 The main difference in using a continue statement inside a for loop and a while loop is the
place where the control is transferred.
 Inside a for loop, control is transferred to the expression-list, and in a while loop, the control
is transferred to the condition-expression.
 This is why a for-loop statement cannot always be converted to a while-loop statement
without modifying some logic.
 An unlabeled continue statement always continues the innermost for loop, while loop, and do-
while loop.
 If you are using nested loop statements, you need to use a labeled continue statement to
continue in the outer loop.

DTTH Page 7
Java Fundamentals

Example – Continue for inner loop


for(int i = 1; i <= 3; i++ )
{
System.out.println("i=" + i + " Outer Loop First Statement");
for(int j = 1; j <= 3; j++ )
{
System.out.println("j=" + j +" Inner Loop First
Statement");

if (j==2)
{
continue; // Contiue the inner for loop
}
System.out.println("j=" + j +" Inner Loop Last
Statement");
}
System.out.println("i=" + i + " Outer Loop Last Statement");
}
Output
i=1 Outer Loop First Statement
j=1 Inner Loop First Statement
j=1 Inner Loop Last Statement
j=2 Inner Loop First Statement
j=3 Inner Loop First Statement
j=3 Inner Loop Last Statement
i=1 Outer Loop Last Statement
i=2 Outer Loop First Statement
j=1 Inner Loop First Statement
j=1 Inner Loop Last Statement
j=2 Inner Loop First Statement
j=3 Inner Loop First Statement
j=3 Inner Loop Last Statement
i=2 Outer Loop Last Statement
i=3 Outer Loop First Statement
j=1 Inner Loop First Statement
j=1 Inner Loop Last Statement
j=2 Inner Loop First Statement
j=3 Inner Loop First Statement
j=3 Inner Loop Last Statement
i=3 Outer Loop Last Statement

Example – Continue for outer loop


outer: for(int i = 1; i <= 3; i++ ) Output
{ for(int j = 1; j <= 3; j++ ) 11
{ 21 22
System.out.print(i + "" + j); 31 32 33
System.out.print("\t");

if (i == j)
{
System.out.println();
continue outer; // Contiue outer for loop
}
}
}

DTTH Page 8
Java Fundamentals

PrimeFactor.java
import java.io.*;
public class PrimeFactor
{
public static void main(String[] args)
{
try
{
InputStreamReader ir = new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
System.out.println("Enter a number: ");
String str = br.readLine();
int num = Integer.parseInt(str);

int i = 2;
while ( i < num)
{
if ( num % i == 0)
{
System.out.print(i + "*");
num = num / i;
i=2;
continue;
}
i++;
}
System.out.print(" " + num);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Output
Enter a number:
6
2* 3

DTTH Page 9

You might also like