4 Working with Decision-making Statement in Java

4.1 INTRODUCTION

Decision-making statements are needed to alter the sequence of statements in a program depending on certain circumstances. In the absence of decision-making statements, a program executes in a serial fashion on statement by statement basis, which have been presented in programs given in earlier chapters. This chapter deals with statements that control the flow of execution on the basis of some decision. All the control flow constructs have their conditions which return Boolean value. Depending on truth or falsity, the decision is taken. Decision can be made on the basis of success or failure of some logical condition. They allow one to control the flow of program. The statements inside source files are generally executed from top to bottom, in the order they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping and branching, enabling the program to conditionally execute particular blocks of code. This chapter describes the decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) supported by the Java programming language. Java language supports the following decision-making/control statements:

1.   The if statement

2.   The if-else statement.

3.   The if-else-if statement.

4.   The switch-case statement.

All theses decision-making statements check the given condition and then execute its sub-block if the condition happens to be true. On falsity of condition, the block is skipped. (A block is a set of statements enclosed within opening brace and closing brace {and}). All control statements use a combination of relational and logical operators to form conditions as per the requirement of the programmer.

4.2 THE if STATEMENT

The if statement is the most basic of all the control flow statements. It tells the program to execute a certain section of code only if a particular test evaluates to true. The general syntax of if statement is given as follows:

   if (condition)
   {
           statements;
           statements;
           ..........  ;
           ..........  ;
   }

The if statement is used to execute/skip a block of statements on the basis of truth or falsity of a condition. The condition to be checked is put inside the parenthesis which is preceded by the keyword if.

For example, consider the following code:

int x = 16;
if(x > 0)
System.out.println("x is greater than 0");

In this code, the condition is x > 0 which is checked using if. As the value of x is greater than 0, the condition x > 0 is true. If no braces are present after if, the first statement after if depends on if. So it is executed and the output becomes ' x is greater than 0'.

In case condition is false, the statement after if will be skipped and there will be no output. An example is given below.

x = 30;
if (x < 15)
System.out.println("x is less than 15");
System.out.println("x is greater than or equal to fifteen");

Here as the condition is false and there are no braces after if, only the first statement after if will be skipped and the next statement will be executed. So the output will be ' x is greater than or equal to fifteen'.

In case no condition is specified in if statement, i.e., the expression is given as if (x), it is considered equivalent to the condition if (x! = false). The condition if (! x) is considered equivalent to the condition if (x = = false). In both the cases, x must be a Boolean variable.

/*PROG 4.1 DEMO OF IF VER 1 */
import java.io.*;
import java.util.*;
class JPS1
{
   public static void main(String args[])
   {
       Scanner sc = new Scanner (System.in);
       System.out.print("

Enter an integer number:=");
       int x = sc.nextInt();
       if (x>=100)
       {
          System.out.println("
 x is greater or equal to 100
");
          System.out.println("
 You think better
");
       }
       System.out.println("
 x is less than 100
");
   }
}
OUTPUT:

First Run)
Enter an integer number:=15
x is less than 100
(Second Run)
Enter an integer number: = 105
x is greater or equal to 100
You think better
x is less than 100

Explanation: Here the statements after if expression are put in the braces. When the if condition is true, all the statements within the braces get executed; in case the condition is false, the statements within the braces are skipped. Regardless of true/falsity of if condition, the remaining statements are executed and so is the output. To execute only if-dependent statements, one will have to use if-else construct or terminate the program after the execution of if block. The second alternative is shown in the next program.

/*PROG 4.2 DEMO OF IF VER 3 */
class JPS3
{
   public static void main(String args[])
   {
         boolean x = false;
         if (x)
         {
                System.out.println("
 X is greater or equal
                                                  to 100");
                System.out.println("
 You think better");
                System.exit(0);
         }
         System.out.println("
 X is less than 100");
   }
}
OUTPUT:

X is less than 100

Explanation: In Java, if(x) is equivalent to if(!x 5 false) and x can only be Boolean value. Similarly, if(!x) is equivalent to if(x = = false).

4.3 THE if-else STATEMENT

The if-else statement provides a secondary path of execution when an 'if clause evaluates to false. In all the above programs, the other side of if condition was not written, i.e., no action was taken when the condition fails. The if-else construct allows one to do this as shown below:

   if(condition)
   {
   statements;
   statements;
   .........;
   }
   else
   {
   statements;
   statements;
   .........;
   }

If the condition within if command is true, all the statements within the block following if are executed else they are skipped and statements within the else block get executed. In any case either if block or else block is executed. For example, consider the following code:

if(x>=0)
System.out.println("x greater than equal to 0");
else
System.out.println("x less than 0");

Check out few programs given below:

/*PROG 4.3 PROGRAM TO CHECK NUMBER IS EVEN OR ODD */
import java.io.*;
import java.util.*;
class JPS4
{
   public static void main(String args[])
   {
          int x;
          Scanner sc = new Scanner(System.in);
          PrintStream pr = System.out;
          pr.println("
 Enter an Integer number");
          x = sc.nextInt();
          if (x % 2 == 0)
                 pr.println("Number " + x + " is even");
          else
          pr.println("Number " + x + " is odd");
   }
}
OUTPUT:

(First Run)
Enter an Integer number
14
Number 14 is even
(Second Run)
Enter an Integer number
13
Number 13 is odd

Explanation: As discussed earlier, System.out is an object of class PrintStream so it is assigned to a reference pr of PrintStream type. Now instead of writing System.out.println, you can write pr.println. If the if condition x%2 = = 0 is true, the number is even, else the number is not even. The else part executes only when if part is false and vice-versa. In the program both if and else parts contain just one statement to be dependent on them so braces are not needed; however, if you put the braces there will not be any harm.

/*PROG 4.4 MAXIMUM OF TWO NUMBERS */
import java.io.*;
import java.util.*;
class JPS5
{
   public static void main(String[] args)
   {
          int x, y;
   Scanner sc = new Scanner(System.in);
          System.out.print("
Enter first number :=");
          x = sc.nextInt();
          System.out.print("
Enter second number:=");
          y = sc.nextInt();
          if (x == y)
          {
                 System.out.println("
Both are equal");
                 System.exit(0);
          }
          if (x > y)
                 System.out.println("
Maximum is " + x);
          else
                 System.out.println("
Maximum is " + y);
   }
}
OUTPUT:

(FIRST RUN)
Enter first number      :=40
Enter second number     :=40
Both are equal
(Second Run)
Enter first number      :=40
Enter second number     :=60
Maximum is 60

Explanation: Program is self-explanatory.

4.4 NESTING OF if-else STATEMENT

Nesting of if-else means one if-else or simple if as the statement part of another if-else or simple if statement. There may be various syntaxes of nesting if-else. The most commonly used are given in Figure 4.1 as shown below:

1.   In the first form of nesting of if-else, if the first if condition is true then the inner if-else block is executed. In case the condition is false, the entire inner if-else block is skipped and no action is taken.

2.   The second form is the variation of the first form, where if the outer if condition is false, outer else block gets executed. In the outer else block there is no inner if or if-else part.

3.   In the third form, we have inner if-else blocks for execution in both outer if and outer else blocks.

images

Figure 4.1 Different types of nested if-else statement

/*PROG 4.5 MAXIMUM OF THREE NUMBERS USING NESTING OF IF-ELSE STATEMENT */
import java.io.*;
import java.util.*;
class JPS6
   {
          public static void main(String args[])
          {
             int a, b, c, d = 0;
             Scanner sc = new Scanner(System.in);
             System.out.println("
Enter three number");
             a = sc.nextInt();
             b = sc.nextInt();
             c = sc.nextInt();
             if ((a == b) && (a == c))
                 System.out.println("All three are equal
");
             else
             {
                 if (a > b)
                 {
                       if (a > c)
                           d = a;
                       else
                           d = c;
                 }
                 else
                 {
                       if (b > c)
                           d = b;
                       else
                           d = c;
                 }
             }
             System.out.println("Maximum is " + d);
   }
}
OUTPUT:

Enter three number
23 56 78
Maximum is 78

Explanation: If the numbers are equal the first if condition is true else else block is executed. In the else part, there is one more if-else. If a > b is true then inside this if block, using one more if-else it is checked whether a > c, if this is so then a is greater else c is greater.

If the first if condition is false in the else block then else part of the inner if executes which means b > a. Inside this inner else one more if-else checks whether b > c, if it is so then b is greater else c is greater.

4.5 else-if LADDER

The general syntax of else-if ladder is shown below:

if (condition)
  statements;
    else if(condition)
      statements;
        else if (condition)
          statements;
          ................  ;
          ................  ;
          ................  ;
else
  statements;

If the first if condition is satisfied then all its related statements are executed and all other else-if's are skipped. The control reaches to first else-if only if the first if fails. This is same for second, third and other else-if's depending on what the program required. That is, out of this else-if ladder only one if condition will be satisfied.

For example, consider the following code:

if(marks>=90)
 System.out.println("Grade is A");
   else if(marks>=80 && marks<90)
     System.out.println("Grade is B");
       else if(marks>=70 && marks<80)
         System.out.println("Grade is C");
           else if(marks>=60 && marks<70)
             System.out.println("Grade is D");
               else if(marks>=50 && marks<60)
                 System.out.println("Grade is E");
else
  System.out.println("Fail");

If marks ≥ 90, first if will be true, 'Grade is A' will be displayed and the remaining else-ifs will be skipped. In case first if is false, first else-if will be checked. If it is true then 'Grade is B' will be displayed and the remaining else-ifs will be skipped. The same analogy applies for other else-ifs.

A few programs are given below:

/*PROG 4.6 FINDING ROOTS OF THE QUADRATIC EQUATION */
import java.io.*;
import java.util.*;
class JPS8
{
   public static void main(String args[])
   {
          double a, b, c, r1, r2, dis;
          Scanner sc = new Scanner(System.in);
          System.out.print("

Enter value of A :=");
          a = sc.nextDouble();
          System.out.print("Enter value of B :=");
          b = sc.nextDouble();
          System.out.print("Enter value of C :=");
          c = sc.nextDouble();
          dis = b * b - 4 * a * c;
          if (dis < 0)
                 System.out.print("
Roots are imaginary
");
          else if (dis == 0)
          {
                 System.out.print("
Roots are equal
");
                 r1 = -b / (2 * a);
                 r2 = b / (2 * a);
                 System.out.print("
Root1 or r1 := "
                                    +r1+"
");
                 System.out.print("
Root2 or r2 := "
                                    +r2+"
");
          }
          else
          {
                 System.out.println("
 Roots are
                                        unequal
");
                 r1 = (-b + Math.sqrt(dis)) / (2.0 * a);
                 r2 = (-b + Math.sqrt(dis)) / (2.0 * a);
                 System.out.print("
Root1 or r1:= "
                                     +r1+"
");
                 System.out.print("
Root2 or r2:= "
                                     +r2+"
");
          }
   }
}
OUTPUT:

Enter value of A :=2
Enter value of B :=6
Enter value of C :=2
   Roots are unequal
Root1 or r1:= -0.3819660112501051
Root2 or r2:= -0.3819660112501051

Explanation: The quadratic equation in mathematics is given as follows:

AX2 + BX + C = 0,

where, A, B and C are constants. The solution of the equation comprises two roots as power of X is 2.

R1 = (-B + sqrt (B * B - 4 * A * C)) / 2 * A

R2 = (-B - sqrt (B * B - 4 * A * C)) / 2 * A

The expression B * B - 4 * A * C is known as discriminant (say dis), and on the basis of its value the roots are determined as equal (dis = = 0) imaginary (dis < 0) or unequal (dis > 0) as shown in the above program.

In the program, the value of three constants are taken as output using A, B and C and the value of dis is calculated.

/*PROG 4.7 TO DETERMINE THE STATUS OF ENTERED CHARACTER */
import java.io.*;
class JPS9
{
   public static void main(String args[])
   {
   char c;
   try
   {
          DataInputStream input;
          input=new DataInputStream(System.in);
          System.out.println("Enter a character");
          c=(char)(input.read());
          if(c>=65 && c <=90)
              System.out.println("You have entered
                                  uppercase letter
");
          else if(c>=97&&c<=122)
              System.out.println("You have entered
                                  lowercase letter
");
          else if(c>=48 && c<=57)
              System.out.println("You have eneterd a digit
");
          else
              System.out.println("You have entered a
                                  special symbol
");
      }
          catch(Exception eobj)
          {
              System.out.println("ERROR!!!!");
          }
      }
}
OUTPUT:

(First Run)
Enter a character
A
You have entered uppercase letter
(Second Run)
Enter a character
a
You have entered lowercase letter
(Third Run)
Enter a character
2
You have entered a digit
(Fourth Run)
Enter a character
$
You have entered a special symbol

Explanation: The ASCII/unicode values is from 97 to 122 (inclusive both) for lowercase alphabets and 65 to 90 (inclusive both) for uppercase alphabets. It is checked whether the entered character is within these two ranges using else-if ladder. Similarly ASCII/Unicode values for digits are from 48 to 57 (inclusive both), so character entered is also checked with this range. If all the three conditions fail then the character entered must be a special symbol.

4.6 SWITCH-CASE STATEMENT

Switch-case can be used to replace else-if ladder construct. The switch statement allows for any number of possible execution paths. A switch works with the byte, short, char and int primitive data types. It also works with enumerated types and a few special classes that 'wrap' certain primitive types: Character, Byte, Short and Integer (discussed in simple data objects). Its general syntax is as follows:

switch (expression)
{
case choice1:
             statements;
             break;
case choice2:
             statements;
             break;
case choice3:
             statements;
             break;
........................
........................
........................
case choice N:
             statements;
             break;
default:
             statements;
}

The expression may be any integer or char type which yields only char or integer as result. choice1, choice2 and choice N are the possible values which are going to be tested with the expression. In case none of the values from choice 1 to choice N matches with the value of expression, the default case is executed. Writing default is optional. For example:

  switch(num)
  {
  case0:
         System.out.println("You have entered ZERO
");
         break;
  case1:
         System.out.println("You have entered ONE
");
  break;
  case2:
         System.out.println("You have entered TWO
");
         break;
  default:
  System.out.println("Other than 0,1,2
");
  }

The condition to be checked is placed inside the switch enclosed in parenthesis. Here num is checked against different case expressions. The different values against which condition is checked are put using case statement. In the first case, value of num is checked against 0. This is similar to writing if (num=="). The colon ':' after case is necessary. If the value of num is zero then the first case matches and all the statements under that get executed. Similarly, if the value of num is 1, the second case gets executed and the same applies to the rest of the case statements. A break statement is needed to ignore the rest of the case statements and come out from switch block in case a match is found. If none of the case matches then default gets executed. It is to be noted that no break is used after the default as the switch block ends after the default: case. Writing default is optional and not necessarily be put at the end of switch-case. It can be put anywhere within the switch-case; in that case, one will have to write break after the default.

A few programs are given below:

/*PROG 4.8 DEMO OF SWITCH-CASE VER 1 */
import java.io.*;
import java.util.*;
class JPS10
{
   public static void main(String args[])
   {
          Scanner sc=new Scanner(System.in);
          System.out.print("
 Enter 0, 1, or 2 :=");
          int num = sc.nextInt();
          switch (num)
          {
            case 0:
                   System.out.println("
 U entered zero
");
                   break;
            case 1:
                   System.out.println("
 U entered one
");
                   break;
            case 2:
                   System.out.println("
 U enterd two
");
                   break;
            default:
                   System.out.println("
 U entered other
                                    than 0,1,or 2
");
         }
   }
}
OUTPUT:

(First Run)
Enter 0, 1, or 2 :=0
U entered zero
(Second Run)
Enter 0, 1, or 2 :=1
U entered one
(Third run)
Enter 0, 1, or 2 :=2
U enterd two
(Fourth Run)
Enter 0, 1, or 2 :=3
U entered other than 0,1,or 2

Explanation: There is no break statement in case 1, so both case 1 and case 2 are assumed to be true and so is the output. In fact, due to the absence of break statement in the second case, rest of the statements are considered part of the second case till a break is not found. Break in case 2 causes control to come out from switch. If break were not in case 2 also then default would have got executed too.

4.7 INTRODUCTION OF LOOPS

Looping is a process in which a set of statements are executed repeatedly for a finite or infinite number of times. Java provides three ways to perform looping by providing three different types of loop. Looping can be synonymously called iteration or repetition. Loops are the most important part of almost all the programming languages such as C, C+ +, Java, VB, C#, and Delphi.

In many practical examples some repetitive tasks have to be performed like finding average marks of students of a class, finding maximum salary of a group of employees, counting numbers, etc.

A loop is a block of statements which are executed again and again till a specific condition is satisfied. Java provides three loops to perform repetitive actions: while, for and do-while.

To work with any type of loop, three things have to be performed: loop control variable and its initialization; condition for controlling loop; and increment/decrement of control variable.

4.7.1 The while Loop

The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as follows:

while (expression/condition)
{
 statement(s);
}

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.

The statement inside {} is called the body of the while loop. If no braces are there then only the first statement after while is considered as the body of the while loop. All the statements within the body are repeated till the condition specified in the parenthesis in while is satisfied. As soon as the condition becomes false, the body is skipped and control is transferred to the next statement outside the loop. There should be no semicolon after the while. The while loop is also called top-testing or entry-controlled loop as the control enters into the body of the loop only when initial condition turns out to be true. If in the beginning of the while loop, condition is false then control never enters into the body of the while loop.

int t=1;        //initial value of loop control variable t
while(t<=10)    //condition in the while
{
 System.out.print(t+" ");
 t++;
}

In the while loop, the condition stated is t < =10 where t is called loop control variable. Initially, the value of t is 1. This value is compared with 10, which is true so control reaches into the while loop body, and System.out.println statement within the loop executes and prints the value of t. Note that the statement within braces are known as the body of the while loop. If no braces are present, the first statement after the while is considered the body of the while loop. Then t is incremented by 1, i.e., becomes 2. Control reaches back to the condition of the while loop, which is true again. This process continues and when the value of t becomes 11, the condition in the while loop becomes false and control comes out of the loop. The output of the above code will be as follows:

1  2  3  4  5  6  7  8  9  10

Now consider the example of printing number backwards by doing a small change in the above program:

int t=10;       //initial value of loop control variable t
while(t>=1)     //condition in the while
System.out.print(t--+" ");

In this example, the loop control variable t is decremented after printing its value within the expression t itself. The point to be noted is braces were not used; however, there is no problem even if it is used. In the above code if one forgets to decrement the value of t then infinite loop follows.

Similarly, the loop counter may be incremented or decremented by any value depending on the requirement. But while incrementing the counter, test condition must use < = or < operator and in decrementing test condition must use > = or > operator. This is very common programming mistake done by most of the beginners. This mistake is better avoided.

As stated in the beginning of the section, there should be no semicolon after the while loop. But what if there is a semicolon after the while loop? Consider the following code:

int t=5;
while(t>=1);
System.out.println(t-- +" ");

The semicolon (;) after the while is called empty statement which is also the body of the while loop since no braces are there. Empty statement means doing nothing, so while loop does nothing and keeps checking the value of t against 1; as t is 5 initially, the condition remains true forever and the infinite loop follows.

The programs given below will help understand the working of the while loop better:

/*PROG 4.9 GENERATING TABLE OF A GIVEN NUMBER */
import java.io.*;
import java.util.*;
class JPS12
{
   public static void main(String args[])
   {
          int num, t = 1, value;
          Scanner sc = new Scanner(System.in);
          System.out.print("
Enter any +ve number:= ");
          num = sc.nextInt();
          System.out.println("
The table of "+num+" is
                                 given below
");
          while (t <= 10)
          {
                value = num * t;
                System.out.println(num + " x " + t + " = " +
                                   value);
                t++;
          }
   }
}

OUTPUT:

Enter any +ve number: = 5
The table of 5 is given below

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

Explanation: Any +ve number is taken as input. The number n is multiplied by 1 through 10 inside the loop and the loop counter; the number and value are displayed by formatting as to produce the desired output.

/*PROG 4.10 MAXIMUM OF N ELEMENTS */
import java.io.*;
import java.util.*;
class JPS13
{
   public static void main(String args[])
   {
          int n, max, t=1, m;
          Scanner sc = new Scanner(System.in);
          System.out.println("Enter how many numbers");
          n = sc.nextInt();
          System.out.println("Enter the number");
          m = sc.nextInt();
          max = m;
          while (t<=n-1)
          {
                 System.out.println("Enter the number");
                 m = sc.nextInt();
                 if(max<m) ;
                 max=m;
                 t++;
          }
          System.out.println("Maximum element is " + max);
   }
}
OUTPUT:

Enter how many numbers:=5
Enter the number:=12
Enter the number:=15
Enter the number:=17
Enter the number:=18
Enter the number:=145
Maximum element is:= 145

Explanation: Initially the number of elements taken is n. The first number is taken outside the loop and assumed to be maximum; this number is stored in max. The remaining numbers are taken inside the loop. On each iteration, the number is compared with the max. If the max is less than the number taken, the number will be the maximum one. This is checked through if statement. In the end when control comes out from while loop, max is displayed.

/*PROG 4.11 FINDING REVERSE OF A NUMBER */
import java.io.*;
import java.util.*;
class JPS14
{
   public static void main(String args[])
   {
          int orig, rev = 0, r;
          Scanner sc = new Scanner(System.in);
          System.out.print("
Enter any +ve number:= ");
          orig = sc.nextInt();
          while (orig != 0)
          {
                 r = orig % 10;
                 rev = rev * 10 + r;
                 orig = orig / 10;
          }
          System.out.print("

Reverse Number:= " + rev);
   }
}
OUTPUT:

Enter any +ve number:= 3456
Reverse Number:= 6543

Explanation: The logic to reverse a number is quite simple. It can be understood step by step inside the loop:

Suppose orig = > original number entered by programmer.

   rev => reverse of the orig.
   r => remainder
While (orig! =0)
{
   r = orig%10;
   rev = rev *10 +r;
   orig= orig /10;
}

The step-by-step procedure inside the loop is as follows.

images

As orig = 0, so condition inside the while loop is false and control comes out of loop. The reverse number is variable rev, which is printed.

/*PROG 4.12 TO CHECK NUMBER IS PRIME OR NOT */
import java.io.*;
import java.util.*;
class JPS15
{
   public static void main(String args[])
   {
          int num, c = 2;
          Scanner sc = new Scanner(System.in);
          System.out.print("

Enter any +ve number:= ");
          num = sc.nextInt();
          while (c <= num / 2)
          {
             if (num % c == 0)
             {
                System.out.println("
Number is not prime");
                System.exit(0);
             }
             c++;
          }
          System.out.println("
Number is prime");
   }
}
OUTPUT:

(First Run)
Enter any +ve number: = 12
Number is not prime
(Second Run)
Enter any +ve number: = 23
Number is prime

Explanation: A number is prime if it is completely divisible by 1 and itself, e.g., 1, 3, 5, 7, 11, 13, 17, 19, 23, etc. To check whether a number is prime or not, start from a counter c = 2 (every number divides by 1) and continue till c < = num/2 since no number is completely divisible by a number which is more than half of that number. For example, 12 is not divisible by 7, 8, 9, 10, 11 which are greater than 6. So it should be checked whether the number divisible by any number < = num/2 is true; simply print ' Number is not prime ' and exit from the program, using System.exit(0). If num%c = = 0 is never true during the loop then at the end when loop exits maturely print 'Number is prime'.

/*PROG 4.13 CHECK NUMBER FOR PALINDROME */
import java.io.*;
import java.util.*;
class JPS16
{
   public static void main(String args[])
   {
          int orig, rev = 0, r, save;
          Scanner sc = new Scanner(System.in);
          System.out.print("Enter any +ve number:=");
          orig = sc.nextInt();
          save = orig;
          while (orig != 0)
          {
                 r = orig % 10;
                 rev = rev * 10 + r;
                 orig = orig / 10;
          }
          if (rev == save)
                 System.out.println("Number is palindrome");
          else
                 System.out.println("Number is not palindrome");
   }
}
OUTPUT:

First Run)
Enter any +ve number: =4545
Number is not palindrome

Second Run)

Enter any +ve number: =454
Number is palindrome

Explanation: A number is called palindrome if on reversing it is equal to the original number, e.g., 121, 454 and 3443, etc. To check whether an entered number is palindrome or not, simply reverse a number; the original number becomes zero when controls come out from the loop. So, the original number is saved in a variable before processing; in the above program, it is in the save variable.

/*PROG 4.14 CHECK NUMBER FOR ARMSTRONG */
import java.io.*;
import java.util.*;
class JPS17
{
   public static void main(String args[])
   {
          int num, r, save, newnum = 0, count = 0;
          Scanner sc = new Scanner(System.in);
          System.out.print("
Enter any +ve number:= ");
          num = sc.nextInt();
          save = num;
          while (num != 0)
          {
                 num = num / 10;
                 count++;
          }
          num = save;
          while (num != 0)
          {
                 r = num % 10;
                 newnum = newnum + (int)Math.pow(r, count);
                 num = num / 10;
          }
          if (newnum == save)
                 System.out.println("
Number " + save + " is
                                        Armstrong");
          else
                 System.out.println("
Number " + save + " is
                                        not Armstrong");
   }
}
OUTPUT:

(First Run)
Enter any +ve number:= 153
Number 153 is Armstrong
(Second Run)

Enter any +ve number: = 2345
     Number 2345 is not Armstrong

Explanation: A number is called Armstrong if sum of count number of power of each digit is equal to the original number. For example, to check whether 153 is Armstrong number or not, see that number of digits are 3 then

images

This is equal to the original number so number 153 is Armstrong.

Consider a four digit number 1653.

images

So program proceeds as follows:

First while loop: First find out number of digits; before doing this, save the number in the save variable. Now number of digits is stored in the count variable. At this stage, num is 0 so copy the value from save to num. POW is a library function whose prototype is given in header file math.h. It returns the number to the power where first argument is number and second is power, e.g., pow(2, 3) gives 23 = 8, pow(3, 2) = 32 = 9.

Second while loop: Steps of second while loop are as follows:

images

As newnum contains 153, it is compared with the original number stored in save. The output becomes 153 as Armstrong number.

4.7.2 The for Loop

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the 'for loop' because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

for (initialization; termination; increment)
{
     Statements;
     Statements;
     Statements;
}

When using this version of the for statement, keep in mind the following:

1.   The initialization expression initializes the loop; it is executed once, as the loop begins.

2.   When the termination expression evaluates to false, the loop terminates.

3.   The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

For example: Consider the following code:

for(t=1;t<=10;t++)
System.out.print(" "+t);

The first part of for loop t = 1 is the initialization, i.e., providing an initial value of 1 to loop counter t. Next statement t < = 10 is the testing condition for which this loop runs. If the condition is true, the last part is incremented with loop counter t. The for loop works by first taking t = 1 and then checking the condition whether t < = 10; if so, it executes the next statement following System.out.println. Recall as there are no braces after the for loop, only the first statement is considered the body of the for loop. It then goes on to increment the value of t, checks the test condition and again executes System.out.println. This continues till the condition t < = 10 is true. As soon as the condition becomes false (in this case t becomes 11), control comes out from the loop and the program terminates. The output of the loop will be as follows:

1  2  3  4  5  6  7  8  9  10

The initialization statement executes only once, whereas condition check and increment/decrement part of the for loop execute till the condition remains true.

Note: There must be two semicolons in the for loop.

Note the difference between while loop and for loop. In the while loop, only condition is specified; initialization of the loop control variable is done before the while loop and increment/decrement is done within the body of the loop. But in the for loop, all three are used simultaneously within the loop itself.

Some more examples of for loop are given below:

(a)  for(int t=10;t>=1;t--)
    System.out.println(" "+t);
 Output:- 10 9 8 7 6 5 4 3 2 1

(b)  for(t=30;t>=1;t=t-3)
    System.out.print(" "+t);
 Output:-30 27 24 21 18 15 12 9 6 3

(c)  for(t=100;t>=10;t=t-10)
    System.out.print(" "+t);
 Output: - 100 90 80 70 60 50 40 30 20 10

4.8 DIFFERENT SYNTAXES OF for LOOP

There are different syntaxes of for loop. The first syntax has been presented as above. Other syntaxes are as follows:

1.   initialization;
for (; condition; increment/decrement)
body of the loop;

In this syntax, though we have left the initialization part and have put this before the for loop, semicolon (;) is must in the for loop. For example, see the code given below:
int t=10;
for (;t<=100;t+=10)
System.out.print (" "+t);

2.   for(initialization; condition ;)
{
   Statements;
   Increment/decrement;
}

In this syntax, increment/decrement part has been written within braces. Note that braces are must because there are two statements required to be made as body of the for loop. For example, see the code given below:
for(t=1;t<=10;)
{
System.out.print(" "+t);
t++;
}

3.   initialization;
for(;condition;)
{
Statements;
Increment/decrement;
}

In this syntax, though we have left both initialization and increment part, semicolon is necessary on both sides.

t=1;
for (; t<=10 ;)
System.out.println(" "+t);

4.9 PROGRAMMING EXAMPLES

/*PROG 4.15 SUM OF THE SERIES 1−2+3−4+......*/
import java.io.*;
import java.util.*;
class JPS18
{
   public static void main(String args[])
   {
       int n, sum = 0, t, k = 1;
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter the number of terms
");
       n = sc.nextInt();
       for (t = 1; t <= n; t++)
       {
           if (t % 2 != 0)
               System.out.print(t + "-");
           else
               System.out.print(t + "+");
           sum = sum + (t * k);
           k = k * (-1);
       }
   System.out.println("
Sum of series is " + sum);
   }
}

OUTPUT:

Enter the number of terms
7
1-2+3-4+5-6+7-
Sum of series is 4

Explanation: In the series to be generated, odd numbers are +ve and even numbers are −ve. Take one variable k = 1. k is multiplied by −1 inside the loop in each iteration.

Initially sum = 0 + (1 * 1) gives sum = 1 then k becomes k = 1 * − 1= −1, which is used in the second iteration of the loop. In the second iteration, sum becomes sum = 1 + (2 * −1) => sum = 1 − 2 = − 1 and value of k changes to 1 again (−1 * −1 = 1) and this continues for n times.

/*PROG 4.16 TO PRINT AND FIND SUM OF SERIES 1^2+2^2+3^2+4^2+...........(^ STANDS FOR POWER) */
import java.io.*;
import java.util.*;
class JPS19
{
       public static void main(String args[])
       {
          double sum = 0;
          int n, t;
          Scanner sc = new Scanner(System.in);
          System.out.println("Enter the number of terms
");
          n = sc.nextInt();
          for (t = 1; t <= n; t++)
       {
          System.out.print(t + "^2+");
          sum = sum + Math.pow(t, 2);
   }
          System.out.println("
 Sum of series is " + sum);
   }
}

OUTPUT:

Enter the number of terms
7
1^2+2^2+3^2+4^2+5^2+6^2+7^2+
Sum of series is 140.0

Explanation: pow is standard library function which returns power of first argument to second number, i.e., pow(2, 3) returns 2 to the power 3, i.e., 8. A number of terms are taken in n and loop is run from 1 to n. On each iteration, 2 was found to the power t and added to sum. The pattern is displayed within the for loop and sum of series is displayed outside the loop.

/*PROG 4.17 TO CHECK A NUMBER IS PERFECT OR NOT */
import java.io.*;
import java.util.*;
class JPS20
{
   public static void main(String args[])
   {
          int num, t, sum = 1;
          Scanner sc = new Scanner(System.in);
          System.out.println("Enter an integer");
          num = sc.nextInt();
          for (t = 2; t <= num / 2; t++)
          {
                 if (num % t == 0)
                        sum = sum + t;
          }
          if (sum == num)
                 System.out.println("The number is perfect");
          else
                 System.out.println("The number is not perfect");
      }
}

OUTPUT:

Enter an integer
15
The number is not perfect

Explanation: A number is called perfect if sum of its factor is equal to the number itself, e.g., 6; its factors are 1, 2 and 3 and their sum is 6, which is equal to the number itself, so it is a perfect number. Similarly 28 is a perfect number. In the loop, the sum is initialized to 1 and the loop is run for num/2 as for any number, e.g., t which is more than num/2, num%t will not be zero (excluding num itself).

4.9.1 Nesting of for Loop

Nesting of for loop is used most frequently in many programming situations and one of the most important usage is in displaying various patterns which can be seen in the following programs. The general syntax is given below:

for(initialization;condition;increment/decrement)
{
   for(initialization;condition;increment/decrement)
   {
     satements;
   }
   statements;
}

For each iteration of first for loop (outer for loop), inner for loop runs as it is part of the body of outer for loop. The inner for loop has its own set of statements which executes till the condition for inner for loop is true.

For example, consider the following code:

for(a=1;a<=3;a++)
{
   for(b=1;b<=4;b++)
     System.out.print(a*b+"	");
   System.out.println();
}

The body of the first for loop (outer) contains three statements enclosed within braces. The inner for loop's body has got only one statement as there are no braces after the inner for loop. Initially a is 1 and condition a < = 3 in the outer loop is true. The first statement inside outer for loop is inner for loop which initializes b = 1. Now this for loop runs from 1 to 4 for the value of a = 1. When this loop terminates on reaching a value of b = 5, control is transferred to third statement System.out.println(); which leaves a line on the output screen. Now control is transferred to outer loop which increments the value of a by 1, which becomes 2. The process repeats with value of b from 1 to 4, for value of a = 2, till a < = 3 remains true.

We present few programs on nesting of for loop.

import java.io.*;
import java.util.*;
class JPS21
{
   public static void main(String args[])
   {
          int line, row, col, value = 0;
          Scanner sc = new Scanner(System.in);
          System.out.print("

Enter the number of
                               lines:= ");
          line = sc.nextInt();
          System.out.println("
The patter is
");
          for (row = 1; row <= line; row++)
          {
                 for (col = 1; col <= row; col++)
                 {
                       value++;
                       System.out.print(" " + value);
                 }
                 System.out.println();
          }
   }
}

OUTPUT:

Enter the number of lines: = 4
The patter is

1
2 3
4 5 6
7 8 9 10

Explanation: Two for loops have been used in the program. One is to control the number of rows and second is to control the number of columns. Initially assume line = 5 so outer for loop runs five times. In the first run, row = 1 and inner loop runs only once. The value of value variable is incremented and printed. Control moves to the new line. For row = 2, inner loop runs twice and second row of output is printed. This continues till row < = line.

 import java.io.*;
 import java.util.*;
 class JPS22
 {
    public static void main(String args[])
    {
           int line, row, col;
           char ch = 'A';
           Scanner sc = new Scanner(System.in);
           System.out.print("

Enter number of lines:=");
           line = sc.nextInt();
           System.out.println("

The pattern is
");
           for (row = 1; row <= line; row++)
           {
                  for (col = 1; col <= row; col++)
                       System.out.print(" " + ch);
                  System.out.println();
                  ch++;
           }
    }
 }

 OUTPUT:

 Enter number of lines:=7
 The pattern is

   A
   B B
   C C C
   D D D D
   E E E E E
   F F F F F F
   G G G G G G G

Explanation: For the first run of outer for loop, ch = 'A'. When first iteration of inner for loop finishes, value of ch is incremented by 1 and becomes B. As one A on first row, two B on second row and so on have to be printed, ch at the end of every iteration of outer for loop is incremented.

 import java.io.*;
 import java.util.*;
 class JPS23
 {
           public static void main(String args[])
           {
           int line, row, col, temp;
           Scanner sc = new Scanner(System.in);
           System.out.print("

Enete the number of lines:=");
           line = sc.nextInt();
           System.out.println("The pattern is 
");
           for (row = 1; row <= line; row++)
           {
                  for (col = 1; col <= row; col++)
                         if (row % 2 == 0)
                         {
                               if (col % 2 == 0)
                                      System.out.print(" 1");
                               else
                                      System.out.print(" 0");
                         }
                         else
                               System.out.print(" " + col % 2);
                  System.out.println();
                  }
           }
 }

 OUTPUT:

 Enter the number of lines: =7
 The pattern is
   1
   0 1
   1 0 1
   0 1 0 1
   1 0 1 0 1
   0 1 0 1 0 1
   1 0 1 0 1 0 1

Explanation: Observe the pattern carefully. There are different patterns on both even and odd number of lines. On even number of lines, i.e., for row = 2, 4, 6..., if the complement of col%2 is printed, the desired pattern is obtained. On row = 1, 3, 5 ..., col%2 is simply checked. If it is equal to 0, 1 is printed else 0 is printed .

 import java.io.*;
 import java.util.*;
 class JPS24
 {
    public static void main(String args[])
    {
           int line, row, col, val, b;
           Scanner sc = new Scanner(System.in);
           System.out.print("

Enter the number of   lines");
           line = sc.nextInt();
           System.out.println("
The patter is
");
           /*Logic to print first half of pattern demarcted
             through bold figure*/
           for (row = 1; row <= line; row++)
           {
                  val = row;
                  for (b = 1; b <= line - row; b++)
                         System.out.print(" ");
                  for (col = 1; col < 2 * row + 1; col += 2)
                         System.out.print(" " + val++);
           /*Logic to print second half of pattern demarcated
             through bold figures*/
                  val = val - 2;
                  for (b = 1; b <= row - 1; b++)
                         System.out.print(" " + val--);
                  System.out.println();
           }
    }
 }

 OUTPUT:

 Enter the number of lines 5
 The patter is
                             1
                           2 3 2
                         3 4 5 4 3
                       4 5 6 7 6 5 4
                     5 6 7 8 9 8 7 6 5

Explanation: It is assumed the pattern itself consists of two sub-patterns. The first pattern assumed is up to the numbers shown in the bold. Rest of the numbers is part of the second pattern. For each iteration of outer loop, row number is stored into val variable and printed till col < 2*row + 1 remains true. But before this, spaces are left so that numbers appear in the centres and space I is obtained on the left before printing each number. This condition has been chosen as for row = 1, 2, 3, 4, 2*row + 1 is obtained as 3, 5, 7, 9 which are shown in bold letters in the pyramid.

For second half of pattern, note that in the second line, just one number (2) has to be printed ; in the third line, two numbers (4, 3) and so on which is controlled by row − 1. To print the number, 2 is subtracted from val and each iteration is decremented.

4.9.2 The do-while Statement

The last loop is do-while loop. Its syntax is as follows:

do
{
    statements;
    statements;
    statements;
    .......... ;
    .......... ;
}while(condition);

It is similar to while loop with the difference that condition is checked at the end, instead of being checked at the beginning. Just because of this the do-while loop is called bottom-testing loop or exit-controlled loop. The loop is called so, as condition is checked at the bottom of the loop and exit of the loop is false; the loop executes at least once.

Consider the code given below:

int t=1;
do
{
   System.out.print(" "+t);
   t++;
}while(t<=10);

The do-while loop is similar to the while loop with the difference that the condition is checked at the end. The loop starts with a do following the block, and at the end of block the condition is written using while. The while is part of the do-while loop and it must be terminated by semicolon; initially the value of t is 1 which is printed through Systemout.print, then t becomes 2. At the end of block, as the condition is true, control transfer back to do block and the process continues.

Some important points regarding do-while loop are as follows:

1.   It is also called bottom testing loop or exit controlled loop as condition is checked at the bottom of the loop.

2.   Regardless of the condition given at the end of block the loop runs at least once.

3.   The do-while loop is mostly used for writing menu-driven programs.

Now consider the code

int t=0;
do
{
   System.out.print(" "+t);
   t++;
}while(t<0);

The condition at the end in while is false at the very first iteration of loop but loop runs at least once as the condition is checked at the end.

/*PROG 4.22 SUM OF DIGITS UP TO SINGLE DIGIT USING DO-WHILE */
import java.io.*;
import java.util.*;
class JPS25
{
   public static void main(String[] args)
   {
          int num;
          int sum=0,save,r;
          Scanner sc=new Scanner(System.in);
          System.out.print("
Enter an integer:=");
          num=sc.nextInt();
          do
          {
                 sum=0;
                 while(num!=0)
          {
                 r=num%10;
                 sum=sum+r;
                 num=num/10;
          }
          if(sum>9)
          System.out.println(sum);
   }while(num>9);
   System.out.println("

Sum of digits up to single
                         digit"+" is:= "+sum);
   }
}

OUTPUT:

Enter an integer:=234
Sum of digits up to single digit is:= 9

Explanation: For example, if the number is 4275 then sum of digits is 4+2 + 7 + 5 = 18. As 18 is greater than 9, the process is repeated and get the result becomes 1 + 8, i.e., 9. As this is the digit required, so the process is stopped. In the program for finding sum of digits while loop has been used, but for sum of digits up to single digit do-while loop has been used. When sum > 9, sum is assigned to num and for this num, sum of digits is determined using while loop.

/*PROG 4.23 MINI AREA CALCULATOR USING SWITCH-CASE AND DO-WHILE */
import java.io.*;
import java.util.*;
class JPS26
{
   static void show(String s)
   {
          System.out.println(s);
   }
   public static void main(String []args)
   {
          Scanner sc=new Scanner(System.in);
          float h,b,s,w,l,r,area;
          int choice;
          final float PI=3.14f;
          do
          {
                   show("Welcome to Area Zone
");
                   show("1. Area of Triangle
");
                   show("2. Area of Circle
");
                   show("3. Area of Rectangle
");
                   show("4. Area of Square
");
                   show("5. Exit
");
                   show("Enter your choice(1-5):=");
                   choice =sc.nextInt();
                   switch(choice)
                   {
                   case 1:
                          show("Enter the base and height of
                                 triangle
");
                          b=sc.nextFloat();h=sc.nextFloat();
                          area=0.5f*b*h;
                          show("Area of triangle is "+area);
                          break;
                   case 2:
                          show("Enter the radius of circle
");
                          r=sc.nextFloat();
                          area=PI*r*r;
                          show("Area of circle is "+area);
                          break;
                   case 3:
                          show("Enter the length and width of
                                 rectangle
");
                          l=sc.nextFloat();w=sc.nextFloat();
                          area=l*w;
                          show("Area of rectangle is "+area);
                          break;
                   case 4:
                          show("Enter the side of square
");
                          s=sc.nextFloat();
                          area=s*s;
                          show("Area of square is "+area);
                          break;
                   case 5:
                          show("Bye Bye......");
                          System.exit(0);
                   default:
                          show("Better you know number 
");
                   }
                   }while(choice>=1&&choice<=5);
      }
}

OUTPUT:

Welcome to Area Zone
1. Area of Triangle
2. Area of Circle
3. Area of Rectangle
4. Area of Square
5. Exit

Enter your choice (1-5):=
1
Enter the base and height of triangle
2 4
Area of triangle is 4.0

Explanation: In the program, the whole switch-case is put into do-while loop. In each case, areas of triangle, circle, rectangle and square are found out. After fulfilling one choice for the user, the menu again appears because of do-while loop. On entering 5 in the choice, the program terminates.

4.10 break AND continue STATEMENT

4.10.1 The break Statement

The break statement is used to come out early from a loop without waiting for the condition to become false. One such usage of break in the switch-case statements has been observed. When the break statement is encountered in the while loop or any of the loop that would be seen later, the control immediately transfers to first statement out of the loop, i.e., loop is exited prematurely. If there is nesting of loops, the break will exit only from the current loop containing it.

As an example of break statement, consider the following code:

int x=1;
while(x<=5)
{
if(x==3)
break;
System.out.println("Inside the loop "+x);
x++;
}
System.out.println("Outside the loop "+x);

In the above code when x is 3, if condition becomes true; the body of the if statement is single break statement, so all the statements in the loop following the break are skipped and control is transferred to the first statement after the loop, which is System.out.println and prints the statement Outside the loop x = 3.

/*PROG 4.24 CHECKING WHETHER A NUMBER IS PRIME OR NOT USING BREAK AND WHILE */
import java.io.*;
import java.util.*;
class JPS28
{
   public static void main(String[] args)
   {
          Scanner sc = new Scanner(System.in);
          int num, c = 2;
          boolean flag = false;
          System.out.print("

Enter the number:= ");
          num = sc.nextInt();
          while (c <= num)
          {
                 if (num % c == 0)
                 {
                        break;
                 }
                 c++;
          }
          if (!flag)
                 System.out.println("
Number is prime");
          else
                 System.out.println("
Number is not prime");
   }
}

OUTPUT:

Enter the number:= 23
Number is prime

Explanation: One version of program which checks number for prime has been given earlier. This is the second version of the same program but written using break. Here it is checked if the number is divisible by any number < = num/2, it cannot be prime; we set flag = true and come out from the loop. The flag was initialized to false in the beginning so if num%c = = 0 is true, control set flag = true, which means number is not prime. If flag remains false, it means control never transferred to if block, i.e., number is prime. So outside the loop, this value of flag is checked and printed accordingly.

4.10.2 The continue Statement

The continue statement causes the remainder of the statements following continue to be skipped and continue with the next iteration of loop. So we can use continue statement to bypass certain number of statements in the loop on the basis of some condition if given generally.

The syntax of continue statement is simply the following:

continue;
int t=0;
while(t<=10)
{
   t++;
   if(t%2!=0)
          continue;
   System.out.println(" "+t);
}
/*PROG 4.25 SQUARE ROOT OF NUMBER USING CONTINUE AND WHOLE */
import java.*;
import java.util.*;
class JPS29
{
   public static void main(String args[])
   {
   int n, i = 1;
   double num;
   Scanner sc = new Scanner(System.in);
   System.out.print("
Enter how many numbers:= ");
   n = sc.nextInt();
   while (i <= n)
   {
          System.out.print("
Enter the double number:= ");
          num = sc.nextDouble();
          if (num < 0)
          {
                 System.out.println("Sqrt of -ve number
                              is not possible");
                 i++;
                 continue;
          }
          System.out.println("Square root:= "
                              +(Math.sqrt(num)));
          i++;
          }
   }
}

OUTPUT:

Enter how many numbers: = 4
Enter the double number: = 15
Square root: = 3.872983346207417
Enter the double number: = -23
Sqrt of -ve number is not possible
Enter the double number: = 55
Square root: = 7.416198487095663

Explanation: This program is simple. The user was initially asked about the limit, i.e., count of numbers of whom square root is to be find out, that is stored into the variable n. The loop was then run for n times. In each repetition, the user was asked a double number whose square root is to be found out. For finding square root of the number, built-in function Math.sqrt() was made use of. In case number is negative, the appropriate message is displayed and continued, i.e., the user is prompted for the next number.

4.10.3 Labelled break and continue Statement

The disadvantage of break and continue is that they are applicable for the current loop only. That is, continue causes next iteration of the current loop in which it is present. Similarly, break causes exit from the current loop. In case of nesting of loops, when we want to come out from the outermost loop or continue from some other loop instead of current loop, simple "break and continue" does not help.

To solve this problem, Java provides the labelled break and labelled continue statements that allow coming out from deeply nested loop and continue with the outer loop, respectively. The syntax is as follows:

break label1;

and

continue label1

where label1 is the label where the control is to be transferred. The label may be any valid identifier name. As labelled break and continue are used with the loops, a label must appear prior to break and continue statements. One example each of break and continue are given below.

/*PROG 4.26 DEMO OF LABELLED CONTINUE */
class JPS30
{
   public static void main(String args[])
   {
          int i, j;
          lab1:
          for (i = 1; i <= 5; i++)
          {
                 for (j = 1; j <= 4; j++)
                 {
                        if (i % 2 == 0)  continue lab1;
                        System.out.println("i="+i+"	j="+j);
                 }
          }
   }
}

OUTPUT:

i= 1  j= 1
i= 1  j= 2
i= 1  j= 3
i= 1  j= 4
i= 3  j= 1
i= 3  j= 2
i= 3  j= 3
i= 3  j= 4
i= 5  j= 1
i= 5  j= 2
i= 5  j= 3
i= 5  j= 4

Explanation: In the for loop, if (i%2 = = 0), the expression continue lab1 is used to continue from lab1 from the outer loop instead of continuing from the current loop if label were not present. Each even value for the control variable 'i' for outer loop is skipped using continue lab1; expression.

/*PROG 4.27 DEMO OF LABELLED BREAK */
class JPS31
{
   public static void main(String args[])
   {
          int i, j;
          lab1:
          for (i = 1; i <= 5; i++)
          {
                 for (j = 1; j <= 4; j++)
                 {
                        if (i % 2 == 0)
                               break lab1;
                        System.out.println("i="+i+"	j="+j);
                 }
          }
   }
}

OUTPUT:

i=1  j=1
i=1  j=2
i=1  j=3
i=1  j=4

Explanation: In the inner for loop, if (i%2 = = 0), the expression break lab1 exits from the outer loop and not from the inner loop in which it is placed. This is because label lab1 is placed on the same line from where outer for loop starts.

4.11 PONDERABALE POINTS

1.   Java supports all decision making and control statements like if, if-else, switch-case, for, while and do-while.

2.   The flow of execution may be transferred from one part of a program to another based on the output of the conditional test carried out. It is known as conditional execution.

3.   if-else, if-else-if and switch-case are known as selective control structures.

4.   A null statement is represented by a semicolon.

5.   Null statements are useful to create time delay and to end a label statement where no useful operation is to be performed.

6.   A do-while loop is called bottom testing loop as condition is checked at the end. Even for the false condition it runs at least once.

7.   The for loop can be used to act as infinite loop; the code is as follows:

for (; ;)
 {
  ………….;
  ………….;
 }

8.   In Java if (x) is equal to if (x! = false), where x must be a Boolean value.

9.   In Java if (!x) is equal to if (x = = false), where x must be a Boolean value.

10. Java supports labelled break and continue, which can be used to come out from a deeply nested loop (break) and to continue from an outer loop (continue).

REVIEW QUESTIONS

1.   What are the different streams available is system package?

2.   What is the difference between print and println statement?

3.   Classify the control flow statement.

4.   Draw a flowchart and write a program to pick the largest of three given numbers.

5.   One feet = 12.0 inches, one inch = 2.54 centimeters; write a program to compute inches and feet of 76.2 cms.

6.   The following table shows the employees code and the percentage of bonus for the value of basic pay.

Employee code Bonus
100 5
200 1
300 2
400 25

7.   In what way does the switch statement differ from if-else statement?

8.   Write a program to get week day number (1...7) from the user and then

If day = 1 print "Have a nice day"
If day = 2, 3, 4, 5, 6 print "Welcome become to working day"
If day = 7 print "Have a nice week end day"

Use the if-else, if-else-if ladder and switch case structure.

9.   Write a program; get the input marks from the user through keyboard by checking the following conditions.

If marks < 40 — fail
If marks > 50 — good
If marks > 75 — very good
If marks > 90 — excellent

10. A frog starts climbing 30 ft well. Each hour frog climbs 3 ft and slips back 2 ft. How many hours does it take to reach top and get out?

11. Differentiate entry control loop and exit control statements.

12. What is wrong with this code?

switch(character)
{
  case 'a':
       i =10;
       break;
  case 'b':
       j = 11;
       break;
  case 'c':
       k = 12;
       break;
       L = 14;
}

13. Write a program to solve linear and quadratic equations.

14. How many times does the println() statement execute?
for(int l =1; l<l++)
System.out.println("My test
  loop");
i = 1
i<10
i++

15. What is an empty statement?

16. Write a program to compute power of 2 using for loop.

17. What is automatic type conversion? How are widening and narrowing achieved?

18. Write a program to display the following output using for loop:

(a)  1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

(b)  1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

(c)  * * * * *
* * * *
* * *
* *
*

19. What will be the output for the given code?

for(int l =-4; l<=4; l = l+2)
{
    System.out.println(2/l);
}

20. What will be the output for the given code?

int x = 10;
switch(x)
{
    default:
      System.out.println("This is
        first");
    case 9:
      System.out.println(" x = 9");
      break;
    case 11:
      System.out.println(" x =
        11");
      break;
    case 12:
      System.out.println(" x =
        12");
}

21. What will be printed out the following code is compiled and run?

int i = 1;
switch(i)
{
   case 0:
     System.out.println("OOPS");
     break;
   case 1:
     System.out.println("C");
   case 2:
     System.out.println("C++");
   default:
     System.out.println("JAVA");
}

22. What will be the output of the following code?

class JPS
{
   public static void main(String
     args[])
   {
     int i, j;
     outer:
     for (i = 0; i < 3; i++)
       inner: for (j = 0; j < 3;
         j++)
       {
         if (j == 2)
           continue outer;
         System.out.println("i" +
           i + "j" + j);
       }
   }
}

Multiple Choice Questions

1.   Identify the wrong statement:

(a) if(a > b);

(b) if a > b;

(c) if(a > b) { ; }

(d) (b) and (c)

2.   Each case statement in switch () is separated by

(a) break

(b) continue

(c) exit()

(d) goto

3.   Which conditional expression always returns false value?

(a) if (a = = 0)

(b) if(a = 0)

(c) if(a = 10)

(d) if(10 = = a)

4.   Which conditional expression always returns true value?

(a) if (a = = 1)

(b) if(a = 1)

(c) if (a = 0)

(d) if(1 = = a)

5.   If default statement is omitted and there is no match with case labels,

(a) no statements within switch-case block will be executed

(b) syntax error is produced

(c) all the statements in switch-case construct will be executed

(d) the last case statement only will be executed

6.   Identify the unconditional control structure from the following options

(a) do-while

(b) switch-case

(c) goto

(d) if

7.   The minimum number of times while loop is executed is

(a) 0

(b) 1

(c) 2

(d) Cannot be predicted

8.   The minimum number of times for loop is executed is

(a) 0

(b) 1

(c) 2

(d) Cannot be predicted

9.   The minimum number of times do-while loop is executed is

(a) 0

(b) 1

(c) 2

(d) Cannot be predicted

10. Infinite loop is

(a) useful for time delay

(b) useless

(c) used to terminate execution

(d) not possible

11. The continue statement is used to

(a) continue the next iteration of a loop construct

(b) exit the block where it exists and continue future

(c) exit the outermost block even if it occurs inside the innermost

(d) continue the compilation even an error occurs in a program

12. Which is the incorrect statement?

(a) while loop can be nested

(b) for loop can be nested

(c) Both (a) and (b) are correct

(d) One type of loop cannot be nested in other type

13. The break statement is used in

(a) selective control structure only

(b) loop control structure only

(c) both (a) and (b)

(d) switch-case control structure only

14. Which of the following statements results in infinite loop?

(a) for (i = 0; ; i++)

(b) for (i = 0; ;);

(c) for (; ;);

(d) All of the above

15. How many x are printed?
for (i = 0, j = 10; i<j; i++, j - -)
System.out.println(x);

(a) 10

(b) 5

(c) 4

(d) None of the above

16. In the following loop construct, which one is executed only once always for (expr1; expr2; expr3)

(a) expr1

(b) expr3

(c) expr1 and expr3

(d) expr1, expr2 and expr3

17. In Java if (x) is equal to

(a) if (x = false) where x must be a Boolean value

(b) if (x = = false) where x must be a Boolean value

(c) if (x!= false) where x must be a Boolean value

(d) if (x = True) where x must be Boolean value

18. In Java if(!x) is equal to

(a) if (x = True) where x must be a Boolean value

(b) if (x = = True) where x must be Boolean value

(c) if (x = false) where x must be Boolean value

(d) if (x = = false) where x must be Boolean value

19. Null statements are useful for

(a) time delay

(b) to run loop infinite times

(c) not running a loop statement

(d) none of the above

KEY FOR MULTIPLE CHOICE QUESTIONS

1.   b

2.   a

3.   b

4.   b

5.   a

6.   c

7.   d

8.   d

9.   b

10. b

11. a

12. d

13. c

14. d

15. b

16. a

17. c

18. d

19. a

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.151.164