icse-promo

Question

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

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;

public class program8
{
	public static void main(String[] args)
	{
	    int choice=0;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("press 1 for Fibonacci Sequence");
		System.out.println("press 2 for Sum of Digits");
		System.out.print("Enter choice: ");
		choice =sc.nextInt();
		switch (choice)
		{
			case 1:
				int a = 0;
				int b = 1;
				System.out.print("0 1 ");
				for (int i = 3; i <= 10; i++)
				{
					int c = a + b;
					System.out.print(c + " ");
					a = b;
					b = c;
				}
				break;
			case 2:
				System.out.print("Enter a number: ");
				int num = sc.nextInt();
				int sum = 0;
				while (num > 0)
				{
					int rem = num % 10;
					sum = sum + rem;
					num = num / 10;
				}
				System.out.println("Sum of digits is " + sum);
				break;
			default:
				System.out.println("Invalid Choice");
		}
	}
}

				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *