Soham
public class NumberTriangle {
public static void main(String[] args) {
int n = 5; // Number of rows in the triangle
for (int i = 1; i <= n; i++) { // Loop for each row
for (int j = 1; j <= i; j++) { // Loop to print numbers in each row
System.out.print(j + " ");
}
System.out.println(); // Move to the next line after printing each row
}
}
}
public class FactorialList {
public static void main(String[] args) {
int number = 1; // Start with the number 1 while (number <= 10) { // Loop through numbers from 1 to 10
int factorial = 1;
int i = number;
// Calculate factorial using a while loop
while (i > 0) {
factorial *= i;
i--;
}
// Print the factorial of the current number
System.out.println("Factorial of " + number + " = " + factorial);
number++; // Move to the next number
}
}
}
public class DivisionByZeroDemo {
public static void main(String[] args) {
int numerator = 10;
int denominator = 0;
int result;
try {
// Attempt to divide by zero
result = numerator / denominator;
System.out.println("The result is: " + result);
} catch (ArithmeticException e) {
// Handle the division by zero exception
System.out.println("Error: Division by zero is not allowed.");
System.out.println("Exception message: " + e.getMessage());
}
}
}
import java.util.Scanner;
public class CircleCalculator {
public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the radius
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
// Calculate the area and circumference
double area = Math.PI * radius * radius;
double circumference = 2 * Math.PI * radius;
// Display the results
System.out.println("Area of the circle: " + area);
System.out.println("Circumference of the circle: " + circumference);
// Close the scanner
scanner.close();
}
}
b) Write a Java program to accept a number and find whether the number is Prime or not.
import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Check if the number is prime
boolean isPrime = isPrime(number);
// Display the result
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
// Close the scanner
scanner.close();
}
// Method to check if a number is prime
public static boolean isPrime(int num) {
if (num <= 1) {
return false; // Numbers less than or equal to 1 are not prime
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false; // If num is divisible by any number other than 1 and itself, it is not prime
}
}
return true; // If no divisors found, num is prime
}
}
Comments
Post a Comment