Control statements

29
Control Statements Unit1-Chapter4

Transcript of Control statements

Page 1: Control statements

Control Statements

Unit1-Chapter4

Page 2: Control statements

Contents

• Input charecters from keyboard• if statement• Nested if ‘s• If else if ladder• Switch statement• Nested switch statement• For loop statement• While loop• Do while loop• Break• Continue• Nested loops

Page 3: Control statements

Input characters from keyboard

• In order to read data from keyboard from user, we use System.in.read()

• System.in is an input object attached to the keyboard• read() method waits until the user presses key and then

return the result.• The character is returned as an integer so it must be

casted back into a character and should be stored in a character variable

• By default the console input is line buffered.• Buffer refers to small portion of memory that is used to

hold the characters before they are read by the program

Page 4: Control statements

• When the user presses Enter then the value from buffer will be sent to your program.

Import java.io.*;class KeyBoardInput{public static void main(String args[]) throws IOException{

char ch;System.out.println("Press a key followed by a letter:");ch=(char) System.in.read();System.out.println("Enter letter is :"+ch);

}//end of main}//end of class

Page 5: Control statements

The if statement

if(condition)

{

statement;

}

class IfExam {

public static void main(String args[]){ int x = 10; if( x < 20 ){ System.out.print("This is if

statement"); } }}

Page 6: Control statements

If else statement

public class IfElseExam { public static void

main(String args[]){ int x = 30; if( x < 20 ){ System.out.print("This

is if statement"); }else{ System.out.print("This

is else statement"); } }}

if(condition)

{

statement;

}

else

{

statement;

}

Page 7: Control statements

The if else if ladderif(condition)

Statement;else if(condition)

Statement;else if(Condition)

Statement;….else

Statement;

class IfElseIfLadder { public static void main(String args[]){ int x = 30; if( x == 10 ) System.out.print("Value of X is 10"); else if( x == 20 ) System.out.print("Value of X is 20"); else if( x == 30 ) System.out.print("Value of X is 30"); else System.out.print("This is else

statement"); }}

Page 8: Control statements

Nested If statements

• An if statement that is the target of another if or elseclass NestedIF { public static void main(String args[]){ int x = 30, y = 10; if( x == 30 ){ if( y == 10 ) System.out.print("X = 30 and Y = 10"); else

System.out.println("Y is not 10”); } }}

Page 9: Control statements

Switch statement

• It provides multi way branch• Gives chance to programmer to select among several

alternatives.• The value of expression is evaluated against list of

constants• When a match is found, the statement sequence

associated with that is executed.

Page 10: Control statements

switch(expression){ case constant1 :

Statements break; //optional

case constant2 : Statements break;//optional

…… default : Statements }

class Result { public static void main(String args[]){ char grade = 'C'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' :System.out.println("Well done"); break; case 'D' :System.out.println("You

passed"); case 'F' :System.out.println("Better try

again"); break; default : System.out.println("Invalid

grade"); } System.out.println("Your grade is " +

grade); }}

Page 11: Control statements

Nested switch statement• Switch part of the

statement sequence of an outer switch

• Even if the case constants of inner and outer switch statements contain common values no conflicts will arise

class NestedSwitchExample { public static void main(String[] args) { int i = 0,j = 1; switch(i) { case 0:switch(j) {

case 0: System.out.println("i is 0, j is 0"); break;

case 1: System.out.println("i is 0, j is 1"); break;

default: System.out.println("nested default case!!");

}//end of inner switch break; default: System.out.println("No matching case

found!!"); } //end of outer switch }//end of main}//end of class

Page 12: Control statements

The For loopfor(intialization;condition;iteration)

{

Statement;

}

class ForLoop {

public static void main(String args[]) {

for(int x = 1; x < 5; x++) {

System.out.println("value of x : " + x );

}

}

}

Page 13: Control statements

Some variations of for loop

• Multiple loop control varaibles can be used.class Comma{public static void main(String args[]){

int i,j;for(i=0,j=10;i<j;i++,j--)

System.out.println("i="+i+" j="+j); }//end of main}//end of class

Page 14: Control statements

• Condition controlling variable can be any valid boolean expression

import java.io.*;

class ForTest {

public static void main(String args[]) throws IOException {

for(int x = 0; (char)System.in.read() !='S'; x++)

System.out.println("Pass #" + x );

}

}

Page 15: Control statements

• Missing pieces• In java, any or all of the initialization, condition or

iteration portions of the for loop can be blank.class Empty { public static void main(String args[]) { int x = 0; for(;x<10;) { System.out.println("Pass #" + x );

x++; } }}

Page 16: Control statements

• Infinite loop-loop that never terminates

• For by leaving the conditional expression emptyfor(; ;)

{

}

Page 17: Control statements

Loops with no body

• Body of the for loop can be empty• Null statement is syntactically valid• Body less loops are less often used.class Nobody{

public static void main(String args[]){

int i,sum=0;for(i=1;i<=5;sum+=i++); //sum+=i and then i++System.out.println(“Sum is “+sum);

}}

Page 18: Control statements

Declaring loop control variables inside the for loop

• Variable that controls a for loop used inside the for loop is needed only for the purposes of the loop and not used elsewhere

• In this case , it is better to declare the variables inside the initialization portion of the for loop.

Page 19: Control statements

class ForVar{public static void main(String args[]){

int sum=0,fact=1;for(int i=1;i<=5;i++)

{sum+=i;fact*=i;

}//end of for loopSystem.out.print("Sum:"+sum+"\nFactorial :"+fact);

}//end of main}//end of class

Page 20: Control statements

Enhanced for loop

for (datatype variable: array_name) {//body of the for loop}

class EnhancedForLoop {public static void main(String[] args) { int primes[] = { 2, 3, 5, 7, 11, 13, 17}; for (int t: primes) System.out.println(t); }}

class EnhancedForLoop1{ public static void main(String[] args) { String languages[] = { "C", "C++", "Java", "Python", "Ruby"}; for (String sample: languages) { System.out.println(sample); } }}

Page 21: Control statements

While loop

while(condition)

statements;• Where statements may be single statement or block of

statements.• The condition may be any valid boolean expression• The loop repeats when the condition is true, when it

becomes false, program control passes to line immediately after the loop.

Page 22: Control statements

class WhileDemo{

public static void main(String args[]){

char ch='a';

while(ch<='d'){

System.out.println(ch);

ch++;

}//end of while loop

}//end of main

}//end of class

Page 23: Control statements

Do while loop

do{

Statements;

}while(condition);

• It will execute as long as condition is true.

import java.io.*;

class DWdemo

{

public static void main(String args[]) throws IOException

{

char ch='a';

do

{

System.out.println(ch);

ch++;

}while(ch!='d');

}

}

Page 24: Control statements

Break statement• When a break statement is encountered inside a loop,

the loop is terminated and program resumes at the next statement followed by the loop.

class BreakDemo{

public static void main(String args[]){

int num=100;

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

{

if(i*i>=num)

break;

System.out.print(i+ " ");

}

System.out.print("Loop complete");

}

}

Page 25: Control statements

Use break as goto statementclass BreakGoto{

public static void main(String args[]){

int i;

for(i=1;i<4;i++)

{

one: {

two:{

three:{System.out.println("\n i is "+i);

if(i==1) break one;

if(i==2) break two;

if(i==3) break three;

//this is never executed

System.out.print("wrong statement");

}System.out.println("After block three");}System.out.println("After block two");

}System.out.println("After block one");

}System.out.println("After for statement");

}

}

Page 26: Control statements

Use continue

• The continue statement forces the next iteration of the loop take place, skipping the code between itself and conditional expression that controls the loop.

• Continue is compliment of break statement

Page 27: Control statements

class ContinueDemo{

public static void main(String args[]){

int i;

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

{

if((i%2)!=0) continue;

System.out.println(i);

}

}

}

Page 28: Control statements

Nested loops

• One loop nested inside of another loop

• Nested for loop to find the factors of the numbers from 2 to 20

class FindFac{

public static void main(String args[]){

for(int i=2;i<=20;i++){

System.out.print("Factors of "+i+" : ");

for(int j=2;j<i;j++)

if((i%j)==0) System.out.print(j+" ");

System.out.println();

}

}

}

Page 29: Control statements