0% found this document useful (0 votes)
12 views2 pages

Assignment 1 Answers

The document contains two Java programs: one that checks if a given number is prime and another that displays all perfect numbers between 1 and a user-defined limit. The first program uses a loop to determine if the number is divisible by any number up to half of itself, while the second program prompts the user for input and checks each number for perfection by summing its divisors. Both programs demonstrate basic Java syntax and control structures.

Uploaded by

weralij635
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Assignment 1 Answers

The document contains two Java programs: one that checks if a given number is prime and another that displays all perfect numbers between 1 and a user-defined limit. The first program uses a loop to determine if the number is divisible by any number up to half of itself, while the second program prompts the user for input and checks each number for perfection by summing its divisors. Both programs demonstrate basic Java syntax and control structures.

Uploaded by

weralij635
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Assignment 1: Introduction to Java

Set A

Q: Write a java Program to check whether given number is Prime or Not.

Ans:

public class PrimeCheck {

public static void main(String[] args) {

int num = 29;

boolean isPrime = true;

for (int i = 2; i <= num / 2; i++) {

if (num % i == 0) {

isPrime = false;

break;

if (isPrime)

System.out.println(num + " is a prime number.");

else

System.out.println(num + " is not a prime number.");

Q: Write a java Program to display all the perfect numbers between 1 to n.

Ans:

import java.util.Scanner;

public class PerfectNumbers {

public static void main(String[] args) {


Assignment 1: Introduction to Java

Scanner sc = new Scanner(System.in);

System.out.print("Enter n: ");

int n = sc.nextInt();

for (int i = 1; i <= n; i++) {

int sum = 0;

for (int j = 1; j < i; j++) {

if (i % j == 0) sum += j;

if (sum == i) System.out.println(i + " is a perfect number.");

sc.close();

You might also like