1
1. **Sum of Two Numbers**:
Write a program that prompts the user for two numbers and prints their sum.
```java
import java.util.Scanner;
public class SumNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
int sum = num1 + num2;
System.out.println("The sum is: " + sum);
scanner.close();
}
}
```
2. **Factorial of a Number**:
Write a program that calculates the factorial of a number given by the user.
```java
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to calculate the factorial: ");
int number = scanner.nextInt();
int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println("The factorial of " + number + " is: " + factorial);
scanner.close();
}
}
```
3. **Prime Number Check**:
Write a program that checks whether a number given by the user is prime or not.
```java
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to check if it is prime: ");
int number = scanner.nextInt();
boolean prime = true;
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
prime = false;
break;
}
}
if (prime)
System.out.println(number + " is a prime number.");
else
System.out.println(number + " is not a prime number.");
scanner.close();
}
}
```
Feel free to use these exercises for practice. And let me know in the comments what you think. :-)
You must log in or register to comment.