C Exercises: Check whether a given number is an armstrong number or not
C For Loop: Exercise-29 with Solution
Write a C program to check whether a given number is an Armstrong number or not.
When the sum of the cube of the individual digits of a number is equal to that number, the number is called Armstrong number. For Example 153 is an Armstrong number because 153 = 13+53+33.
Test Data :
Input a number: 153
Expected Output :
153 is an Armstrong number.
Sample Solution:
C Code:
#include <stdio.h> // Include the standard input/output header file.
void main(){
int num, r, sum=0, temp; // Declare variables for the input number, remainder, sum, and a temporary variable.
printf("Input a number: "); // Prompt the user to input a number.
scanf("%d",&num); // Read the number from the user.
for(temp=num;num!=0;num=num/10){ // Start a loop to extract digits from the number.
r=num % 10; // Get the last digit of the number.
sum=sum+(r*r*r); // Calculate the sum of cubes of each digit.
}
if(sum==temp) // If the sum of cubes of digits is equal to the original number.
printf("%d is an Armstrong number.\n",temp); // Print that it's an Armstrong number.
else
printf("%d is not an Armstrong number.\n",temp); // Otherwise, print that it's not an Armstrong number.
}
Sample Output:
Input a number: 153 153 is an Armstrong number.
Flowchart:
C Programming Code Editor:
Previous: Write a c program to find the perfect numbers within a given number of range.
Next: Write a C program to find the Armstrong number for a given range of number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics