Page 252 - ComputerScience_Class_11
P. 252

c.  The function takes the values as parameters and returns a value as well.
                For example,
                  class average_number
                  {
                      double average(int n)
                      {
                          int i, s=0, c=0;
                          double avg;
                          for(i=1;i<=n;i++)
                          {

                              if(i%2==1)
                              {
                                  continue;
                              }
                              s=s+i;
                              c++;
                          }
                          avg=s/c;
                          return avg;
                      }

                      void main(String[] args)
                      {
                          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
              In Java, the behavior of primitive arguments when passed to methods is different from object arguments due to Java’s
              handling of pass-by-value. Understanding how primitive arguments behave can help avoid common mistakes in code.

              After declaring and defining a method, we must call it or invoke it so that the job assigned to the method (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 4     Write a program that takes numbers as input and calculates the sum of the digits in the
                              number and returns the sum to the caller method.
                1       class PassValue
                2       {




                  250  Touchpad Computer Science (Ver. 3.0)-XI
   247   248   249   250   251   252   253   254   255   256   257