Write a menu driven program to display the following as per user's choice:
Choice 1 : To input a number and check if it is a perfect number.
Sample input: 6
The factors of 6 = 1+2+3 = 6
Output: It is a perfect number
Choice 2: Find the sum of natural numbers up to 'n' Accept the value of ‘n’ from the user
Answers
Answer:
package Coder;
import java.util.*;
public class Series {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int ch,s=0;
System.out.println("Enter your choice 1 or 2");
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter a number");
int n=sc.nextInt();
for(int i=1;i<n;i++)
{
if (n%i==0)
s+=i;
}
if (s==n)
System.out.println("Perfect");
else
System.out.println("Not Perfect");
break;
case 2:
System.out.println("Enter a number");
n=sc.nextInt();
for(int i=1;i<=n;i++)
{
s+=i;
}
System.out.println("Sum="+s);
break;
default:System.out.println("Invalid choice");
}
}
}
____________
Variable description
i--> loop variable
s--> to calculate sum
n--> input variable to take a number input from user
ch---> input variable to take a choice as input
__________
•For verification, please check the attachments
Required Answer:-
Question:
Write a menu driven program to display the following as per user's choice:
Choice 1 : To input a number and check if it is a perfect number.
Choice 2: Find the sum of natural numbers up to 'n' Accept the value of ‘n’ from the user.
Program:
This is an easy question. Read this post to get your answer.
Here comes the program.
import java.util.*;
public class Choice
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("1. Check Perfect number.");
System.out.println("2. Find sum of first n numbers. ");
System.out.print("Enter your choice: ");
int c=sc.nextInt();
switch(c)
{
case 1:
System.out.print("Enter the number: ");
int n=sc.nextInt(), s=0;
for(int i=1;i<n;i++)
if(n%i==0)
s+=i;
System.out.println((s==n)?"Number is a perfect number.":" Number is not a perfect number.");
break;
case 2:
System.out.print("Enter n:");
int a=sc.nextInt(), b=0;
for(int i=1;i<=a;i++)
b+=i;
System.out.println("Sum is: "+b);
break;
default:System.out.println("Invalid Choice.");
}
sc.close();
}
}
Explanation:
We have asked the user to enter the choice. Now, we will check whether the number is perfect or not if the entered choice is 1 and we will find the sum of first n numbers if the choice is 2. This is done using switch case.
To check perfect number, we will sum up all the factors of the number (except the number itself) using loop. Then, we will check if the sum of proper factors and the number is equal or not. If they are equal, number is a perfect number else not.
To find the sum of first n numbers, we will take the value of n as input and then add up all the numbers from 1 to n using loop. Time to print.
Output is attached.