Question-1 [10 Points]
Write a program that prompts the user for an integer and then prints out all coward numbers up to
that integer. For example, when the user enters 20, the program should print: 3 4 6 8 12 14 18 20.
Recall that a number is a prime number if it is not divisible by any number except 1 and itself.
Hint: Use Nested Loop to solve this problem. Outer Loop iterations must start from 3 and ideally inner
loop iterations must start from 2.
Coward Number: Number whose previous number is not divisible by any number other than 1
and number itself.
Instructions:
1. Create a program called CowardNumbers.java.
2. Create appropriate variables and assign values using a Scanner object.
import java.util.Scanner;
public class CowardNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();
for (int i = 2; i <= N; i++) {
boolean isPrime = true;
// ideally inner loop iterations must start from 2.
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print((i+1) + " ");
}
}
// close Scanner
input.close();
}
}
Comments
Leave a comment