In: Computer Science
Write a menu driven Java program which uses a method for each of the following operations:
(Note : The user should be allowed to repeat the operations as long as he wants to. Use appropriate number of parameters and return type for each method.)
A. to find the sum of the following series (up to N terms). The program should display the terms:
22 + 42 + 62…
For example, if N=4, then the program should display the following terms:
22 + 42 + 62 + 82
Sum of terms = 120
B. To accept a number and then check whether it is a prime number or a composite number. Your program should display an appropriate message. A prime number is one which is divisible by itself and 1.
Sample Outputs:
Enter a number : 5
It is a prime number.
Enter a number : 12
It is a composite number.
//TestCode.java import java.util.Scanner; public class TestCode { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n; System.out.print("Enter a number : "); n = scanner.nextInt(); int val = 2; int res = 0; while(n>0){ res += (val*val); val += 2; n--; } System.out.println("Sum of terms = "+res); } }
/////////////////////////////////////////////////////// import java.util.Scanner; public class Prime { private static boolean isPrime(int x) { for(int i = 2;i<x;i++){ if(x%i == 0){ return false; } } return true; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n; System.out.print("Enter a number : "); n = scanner.nextInt(); if (isPrime(n)) { System.out.println("It is a prime number."); } else{ System.out.println("It is a composite number."); } } }