Using a switch statement, write a menu driven program to:

Java Programming Language (Article) (Program)

35

Using a switch statement, write a menu driven program to:
(a) 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.
(b) 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:

import java.util.Scanner;

public class KboatFibonacciNDigitSum
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("1. Fibonacci Series");
        System.out.println("2. Sum of digits");
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();

        switch (ch) {
            case 1:
            int a = 0, b = 1;
            System.out.print(a + " " + b);
            for (int i = 3; i <= 10; i++) {
                int term = a + b;
                System.out.print(" " + term);
                a = b;
                b = term;
            }
            break;

            case 2:
            System.out.print("Enter number: ");
            int num = in.nextInt();
            int sum = 0;
            while (num != 0) {
                sum += num % 10;
                num /= 10;
            }
            System.out.println("Sum of Digits " + " = " + sum);
            break;

            default:
            System.out.println("Incorrect choice");
            break;
        }
    }
}

Output:

1. Fibonacci Series
2. Sum of digits
Enter your choice: 1
0 1 1 2 3 5 8 13 21 34Press any key to continue . . .


1. Fibonacci Series
2. Sum of digits
Enter your choice: 2
Enter number: 15
Sum of Digits  = 6
Press any key to continue . . .

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.