Page 226 - Cs_withBlue_J_C11_Flipbook
P. 226

}
                          avg=s/c;
                          return avg;
                      }

                      void main()
                      {
                          double avg= average(10);
                          System.out.println("Average of even numbers "+ avg);
                      }
                  }
              In the above program, the method double average(int n) takes a value in ‘n’ as a parameter and also returns a double
              type value to the caller method containing the average of all the even numbers up to 10.

                   9.6 CALLING A METHOD
              After declaring and defining a method, we must call it or invoke it so that the job assigned to the method (i.e., the
              statements provided in the method) can be executed. To do so, there are two different ways, namely,
              •  Pass by Value
              •  Pass by Reference
              Let us study these in detail:

              9.6.1 Pass by Value
              The copy of the actual parameters is passed to the formal parameters in such a way that any change made to the formal
              parameters will not affect the actual parameters. This technique is referred to as the pass-by value. The primitive data
              members are sent as parameters in pass-by value.
              For example,

                Program 3     Inputs a number and calculates the sum of the digits in the number and returns the sum to
                              the caller method

                1       class pass_value
                2       {
                3           int sum(int num)

                4           {

                5               int rem=0, s=0;
                6               System.out.println("Value of num in the beginning : " + num);
                7               while(num>0)

                8               {

                9                   rem=num%10;
                10                  s= s+rem;
                11                  num=num/10;

                12              }
                13              System.out.println("Value of num after calculation : " + num);

                14              return s;



                224224  Touchpad Computer Science-XI
   221   222   223   224   225   226   227   228   229   230   231