Page 122 - CTS - CSA TP - Volume 2
P. 122

COMPUTER SOFTWARE APPLICATION - CITS




           These examples demonstrate how to return data from methods in Java. The findMax method returns the maximum
           of two numbers, while the generateRandomNumber method returns a randomly generated integer. By returning
           data from methods, we can encapsulate logic and computations, making our code more modular and reusable.



           TASK 3: Calculating the Factorial of a Number
              public class FactorialDemo {
                  public static void main(String[] args) {

                      int n = 5;
                      // Calling the method to calculate the factorial of a number
                      long factorial = calculateFactorial(n);
                      System.out.println(“Factorial of “ + n + “ is: “ + factorial);
                  }

                  // Method to calculate the factorial of a number
                  public static long calculateFactorial(int n) {
                      if (n == 0) {
                          return 1;

                      } else {
                          long factorial = 1;
                          for (int i = 1; i <= n; i++) {
                              factorial *= i;
                          }
                          return factorial;

                      }
                  }
              }
           Output:
















           Explanation:

           •  In this program, we define a method calculateFactorial that takes an integer n as a parameter and returns the
              factorial of n.
           •  We declare a variable n in the main method and assign a value to it.

           •  We call the calculateFactorial method and pass n as an argument.
           •  Inside the calculateFactorial method, we use a for loop to calculate the factorial of n.



                                                           107
                                CITS : IT & ITES - Computer Software Application - Exercise 96
   117   118   119   120   121   122   123   124   125   126   127