C Online Compiler
Example: Check Armstrong Number in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Check Armstrong Number #include <stdio.h> #include <math.h> // Required for pow() // Function to check if a number is an Armstrong number int isArmstrong(int num) { int originalNum, remainder, n = 0; double result = 0.0; // Step 1: Store the original number originalNum = num; // Step 2: Count the number of digits (n) // For single digit numbers, the power is 1. // For multi-digit numbers, count the digits int tempNum = num; while (tempNum != 0) { tempNum /= 10; n++; } // Handle case for 0 (0 is technically an Armstrong number) if (num == 0) return 1; // Special handling for n=0 (when num was 0), set to 1 for correct power calc if (n == 0) n = 1; // Step 3: Calculate the sum of nth powers of its digits tempNum = num; // Reset tempNum to the original number for digit extraction while (tempNum != 0) { remainder = tempNum % 10; // Get the last digit result += pow(remainder, n); // Add digit raised to the power of n tempNum /= 10; // Remove the last digit } // Step 4: Compare the result with the original number if ((int)result == originalNum) { return 1; // Armstrong number } else { return 0; // Not an Armstrong number } } int main() { int number = 153; // Example number if (isArmstrong(number)) { printf("%d is an Armstrong number.\n", number); } else { printf("%d is not an Armstrong number.\n", number); } number = 123; // Another example if (isArmstrong(number)) { printf("%d is an Armstrong number.\n", number); } else { printf("%d is not an Armstrong number.\n", number); } return 0; }
Output
Clear
ADVERTISEMENTS