w3resource

C Exercises: Check whether an n digits number is Armstrong or not

C For Loop: Exercise-59 with Solution

Write a C program to check the Armstrong number of n digits.

Visual Presentation:

Check whether an n digits number is Armstrong or not

Sample Solution:

C Code:

#include <stdio.h>   // Include the standard input/output header file. 

#include <math.h>     // Include the math header file.
int main()
{
    // Variable declarations
int n1, onum, r, result = 0, n = 0 ;
    // Prompting user for input
printf("\n\n Check whether an n digits number is armstrong or not :\n");
printf("-----------------------------------------------------------\n"); 	
printf(" Input an integer : ");
scanf("%d", &n1);
    // Store the original number for later comparison
onum = n1;
    // Count the number of digits in the input number
while (onum != 0)
    {
onum /= 10;
        ++n;
    }
    // Reset onum to the original number for further processing
onum = n1;
    // Calculate the sum of cubes of individual digits raised to the power of 'n'
while (onum != 0)
    {
        r = onum % 10;
result += pow(r, n);
onum /= 10;
    }
    // Check if the result is equal to the original number
if(result == n1)
printf(" %d is an Armstrong number.\n\n", n1);
else
printf(" %d is not an Armstrong number.\n\n", n1);
return 0;
}

Sample Output:

 Check whether an n digits number is Armstrong or not :                                                       
-----------------------------------------------------------                                                   
 Input  an integer : 1634                                                                                     
 1634 is an Armstrong number.                                                                                                           

Flowchart:

Flowchart : Check whether an n digits number is armstrong or not

C Programming Code Editor:

Previous: Find the length of a string without using the library function.
Next: Counts the number of characters left in the file.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.