Page 193 - Computer science 868 Class 12
P. 193

In the above example, the variables var1 and var2 are assigned with the values 1 and 10 respectively and after each
                 iteration var1 is increased by 1 and var2 is decreased by 1.

                     7.4  JUMP STATEMENTS
                 Sometimes it is necessary to exit from a loop or a switch statement before the condition results in false. This is required
                 according to the need of the logic of the program. This type of statement which transfers the execution control of the
                 program code from one point to another point depending on a certain condition is called a Jump Statement.

                 In Java, there are three types of Jump Statements.
                 •  break
                 •  continue
                 •  return
                 Let us study this in detail.


                 7.4.1 break
                 The break statement is used to exit from the loop and switch case statement. As soon as the break statement is
                 encountered, the control shifts to the next line just after the switch case or the loop.

                 For example:
                 1.  Break in switch case: Input the length and breadth of a rectangle and calculate the area or perimeter according to
                   the user’s choice.
                    class switchcase
                    {
                      public static void main(char ch, int length, int breadth)
                      {
                        switch(ch)
                        {
                                  case 'A':
                                       System.out.println("Area : " + (length*breadth));
                                       break;
                                  case 'P':
                                       System.out.println("Perimeter : " + (2*(length + breadth)));
                                       break;
                                  default:
                                       System.out.println("Your choice is wrong");
                         }
                      }
                    }
                 2.  Break in loop: Input some numbers and print the sum of the positive numbers only. If the user enters zero, the loop
                   terminates and the result is displayed.

                    import java.util.*;
                    class sum_of_even
                    {   public static void main()
                        {   Scanner sc=new Scanner(System.in);
                            int n, sum=0;
                            while(true)
                            {



                                                                                                                       191
                                                                                                 Statements and Scope  191
   188   189   190   191   192   193   194   195   196   197   198