Armstrong Numbers with Code Examples in Java, Python, C++, C#, and Go

0
Armstrong Number Checker

An Armstrong number (also known as a narcissistic number, pluperfect number, or pluperfect digital invariant) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 13 + 53 + 33 = 153.

Armstrong Numbers with Code Examples in Java, Python, C++, C#, and Go
Armstrong Numbers with Code Examples in Java, Python, C++, C#, and Go


Task:

Develop a Java application to check if a given number is an Armstrong number by performing the following:

  • Use Scanner to take user input for the number.
  • Calculate the number of digits in the number.
  • Extract each digit of the number and raise it to the power of the number of digits.
  • Sum these values.
  • If the sum is equal to the original number, print a message stating that the number is an Armstrong number.
  • If it is not, print a message stating that the number is not an Armstrong number.
Armstrong Numbers

Expected Output:

  • Input: 153 → Output: 153 is an Armstrong number.
  • Input: 123 → Output: 123 is not an Armstrong number.
  • Input: 2222 → Output: 2222 is not an Armstrong number.

Armstrong Number Checker

This program checks if a given number is an Armstrong number.


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        // Use Scanner to take user input
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        // Calculate the number of digits in the number
        int originalNumber = number;
        int digits = 0;
        while (originalNumber != 0) {
            originalNumber /= 10;
            digits++;
        }

        // Reset originalNumber to number
        originalNumber = number;
        int sum = 0;

        // Extract each digit and calculate the sum of its power
        while (originalNumber != 0) {
            int digit = originalNumber % 10;
            sum += Math.pow(digit, digits);
            originalNumber /= 10;
        }

        // Check if the sum is equal to the original number
        if (sum == number) {
            System.out.println(number + " is an Armstrong number.");
        } else {
            System.out.println(number + " is not an Armstrong number.");
        }

        scanner.close();
    }
}

    

Instructions:

  1. Copy the Java code into your preferred Java IDE.
  2. Run the program and enter a number when prompted.
  3. View the output to check if the number is an Armstrong number.

Java Code to Check Armstrong Numbers:


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Use Scanner to take user input
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        // Store the original number for comparison
        int originalNumber = number;
        int digits = 0;
        int sum = 0;

        // Calculate the number of digits
        int temp = number;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }

        // Reset temp to the original number for calculation
        temp = number;
        while (temp != 0) {
            int digit = temp % 10;
            sum += Math.pow(digit, digits); // Raise each digit to the power of 'digits'
            temp /= 10;
        }

        // Check if the sum equals the original number
        if (sum == originalNumber) {
            System.out.println(originalNumber + " is an Armstrong number.");
        } else {
            System.out.println(originalNumber + " is not an Armstrong number.");
        }

        // Close the scanner
        scanner.close();
    }
}

    

How to Run the Code:

  1. Copy the code into a Java IDE or text editor.
  2. Compile and run the program.
  3. Enter a number when prompted to check if it is an Armstrong number.

Examples:

  • Input: 153 → Output: 153 is an Armstrong number.
  • Input: 123 → Output: 123 is not an Armstrong number.
  • Input: 2222 → Output: 2222 is not an Armstrong number.

C Program to Check Armstrong Numbers:


#include <stdio.h>
#include <math.h>

int main() {
    int number, originalNumber, remainder, digits = 0, sum = 0;

    // Prompt user for input
    printf("Enter a number: ");
    scanf("%d", &number);

    // Calculate the number of digits
    originalNumber = number;
    while (originalNumber != 0) {
        digits++;
        originalNumber /= 10;
    }

    // Reset originalNumber to the input number
    originalNumber = number;

    // Calculate the sum of powers of each digit
    while (originalNumber != 0) {
        remainder = originalNumber % 10;
        sum += pow(remainder, digits);
        originalNumber /= 10;
    }

    // Check if the number is an Armstrong number
    if (sum == number) {
        printf("%d is an Armstrong number.\n", number);
    } else {
        printf("%d is not an Armstrong number.\n", number);
    }

    return 0;
}

    

How to Run the Code:

  1. Copy the code into a C compiler or IDE.
  2. Compile and run the program.
  3. Enter a number when prompted to check if it is an Armstrong number.

Examples:

  • Input: 153 → Output: 153 is an Armstrong number.
  • Input: 123 → Output: 123 is not an Armstrong number.
  • Input: 2222 → Output: 2222 is not an Armstrong number.

Python Program to Check Armstrong Numbers:


# Function to check if a number is an Armstrong number
def is_armstrong(number):
    # Convert number to string to easily count digits
    digits = len(str(number))
    sum_of_powers = sum(int(digit) ** digits for digit in str(number))
    
    # Check if the sum of the powers equals the original number
    return sum_of_powers == number

# Prompt user for input
number = int(input("Enter a number: "))

# Check and display result
if is_armstrong(number):
    print(f"{number} is an Armstrong number.")
else:
    print(f"{number} is not an Armstrong number.")

    

How to Run the Code:

  1. Copy the code into a Python IDE or text editor.
  2. Run the program.
  3. Enter a number when prompted to check if it is an Armstrong number.

Examples:

  • Input: 153 → Output: 153 is an Armstrong number.
  • Input: 123 → Output: 123 is not an Armstrong number.
  • Input: 9474 → Output: 9474 is an Armstrong number.

Go Program to Check Armstrong Numbers:


package main

import (
	"fmt"
	"math"
)

// Function to check if a number is an Armstrong number
func isArmstrong(number int) bool {
	originalNumber := number
	digits := 0
	sum := 0

	// Count the number of digits
	for temp := number; temp != 0; temp /= 10 {
		digits++
	}

	// Calculate the sum of the digits raised to the power of the number of digits
	for temp := number; temp != 0; temp /= 10 {
		digit := temp % 10
		sum += int(math.Pow(float64(digit), float64(digits)))
	}

	// Check if the sum equals the original number
	return sum == originalNumber
}

func main() {
	var number int

	// Prompt user for input
	fmt.Print("Enter a number: ")
	fmt.Scan(&number)

	// Check and display result
	if isArmstrong(number) {
		fmt.Printf("%d is an Armstrong number.\n", number)
	} else {
		fmt.Printf("%d is not an Armstrong number.\n", number)
	}
}

    

How to Run the Code:

  1. Install the Go programming language if not already installed.
  2. Save the program in a file with the .go extension (e.g., armstrong.go).
  3. Run the program using the go run armstrong.go command.

Examples:

  • Input: 153 → Output: 153 is an Armstrong number.
  • Input: 123 → Output: 123 is not an Armstrong number.
  • Input: 9474 → Output: 9474 is an Armstrong number.

C++ Program to Check Armstrong Numbers:


#include <iostream>
#include <cmath>
using namespace std;

// Function to check if a number is an Armstrong number
bool isArmstrong(int number) {
    int originalNumber = number;
    int digits = 0, sum = 0;

    // Calculate the number of digits
    int temp = number;
    while (temp != 0) {
        digits++;
        temp /= 10;
    }

    // Calculate the sum of the digits raised to the power of the number of digits
    temp = number;
    while (temp != 0) {
        int digit = temp % 10;
        sum += pow(digit, digits);
        temp /= 10;
    }

    // Check if the sum equals the original number
    return sum == originalNumber;
}

int main() {
    int number;

    // Prompt user for input
    cout << "Enter a number: ";
    cin >> number;

    // Check and display result
    if (isArmstrong(number)) {
        cout << number << " is an Armstrong number." << endl;
    } else {
        cout << number << " is not an Armstrong number." << endl;
    }

    return 0;
}

    

How to Run the Code:

  1. Save the code in a file with the .cpp extension (e.g., armstrong.cpp).
  2. Compile the code using a C++ compiler (e.g., g++ armstrong.cpp -o armstrong).
  3. Run the compiled program using the command ./armstrong.

Examples:

  • Input: 153 → Output: 153 is an Armstrong number.
  • Input: 123 → Output: 123 is not an Armstrong number.
  • Input: 9474 → Output: 9474 is an Armstrong number.

C# Program to Check Armstrong Numbers:


using System;

class Program
{
    // Function to check if a number is an Armstrong number
    static bool IsArmstrong(int number)
    {
        int originalNumber = number;
        int digits = 0, sum = 0;

        // Calculate the number of digits
        int temp = number;
        while (temp != 0)
        {
            digits++;
            temp /= 10;
        }

        // Calculate the sum of the digits raised to the power of the number of digits
        temp = number;
        while (temp != 0)
        {
            int digit = temp % 10;
            sum += (int)Math.Pow(digit, digits);
            temp /= 10;
        }

        // Check if the sum equals the original number
        return sum == originalNumber;
    }

    static void Main()
    {
        Console.Write("Enter a number: ");
        int number = int.Parse(Console.ReadLine());

        // Check and display result
        if (IsArmstrong(number))
        {
            Console.WriteLine(number + " is an Armstrong number.");
        }
        else
        {
            Console.WriteLine(number + " is not an Armstrong number.");
        }
    }
}

    

How to Run the Code:

  1. Save the code in a file with the .cs extension (e.g., ArmstrongNumber.cs).
  2. Compile the code using the C# compiler (e.g., csc ArmstrongNumber.cs).
  3. Run the compiled program using the command ArmstrongNumber.

Examples:

  • Input: 153 → Output: 153 is an Armstrong number.
  • Input: 123 → Output: 123 is not an Armstrong number.
  • Input: 9474 → Output: 9474 is an Armstrong number.

Tags

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
✨ Updates