Write a function to print all Armstrong numbers between given interval in C programming. How to print all Armstrong numbers in given range using functions in C programming. C function to print all Armstrong numbers from 1 to n.
Example
Input
Input lower limit: 1 Input upper limit: 1000
Output
Armstrong numbers between 1 to 1000 are: 1, 153, 370, 371, 407,
Required knowledge
Basic C programming, If else, While loop, Functions
Must know –
Declare function to print Armstrong numbers in given range
- First give a meaningful name to function. Say
printArmstrong()
function prints all Armstrong numbers in given range. - Next the function prints Armstrong number in given range. Hence, we must pass two integer parameters to the function, say
printArmstrong(int start, int end);
. - Finally the function prints all Armstrong numbers in given range returning nothing. Therefore, return type of the function must be
void
.
The final function declaration to print all Armstrong numbers in given range is – void printArmstrong(int start, int end);
.
Program to print Armstrong numbers using function
/**
* C program to print all Armstrong numbers between a given range
*/
#include <stdio.h>
/* Function declarations */
int isArmstrong(int num);
void printArmstrong(int start, int end);
int main()
{
int start, end;
/* Input lower and upper limit to of armstrong numbers */
printf("Enter lower limit to print armstrong numbers: ");
scanf("%d", &start);
printf("Enter upper limit to print armstrong numbers: ");
scanf("%d", &end);
printf("All armstrong numbers between %d to %d are: \n", start, end);
printArmstrong(start, end);
return 0;
}
/**
* Check whether the given number is armstrong number or not.
* Returns 1 if the number is armstrong otherwise 0.
*/
int isArmstrong(int num)
{
int temp, lastDigit, sum;
temp = num;
sum = 0;
/* Calculate sum of cube of digits */
while(temp != 0)
{
lastDigit = temp % 10;
sum += lastDigit * lastDigit * lastDigit;
temp /= 10;
}
/*
* Check if sum of cube of digits equals
* to original number.
*/
if(num == sum)
return 1;
else
return 0;
}
/**
* Print all armstrong numbers between start and end.
*/
void printArmstrong(int start, int end)
{
/*
* Iterates from start to end and print the current number
* if it is armstrong
*/
while(start <= end)
{
if(isArmstrong(start))
{
printf("%d, ", start);
}
start++;
}
}
Output
Enter lower limit to print armstrong numbers: 1 Enter upper limit to print armstrong numbers: 1000 All armstrong numbers between 1 to 1000 are: 1, 153, 370, 371, 407,
Happy coding 😉
Recommended posts
- Function and recursion programming exercise index.
- C program to find prime numbers in given range using function.
- C program to find strong numbers in given range using function.
- C program to find perfect numbers in given range using function.
- C program to check even number using function.
- C program to print all natural numbers in given range using recursion.