Solutions for Class 10 ICSE Logix Kips Computer Applications with BlueJ Java | IT Developer <?php echo $page_title; ?>
IT Developer

Iterative Constructs in Java

Chapter 9

Iterative Constructs in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Program: Menu-Driven Program: Fibonacci or Sum of Digits


25. Using the switch statement, write a menu driven program to:

(1). Generate and display the first 10 terms of the Fibonacci series 0, 1, 1, 2, 3, 5....

The first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two.

(2). Find the sum of the digits of an integer that is input.
Sample Input: 15390
Sample Output: Sum of the digits = 18

For an incorrect choice, an appropriate error message should be displayed.

Program Title: Menu-Driven Program: Fibonacci or Sum of Digits

import java.util.Scanner;

 

public class MenuDrivenProgram {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

 

        System.out.println("MENU");

        System.out.println("1. First 10 terms of Fibonacci series");

        System.out.println("2. Sum of digits of a number");

        System.out.print("Enter your choice: ");

        int choice = sc.nextInt();

 

        switch (choice) {

            case 1:

                // Fibonacci series

                int n = 10; // first 10 terms

                int a = 0, b = 1;

                System.out.print("Fibonacci Series: " + a + " " + b + " ");

                for (int i = 3; i <= n; i++) {

                    int c = a + b;

                    System.out.print(c + " ");

                    a = b;

                    b = c;

                }

                System.out.println();

                break;

 

            case 2:

                // Sum of digits

                System.out.print("Enter a number: ");

                int num = sc.nextInt();

                int temp = num;

                int sum = 0;

 

                while (temp != 0) {

                    sum += temp % 10;

                    temp /= 10;

                }

 

                System.out.println("Sum of the digits = " + sum);

                break;

 

            default:

                System.out.println("Invalid choice! Please select 1 or 2.");

        }

 

        sc.close();

    }

}

Output

Sample Output 1 (Fibonacci)
MENU
1. First 10 terms of Fibonacci series
2. Sum of digits of a number
Enter your choice: 1
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Sample Output 2 (Sum of Digits)
MENU
1. First 10 terms of Fibonacci series
2. Sum of digits of a number
Enter your choice: 2
Enter a number: 15390
Sum of the digits = 18 

📝 Explanation

  1. Option 1 (Fibonacci):
    • Starts with 0 and 1, calculates each term as sum of previous two.
  2. Option 2 (Sum of digits):
    • Extract digits using % 10 and sum them in a loop.
  3. Default: Handles invalid menu input.