KnowledgeBoat Logo

Computer Applications

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.

Java

Java Iterative Stmts

ICSE 2012

43 Likes

Answer

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;
        }
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of 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.BlueJ output of 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.

Answered By

14 Likes


Related Questions