Header Ads Widget

Write a C program to print out all the Armstrong number between 100 and 500.

 

 C program to print out all the Armstrong number between 100 and 500

Here we have to write a C program to print out all the Armstrong numbers between 100 to 500 . So first we have to know what is Armstrong number ? 

An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits. In other words, if we take an n-digit number and raise each of its digits to the nth power, and add these values together, the result is equal to the original number.

For example, the number 153 is an Armstrong number because it has three digits and:

1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Similarly, 371 is also an Armstrong number because:

3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371

Armstrong numbers are also called narcissistic numbers or pluperfect digital invariants.

 C program to print out all the Armstrong number between 100 and 500

The objective of the code is to print all the Armstrong number between 100 to 300 .

Algorithm :

  1. Start iterating from 100 to 500.
  2. For each number, find the number of digits in it.
  3. Compute the sum of digits raised to the power of the number of digits.
  4. Compare the computed sum with the original number.
  5. If the computed sum is equal to the original number, then print the number as it is an Armstrong number.
  6. Continue with the iteration until all numbers from 100 to 500 are checked.

Code(C):-


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

int main() {
int i, num, digit, sum;
for (i = 100; i <= 500; i++) {
num = i;
sum = 0;
while (num > 0) {
digit = num % 10;
sum += pow(digit, 3);
num /= 10;
}
if (sum == i) {
printf("%d ", i);
}
}
return 0;
}


Output:

153 370 371 407

Explanation:

The above program uses a for loop to iterate through all numbers from 100 to 500. For each number, it computes the sum of its digits raised to the power of the number of digits using a while loop. If the computed sum is equal to the original number, then the number is an Armstrong number, and it is printed.

In the while loop, the modulus operator is used to extract the last digit of the number. The pow() function from the math.h library is used to raise the digit to the power of 3. The sum of these cubes is computed for each digit. The integer division operator is used to remove the last digit from the number.

Finally, the program terminates after printing all Armstrong numbers between 100 and 500.


Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-

Post a Comment

0 Comments