0 likes | 1 Vues
Very interactive java programming
E N D
Chapter Three Decision & Repetition Statements 1
*A running program spends all of its time executing statements. *The order in which statements are executed is called flow control or (control flow). *Flow control in a program is sequential, from one statement to the next, but may be diverted to other paths by branch statements. *Program Control Statements allow us to change the ordering (sequence) of how the statements in our programs are executed. 2
Cont.… There are different forms of Java statements: Declaration statements are used for defining variables. Assignment statements are used for simple, algebraic computations. Branching statements are used for specifying alternate paths of execution, depending on the outcome of a logical condition. Loop statements are used for specifying computations, which need to be repeated until a certain logical condition is satisfied. 3
2.1 Decision/Conditional Statements *Decision statements are Java statements that allows us to select and execute specific blocks of code while skipping other sections. 2.1.1 The if statement *The if-statement specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true. *General form: if(expression) statements; *The first expression is evaluated. If the outcome is true then statement is executed. Otherwise, nothing happens. *Example: When dividing two values, we may want to check that the denominator is nonzero if(y!=0) div=x/y; 4
2.1.2The if-else statement *The if-else statement is used to execute a certain statement if a condition is true, and a different statement if the condition is false. *General form: if(expression) statement1; else statement2; *First expression is evaluated. If the outcome is true then statement1 is executed. Otherwise, statement2 is executed. *Example: if(score>=50) { System.out.println("Congratulations! You Passed!”; "); } else { System.out.println(”You Failed!”); System.out.println(”You Must Take This Course Again!”); 5 }
*The statement in the else-clause of an if-else block can be another if-else structures. *This cascading of structures allows us to make more complex selections. *Example: if(score<0 && score>100) { System.out.println(“ Score [0-100]”); } if(score>=85 && score<=100) { System.out.println(“ A Grade”); } else if(score>=75 && score<85 ){ System.out.println(“ B Grade”); } else if(score>=65 && score<75 ) { System.out.println(“ C Grade”); } else if(score>=50 && score<65 ) { System.out.println(“D Grade”); } else { System.out.println(“F Grade”); } if(CGPA<0 && CGPA>4) { System.out.println(“CGPA [0-4]”); } if(CGPA>=3.5 && CGPA<=4) { System.out.println(“ Excellent!”); } else if(CGPA>=3.0 && CGPA<3.5){ System.out.println(“ Very Good!”); } else if(CGPA>=2.5 && CGPA<3.0 ) { System.out.println(“ Good!”); } else if(CGPA>=2.0 && CGPA<2.5 ) { System.out.println(“Satisfactory!”); } else { System.out.println(“Poor!”); } 6
switch statement *Another way to indicate a branch is through the switch keyword. *The switch construct allows branching on multiple outcomes. *Multiple-choice, provides a way of choosing between a set of alternatives. *General form: switch (expression) { case: constant1: statements; ... case: constantn: statements; default: statements; } *First expression (called the switch tag) is evaluated, and the outcome is compared to each of the numeric constants (called case labels), in the order they appear, until a match is found. The final default case is optional and is exercised if none of the earlier cases provide a match. 7
switch(op) // The 4 basic arithmetic operators using switch { import java.io.*; case '+': public class switch1 System.out.println("Sum="+(a+b)); { break; public static void main(String args[])throws IOException case '-': { System.out.println("Sub="+(a-b)); String s; char op; break; int a, b; case '*': BufferedReader aa=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Mul="+(a*b)); break; System.out.print("The First Number:="); case '/':; s=aa.readLine();//to read an input data; System.out.println(“Quo="+(a/b)); a=Integer.parseInt(s);//convert the given string in to integer System.out.print("The Second Number:="); break; s=aa.readLine();//to accept a string from the use default: b=Integer.parseInt(s); System.out.println("Invalid Operator"); System.out.print("An Operator:="); } } } op=(char)aa.read();//to accept a character from the user 8
2.2 Repetition/Looping Statements *Repetition statements are Java statements that allows us to execute specific blocks of code a number of times. There are three types of repetition statements, the while, do-while and for loops. 2.2.1 The while loop statement *The while loop is a statement or block of statements that is repeated as long as some condition is satisfied(holds true). *General form: while(expression) statements; inc/dec; *First expression (called the loop condition) is evaluated. If the outcome is nonzero then statement (called the loop body) is executed and the whole process is repeated. Otherwise, the loop is terminated. *Example: Adding the first 10 natural numbers(1-10) int i=1,sum=0; while(i<=10) sum+=i; i++; 9
*The do loop is similar to the while statement, except that its body is executed first and then the loop condition is examined. *The statements inside a do-while loop are executed several times as long as the condition is satisfied. *General form: do statement; while (expression); *First statement is executed and then expression is evaluated. If the outcome of the latter is nonzero then the whole process is repeated. Otherwise, the loop is terminated. *Example: int x = 0; int n; do { do { System.out.println(x); System.out.println(“Enter n: ”); x++; n=input.nextInt(); } System.out.println((n*n)); while (x<10); } 10 while (n!=0);
*The for loop allows execution of the same code a number of times. *General form: for(Initialization; LoopCondition; StepExpression) statement; *Initialization-initializes the loop variable. *LoopCondition - compares the loop variable to some limit value. *StepExpression - updates the loop variable. *First Initialization is evaluated. Each time round the loop, LoopCondition is evaluated. If the condition is true then statement is executed and StepExpression is evaluated. Otherwise, the loop is terminated. *Example: int i, sum=0; int i; for (i = 1; i <= n; i++) { sum += i; } } * Loops can be nested: for (int i = 1; i <= 3; ++i) for (int j = 1; j <= 3; ++j) System.ou.println(“(”+i+”, ”+j+”)”); for( i = 0; i < 10; i++ ) { System.out.print(i) 11
2.3 Branching Statements *Branching statements allows us to redirect the flow of program execution. Java offers three branching statements: break, continue and return. 2.3.1 The continue statement *The continue statement terminates the current iteration of a loop and instead causes to jump/proceed to the next iteration of the loop. *Example: int i, sum=0; for ( i = 1; i <= 10; i++ ) { // loop 10 times if ( i%3 == 0) {// if remainder of i divided by 3 is 0 continue; } sum+=i; System.out.println(i+ “ +“); } // end for 12 System.out.print( “= “+ sum );
*break causes immediate termination/exit from looping/repetition statements entirely. *Example: public class Break { public static void main(String[] args) { int num; num = 10; //loop while i is less than 6 for(int i=num; i >=1; i--) { if(i<6){ break; // terminate loop if i <6 } System.out.print(i + " "); } System.out.println("Countdown Aborted!"); } } 13
*The return statement is used to exit from the current method. *The flow of control returns to the statement that follows the original method call. *The return statement has two forms: one that returns a value and one that doesn't. *General form: return expression; *To return a value, simply put the value (or an expression that calculates the value after the keyword return. * For example: return sum; public double Sum(double x, double y) { return sum = x+y; } *The data type of the value returned by return must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value. * For example: return; 14
public class Power { private int x; // instance variables private int y; public Power(int a, int b) { //A constructor to Initializes instance variable x=a; y=b; } public double computePower() {//a method to access the data members double z; z=Math.pow(x,y); return z; } public static void main(String args[]) { Power p= Power(2,3); //Object creation with a parameterized constructor double result=p. computePower(); //Assign the return value of the function to the variable res System.out.println("Output :"+result); } } 15