Page 78 - TP_iPlus_V2.1_Class8
P. 78

The syntax of the if statement is as follows:

                  if (< conditional expression >)                                                 Start
                  {
                         [statements]

                  }
                                                                                              Conditional       False
                  For example:
                                                                                              Expression
                  public class IfStatement

                  {
                                                                                                     True
                        public static void main(int num)
                        {                                                                      Body of if
                             System.out.println("Entered number is: " + num);

                             if (num % 2 == 0)
                                                                                                  Stop
                             {
                             System.out.println("The number is even");
                                                                                            Flowchart of 'if' statement
                             }
                             System.out.println("Statement outside the if statement");

                        }
                  }


                  Run the  program  twice  for  values of 22 and  7,
                  respectively. When you enter 22, the condition (22 %
                  2 == 0) returns true. So, the statement inside the body
                  of the if statement gets executed and the output will

                  appear as shown:

                  When you enter the value 7, then the output will                                Output
                  appear as shown:

                  Since the  condition  (7  % 2 == 0)  returns  false, the
                  statement inside the body of the if statement does
                  not get executed and only the statement outside the
                  if statement gets executed.

                  The if…else Statement                                                           Output

                  The if…else statement is used to execute either of the blocks of statements from if or else
                  statements. When the condition next to the if keyword evaluates to true, the statement(s)

                  inside the if block will be executed. Otherwise, the statement(s) inside the else block will be
                  executed.




                    76
                         iPlus (Ver. 2.1)-VIII
   73   74   75   76   77   78   79   80   81   82   83