Number related program

Question 1:

Write a program in Java to enter a 2-digit number and find out its first factor excluding 1. The program then finds the second factor when the number is divided by the first factor.
Use a function void fact(int n) to accept the number and find the factors of the number.
Example:
If input = 21, then factors are 3 and 7.

import java.util.Scanner;
public class FactorFinder {

public static void fact(int n) {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
int secondFactor = n / i;
System.out.println(“First Factor: ” + i);
System.out.println(“Second Factor: ” + secondFactor);
break;
}
}
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print(“Enter a 2-digit number: “);
int num = sc.nextInt();

if (num >= 10 && num <= 99) {
fact(num);
} else {
System.out.println(“Please enter a valid 2-digit number.”);
}
}

}

OUTPUT:

WhatsApp Group Join Now
Telegram Group Join Now

Question 2:

Q2. Write a method fact(int n) to find the factorial of a number.
Include a main class to find the value of S,

where:

import java.util.Scanner;

public class FactorialExpression {

public static long fact(int n) {
    long f = 1;
    for (int i = 1; i <= n; i++) {
        f *= i;
    }
    return f;
}

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter value of n: ");
    int n = sc.nextInt();

    System.out.print("Enter value of r: ");
    int r = sc.nextInt();

    System.out.print("Enter value of t: ");
    int t = sc.nextInt();

    System.out.print("Enter value of m: ");
    int m = sc.nextInt();

    long numerator = fact(n) * (long)Math.pow((n - r), t);
    long denominator = fact(m) * fact(n - m);

    double S = (double) numerator / denominator;

    System.out.println("Value of S = " + S);
}

}

OUTPUT:

Question 3:

Aceept a string from user and count the number of vowels.

import java.util.Scanner;

public class VowelCounter {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter a string: ");
    String str = sc.nextLine();

    int count = 0;

    // Convert string to lowercase to handle both cases
    str = str.toLowerCase();

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            count++;
        }
    }

    System.out.println("Number of vowels: " + count);
}

}

OUTPUT:

Leave a Comment