Friday 1 March 2013

Control Statements


Depending on the results of computations the flow of control may require to jump from one part of the program to another part, such jumps are called Control statements.  The control statements are of two categories.
1.      Decision (Conditional) control statements
2.      Loop control statements
3.      Jump control statements

1. Decision (Condition) Control statements: In decision control statements, depending on the result of evaluation of an expression a statement or block of statements are executed.  The condition involves boolean values either true or false.  Java provides the following decision control statements.
a)      if statement
b)      if-else statement
c)      nested if-else statement
d)     switch
a) if statement: The if statement conditionally process the statements when the specified test condition is true.
            Syntax:            if(condition)
                                    {
                                                      // Block of statements
                                    }

            Flowchart:      

 















            Here, if the condition is true then block of statements are executed.  Otherwise, block of statements are not executed and the control is passed to the next statements available after the block statements.
            The statements are either simple or compound statements.  If the statements are single statement then they ended with a semicolon.  If the statements are compound statements then they are placed in between the left and right curly braces.

Example:

class if1
{
            public static void main(String[] args)
            {
                        int a=6,b=4;
                        if(a>b)
                        System.out.println("a is big");
            }
}

b) if-else statement: In if-else statement general form is as
            Syntax:            if (condition)
                                    {
                                                      //true block statements
                                    }
                                    else
                                    {
                                                      //false block statements
                                    }
 
            Flowchart:



 












Next statements
 
 




            Here, first the test condition is evaluated.  If the condition is true, then true block statements are executed otherwise false block statements are executed.
            The statements are either simple or compound statements.  If the statements are single statement then they ended with a semicolon.  If the statements are compound statements then they are placed in between the left and right curly braces.

Example:

class if2
{
            public static void main(String[] args)
            {
                        int a=2,b=4;
                        if(a>b)
                        System.out.println("a is big");
                        else
                        System.out.println("b is big");
            }
}

c) Nested if-else statement: The if-else statement is placed within another if-else statement such methods are called nested if-else statement.
            Syntax:            if (condition1)
                                    {
                                    else if(condition2)
                                    {
                                                      //block1 statements
                                    }
                                    else
                                    {
                                                      //block2 statements
                                    }
                                    }
                                    else
                                    {
                                                      //block3 statements
                                    }


Lab Program1: Write a program to print the roots of a quadratic equation ax2+bx+c=0

import javax.swing.JOptionPane;
import java.text.DecimalFormat;
class lab1
{
            public static void main(String[] args)
            {
            double a,b,c,dis,root1,root2,p;
            DecimalFormat d=new DecimalFormat("0.00");
            a=Double.parseDouble(JOptionPane.showInputDialog("Enter a value"));
            b=Double.parseDouble(JOptionPane.showInputDialog("Enter b value"));
            c=Double.parseDouble(JOptionPane.showInputDialog("Enter c value"));
            dis=(b*b-4*a*c);
            if(dis==0)
            {
            System.out.println("Roots are real and equal");
            root1=-b/(2*a);
            System.out.println("Root1="+(d.format(root1)));
            System.out.println("Root2="+(d.format(root1)));
            }
            else if(dis>0)
            {
            System.out.println("Roots are real and different");
            p=Math.sqrt(dis);
            root1=(-b+p)/(2*a);
            root2=(-b-p)/(2*a);
            System.out.println("Root1="+(d.format(root1)));
            System.out.println("Root2="+(d.format(root2)));
            }
            else
            System.out.println("Roots are imaginary");
            }
}

d) switch statement: The switch statement allows section among the multiple section of a code depending on the value of an expression.  The objective is to check several possible constant values for an expression.
            Syntax:            switch (expression)
                                    {
                                    case value1:     block1 statements
                                                            break;
                                    case value2:     block2 statements
                                                            break;
                                    .
                                    .
                                    default:            default block statements
                                    }

   

 























            First, the switch statement evaluates the expression and check whether the evaluated value is coinciding with any case value or not.  If any value is coinciding, it executes that particular block of statements until the break statement is reached.  After executing the statements the control is transferred out of the statements that are available after the switch statement.
            If any value is not coinciding with the case value then it executes default block statements.  Default block is an optional.
Note: case values are either integer constant or character constant.

Example:

class if4
{
            public static void main(String[] args)
            {
                        int rno;
                        rno=Integer.parseInt(args[0]);
                        switch(rno)
                        {
                        case 1:System.out.println("RED");
                                                      break;
                        case 2:System.out.println("GREEN");
                                                      break;
                        case 3:System.out.println("BLUE");
                                                      break;
                        default:System.out.println("Select 1,2 or 3 only");
                        }
            }
}

Example:

class if5
{
            public static void main(String[] args)
            {
                        char rno='t';
                        switch(rno)
                        {
                        case 'a':System.out.println("RED");
                                                      break;
                        case 'b':System.out.println("GREEN");
                                                      break;
                        case 'c':System.out.println("BLUE");
                                                      break;
                        default:System.out.println("Select 1,2 or 3 only");
                        }
            }
}


2. Loop Control Statements: A Loop statement allows to run a statement or block of statements repeatedly for a certain number of times.  The repetition is continues while the condition is true.  When the condition becomes false, then loop ends and control passed to the next statements following the loop.  Repetitive execution of statements is called looping.  Java provides three types of loop control statements.
a)      while statement
b)      do-while statement
c)      for statement
a) while statement: while loop executes the statements repeatedly as long as a given condition becomes true.  When the condition becomes false the control immediately pass to the next statements available after the loop statements.
            Syntax:            while (condition)
                                    {
                                                      //statements
                                    }
        

 

           

 












            The statements are either simple or compound statements.  If the statements are single statement then they ended with a semicolon.  If the statements are compound statements then they are placed in between the left and right curly braces.

Lab Program2: Write a program to print the first n fibonacci sequence numbers

class lab2
{
            public static void main(String[] args)
            {
                        int f0=1,f1=1,i=3,f2,n;
                        n=Integer.parseInt(args[0]);
                        System.out.println(f0);
                        System.out.println(f1);
                        while(i<=n)
                        {
                        f2=f0+f1;
                        System.out.println(f2);
                        f0=f1;
                        f1=f2;
                        i++;
                        }
            }
}


b) do-while statement: In do-while loop statements, first the control executes the statements then it checks for the condition.  The statements are executed repeatedly as long as a given condition becomes true.  If the condition becomes false then the control comes out from the loop and executes the statements available after the loop statements.
            Syntax:            do
                                    {
                                                      //statements
                                    } while (condition);


     


 














            The statements are either simple or compound statements.  If the statements are single statement then they ended with a semicolon.  If the statements are compound statements then they are placed in between the left and right curly braces.  The main difference between while and do-while statement is do-while statement executes the statements at least once even the condition becomes false.

Example: Write a program to check whether a given number is Armstrong number (153) or not

class labd
{
            public static void main(String[] args)
            {
                        int x,n,temp,sum=0;
                        n=Integer.parseInt(args[0]);
                        temp=n;
                        do
                        {
                        x=n%10;
                        sum=sum+x*x*x;
                        n=n/10;
                        }while(n>0);
                        if(sum==temp)
                        System.out.println("Number is armstrong");
                        else
                        System.out.println("Number is not armstrong");
            }
}

c) for statement: The for statement also repeat a statement or compound statements for a specified number of times.  The general form of for statement is as
            Syntax:            for (initialization;condition;increment/decrement)
                                    {
                                                      //statements
                                    }
            Flowchart:

 
















            Initialization is the start with the assigning value to the variable and it executes only once at the start of the loop.  Then the control checks for the test condition.
            In condition section, if the condition becomes true then the control pass to the block of statements and executed.  After executing the statements the control pass to the increment/decrement section.  After incrementing/decrementing the variable again the control is passed to the condition section.  This procedure is repeated as long as the condition becomes true.
            If the condition becomes false, the control passes out of the loop statements.

Note:   1. Multiple initializations are possible by comma operator.
                        Ex:       for( i = 0,j = 5; i<n; i++, j--)
            2. At the place of condition section, it is also possible to use relational expressions

Example:

Lab Program3: To print all prime numbers between a given range

import javax.swing.JOptionPane;
class lab3
{
            public static void main(String[] args)
            {
                        int n,j,x,count;
                        //n=Integer.parseInt(args[0]);
n=Integer.parseInt(JOptionPane.showInputDialog("Enter range"));
                        for(int i=1;i<=n;i++)
                        {
                        x=i;
                        count=0;
                        j=2;
                        while(j<x)
                        {
                        if(x%j==0)
                        {
                        count=1;
                        break;
                        }
                        j++;
                        }
                        if(count==0)
                        System.out.println(x+"is prime");
                        }
                        }
}

3. Jump Control Statements: Java provides the following Jump Control statements.
a)      break statement
b)      continue statement
c)      return statement
d)     exit statement

a) break statement: break statement executed in a while, do-while, for or switch statements causes immediate exist from that structure.  It can be used in two ways as unlabeled break and labeled break statement.

Unlabeled break statement:
            Syntax:            break;
            Example:         for(int k=1;k<=10;k++)
                                    {
                                    if(k= =5)
                                    break;
                                    System.out.println(k);
                                    }
            O/P:                 1 2 3 4

Labeled break statement: To break out of nested structures, we can use the labeled break statements.  This statement, when executed in a while, do-while and for statements causes immediate exit from that structure and any number of enclosing repetition structures.  Program execution resumes with the first statement after the enclosing labeled compound statement.
            Example:
           
            class ex
{
            public static void main(String[] args)
            {
                        stop:
                        {
                        for(int row=1;row<=10;row++)
                        {
                        for(int col=1;col<=5;col++)
                        {
                        if(row==3)
                                    break stop;
                                    System.out.print("* ");
                                    }
                                    .out.println("\n");
                                    }
                                    }
                        }
            }

            O/P:    * * * * *
                        * * * * *
           
b) continue statement: continue statement executed in a while, do-while or for statements skip the remaining statements in the body of that structure and proceeds with the next iteration of the loop.  It can be used in two ways as unlabeled continue and labeled continue statement.

Unlabeled continue statement:
            Syntax:            continue;
            Example:         for(int k=1;k<=10;k++)
                                    {
                                    if(k= =5)
                                    continue;
                                    System.out.println(k);
                                    }
            O/P:                 1 2 3 4 6 7 8 9 10

Labeled continue statement: The labeled continue statement when executed in a repetition structure skips the remaining statements in that structure body and any number of enclosing repetition on structure and proceeds with the next iteration of an enclosed labeled repetition.
            Example:
           
            class ex
            {
            public static void main(String[] args)
            {
                        stop:
                        for(int row=1;row<=4;row++)
                        {
                        for(int col=1;col<=3;col++)
                        {
                        if(col==2)
                        continue stop;
                        System.out.print(col);
                        }
                        System.out.println("\n");
                        }
            }
            }

            O/P:    1111

c) return statement: The return statement is used to explicitly return from a method.  This causes program control to transfer back to the caller of the method.  The return statement immediately terminates the method in which it executes.
            Syntax:            return;

d) exit statement: The method exit( ) is defined in System package.  The purpose of exit is to terminate the program with a specific exit code.
            Syntax:            System.exit(exit_code);
The program finish normally by placing exit_code as ‘0’ other value means error.
            Example:         System.exit(0);
 
 
 

No comments:

Post a Comment