Tuesday, 21 August 2018

Decision Making and Branching, Decision Making and Looping and Jumps in Loops


Decision Making and Branching

Decision Making with If statement
The general form of simple statement is
                        if(test expression)
{
Statement-block;
}
Statement –x;

            The statement block may be a single statement or a group of statements. If the test expression is true, the statement-block will executed; otherwise the statement-block will be skipped and the execution will jump to the statement-x
Example:
class gross
{
            public static void main(String []args)
            {
                        float gross_sal,net_sal=0.0f;
                        gross_sal=Float.valueOf(args[0]).floatValue();
                        if(gross_sal<10000.0f)
                                    net_sal=gross_sal;
                        if(gross_sal>=10000.0f)
                                    net_sal=gross_sal-0.15f*gross_sal;
                        System.out.println("Net Salary is Rs " + net_sal);
            }
}
Output:
D:\ >javac gross.java
D:\ >java gross 4.5
Net Salary is Rs 4.5
D:\ >java gross 12876.7
Net Salary is Rs 10945.195

If else Statement
the if-else statement is an extension of the simple if statement. The general form is..
            if(test expression)
                        {
                                    True-block statement(s)
                        }
            Else
                        {
                                    False-block statement(s)
}
Statement-x;
If the test expression is true then the true-block statement(s) immediately following the if statement are executed; otherwise the false-block statement(s) are executed. In either case, either true-block or false-block will be executed, not both.

The following is the example of

class evenodd
{
            public static void main(String []args)
            {
                        int num=Integer.parseInt(args[0]);
                        if(num%2==0)
                                    System.out.println(num + " is even");
                        else
                                    System.out.println(num + " is odd");   
            }
}
Output:
D:\ \programs>javac evenodd.java
D:\ \programs>java evenodd 6
6 is even
D:\ \programs>java evenodd 5
5 is odd

Nesting If Else Statement
When a series of decisions are involved, we may have to use more than one if..else statement in nested form as follows:
IF (logical-expression) 
{
   IF (logical-expression) {
      Statements  }
   ELSE
      {   statements  }
   statements
ELSE
   statements
   IF (logical-expression) {
      statements
   }
   statements
}
Program:
class nestedif
{
            public static void main(String []args)
            {
                        int a=325,b=712,c=478;
                        System.out.print("Largest value is:");
                        if(a>b)
                        {
                                    if(a>c)
                                    {
                                                System.out.print(a);
                                    }
                                    else
                                    {
                                                System.out.print(c);
                                    }
                        }
                        else
                        {
                                    if(c>b)
                                    {
                                                System.out.print(c);
                                    }
                                    else
                                    {
                                                System.out.print(b);
                                    }
                        }
            }
}
Output:
D:\ \programs>javac nestedif.java
D:\ \programs>java nestedif
Largest value is: 712

ElseIf Ladder
The conditions are evaluated from the top. As soon as the true condition is found, the statement associated with it is executed and the control is transferred to the statement-x. When all the n conditions become false, then the final else containing the default-statement will be executed.
The general form is:
if(condition1)
            Statement-1;
else if(condition 2)
            Statement –2;
else if(condition 3)
            Statement –3;
----------------------
else if(condition n)
            statement –n;
else
            default statement;
statement-x;
Program:
class elsif
{
            public static void main(String []args)
            {
                        int per=Integer.parseInt(args[0]);
                        char grade;
                        if(per>=90)
                                    grade='A';
                        else if(per>=75)
                                    grade='B';
                        else if(per>=60)
                                    grade='C';
                        else if(per>=50)
                                    grade='D';
                        else
                                    grade='F';
                        System.out.println("Grade=" +grade);
            }
}
Output:
D:\ \programs>javac elsif.java
D:\ \programs>java elsif 67
Grade=C

The switch Statement
The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found a block of statements associated with that case is executed. The general form of the switch statement is as shown below:

                                    switch(expression)
                                    {
                                                case value 1:
                                                                                    block1;
                                                                                    break;
                                                case value2:
                                                                                    block2;
                                                                                    break;
                                                ………………
                                                ………………
                                                default:
                                                                                    default-block;
                                                                                    break;
                                    }
Example:
class color
{
public static void main(String args[])
{
String ch=args[0];
char choice=ch.charAt(0);
System.out.println("Press B for Blue  ");
System.out.println("Press G for Green ");
System.out.println("Press R for Red   ");

switch(choice)
{
case 'B':
case 'b':            System.out.println("You choose Blue color");
                        break;
case 'G':
case 'g':            System.out.println("You choose Green color");
                        break; 
case 'r':
case 'R':           System.out.println("You choose Red color");
                        break;

default:            System.out.println("invalid choice");
}
}
}

The ?: operator.
The value of a variable often depends on whether a particular Boolean expression is or is not true and on nothing else. For instance one common operation is setting the value of a variable to the maximum of two quantities  Is
 (a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression, which returns a boolean value.
Example:
class conditional
{
public static void main(String args[])
{
int a,b;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
int max;
max=(a>b)? a : b;
System.out.println("max="+max);
}
}

Decision Making and Looping
The while statement
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.
Syntax:   While(expression){
               Statements; }
Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:
class WhileDemo {
     public static void main(String[ ] args){
          int count = 1;
          while (count < 11) {
               System.out.println("Count is: " + count);
               count++;
          }
     }
}

The do-while statement
The Java programming language also provides a do-while statement, which can be expressed as follows:
Syntax:           do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:
class DoWhileDemo {
     public static void main(String[] args){
          int count = 1;
          do {
               System.out.println("Count is: " + count);
               count++;
          } while (count <= 11);
     }
}

The for statement

The for statement provides a compact way to iterate over a range of values.
The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
    statement(s)
}
When using this version of the for statement, keep in mind that:
  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
The following program, For Demo, uses the general form of the for statement to print the numbers 1 through 10 to standard output:
class ForDemo 
{
     public static void main(String[] args){
          for(int i=1; i<11; i++){
               System.out.println("Count is: " + i);
          }
     }
}

Jumps in Loops
Java supports three types of jumping statements:
  • Break
  • Continue
  • Return

Break:
Some times we need to exit from a loop before the completion of the loop then we use break statement and exit from the loop and loop is terminated.
Continue:
Sometimes we do not need to execute some statements under the loop then we use the continue statement that stops the normal flow of the control and control returns to the loop without executing the statements written after the continue statement.
Diff between break and continue:
There is the difference between break and continue statement that the break statement exit control from the loop but continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions.
Examples for break and continue
class star
{
public static void main(String args[])
{
loop1: for(int i=1;i<=100;i++)
{
System.out.println();
if(i>10) break;
for(int j=1;j<=100;j++)
{
System.out.print("*");
if(i==j)continue loop1;
}
}
}
}

Return Statement:
It is used to explicitly return from the current method. The flow of control transfers back to the caller of the method. To return a value, simply put the value after the return keyword.


No comments: