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

COMPUTER SOFTWARE APPLICATION - CITS




           •  The calculated factorial is returned to the main method, where it is stored in the factorial variable.

           •  Finally, we print the factorial of n to the console.



           TASK 4: Generating Fibonacci Series

           public class FibonacciDemo {
               public static void main(String[] args) {
                   int n = 10;
                   // Calling the method to generate Fibonacci series

                   System.out.println(“Fibonacci series:”);
                   for (int i = 0; i < n; i++) {
                       System.out.print(fibonacci(i) + “ “);
                   }
               }

               // Method to generate the nth Fibonacci number
               public static int fibonacci(int n) {
                   if (n <= 1) {
                       return n;
                   } else {

                       return fibonacci(n - 1) + fibonacci(n - 2);
                   }
               }
           }
           Output:














           Explanation:
           •  In this program, we define a method fibonacci that takes an integer n as a parameter and returns the n-th
              Fibonacci number.
           •  We declare a variable n in the main method and assign a value to it.
           •  We iterate from 0 to n in the main method and print the Fibonacci series using the fibonacci method.
           •  Inside the fibonacci method, we use recursion to calculate the Fibonacci number for each value of n.
           •  The calculated Fibonacci number is returned to the caller.

           These examples illustrate how to return data from methods in Java. The calculateFactorial method returns the
           factorial of a number, while the fibonacci method returns the nth Fibonacci number. Returning data from methods
           allows us to perform calculations and computations, making our code more modular and reusable.



                                                           108

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