CJ_Slip_3A

Slip No.3

A) Write a ‘java’ program to check whether given number is Armstrong or not.(Use static keyword)

1. Open Notepad.

2. Type the following code:

    import java.util.Scanner;

    public class ArmstrongNumberChecker {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int number = scanner.nextInt();

    if (isArmstrong(number)) {
    System.out.println(number + " is an Armstrong number.");
    } else {
    System.out.println(number + " is not an Armstrong number.");
    }
    }

    public static boolean isArmstrong(int number) {
    int originalNumber = number;
    int result = 0;
    int numberOfDigits = String.valueOf(number).length();

    while (originalNumber != 0) {
    int digit = originalNumber % 10;
    result += Math.pow(digit, numberOfDigits);
    originalNumber /= 10;
    }

    return result == number;
    }
    }


3. Save the file with the name ArmstrongNumberChecker.java. Make sure to select "All Files" in the "Save as type" dropdown and add the .java extension manually.

4. Open the Command Prompt.

5. Compile the Java program by typing:
javac ArmstrongNumberChecker.java

6. Run the compiled Java program by typing:
java ArmstrongNumberChecker

7. output:
Enter a number: 153
153 is an Armstrong number.

No comments:

Post a Comment