Python/C/C++/JAVA

Basic Practice Programs with Code and Concept

By D.S

Armstrong Numbers

Hey there! Before we dive into writing a program to check if a number is an Armstrong number, let's first understand what an Armstrong number is. Basically, an Armstrong number is a number that is equal to the sum of the cubes of its digits. Cool, right? Some examples of Armstrong numbers include 0, 1, 153, 370, 371, and 407. Now that we've got that covered, let's get to coding!

(a.) C Code

#include <stdio.h>
int main() {
  int num, originalNum, remainder, result = 0;
  printf("Enter an integer: ");
  scanf("%d", &num);
  originalNum = num;

  while (originalNum != 0) {
    remainder = originalNum % 10;
    result += remainder * remainder * remainder;
    originalNum /= 10;
  }

  if (result == num)
    printf("%d is an Armstrong number.", num);
  else
    printf("%d is not an Armstrong number.", num);

  return 0;
}
    
Output:-
Enter an integer: 153
153 is an Armstrong number.

(b.) C++ Code

#include <iostream>
using namespace std;

int main() {
  int num, originalNum, remainder, result = 0;
  cout << "Enter an integer: ";
  cin >> num;
  originalNum = num;

  while (originalNum != 0) {
    remainder = originalNum % 10;
    result += remainder * remainder * remainder;
    originalNum /= 10;
  }

  if (result == num)
    cout << num << " is an Armstrong number." << endl;
  else
    cout << num << " is not an Armstrong number." << endl;

  return 0;
}
    
Output:-
Enter an integer: 153
153 is an Armstrong number.

(c.) Python Code

num = int(input("Enter an integer: "))
sum = 0
temp = num

while temp > 0:
    digit = temp % 10
    sum += digit ** 3
    temp //= 10

if num == sum:
    print(num, "is an Armstrong number.")
else:
    print(num, "is not an Armstrong number.")
    
Output:-
Enter an integer: 153
153 is an Armstrong number.

(d.) Java Code

import java.util.Scanner;

public class ArmstrongNumber {
  public static void main(String[] args) {
    int num, originalNum, remainder, result = 0;
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter an integer: ");
    num = scanner.nextInt();
    originalNum = num;

    while (originalNum != 0) {
      remainder = originalNum % 10;
      result += Math.pow(remainder, 3);
      originalNum /= 10;
    }

    if (result == num)
      System.out.println(num + " is an Armstrong number.");
    else
      System.out.println(num + " is not an Armstrong number.");
  }
}
    
Output:-
Enter an integer: 153
153 is an Armstrong number.