Problem: Our Armstrong number
Please write code for C language
So far we have worked on obtaining individual digits from 4 digits or 5 digit numbers. Then added them to find the sum of digits in various examples and assignments.
However, the process of extracting individual digits is actually can be solved using a loop as you were doing a repetitive task by using mod operation and division operation. Now, we know how loops work and we can remove the limit of having a specific number of digits using loops.
Write a program to print out all Armstrong numbers between 1 and n where n will be a user input.
Our definition of Armstrong number:
If the sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number.
For example, 153 = (1 * 1 * 1 ) + ( 5 * 5* 5 ) + ( 3 * 3 * 3 )
In order to solve this problem you will implement the following function:
sumDigitCube() : write a function sumDigitCube() that takes a positive integer as a parameter and returns the sum of cube of each digit of the number.
Then in the main function, take an integer n (n>=1) as input and generate each number from 1 to n and call the sumDigitCube() function.
Based on the returned result, compares it with the value of the generated number and take a decision and print the number if it is Armstrong number.
Note that we could actually use a nested loop to solve this problem. You will see how the use of function in this process makes the code simpler!
Sample Input/output:
Enter a number: 500
The Armstrong numbers are:
1
153
370
371
407
Note: Could you plz go through this code and let me
know if u need any changes in this.Thank You
=================================
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
int sumDigitCube(int number);
int main()
{
// Declaring variables
int n;
// getting the input entered by the user
printf("Enter a number :");
scanf("%d", &n);
printf("The Armstrong numbers are:\n");
// Displaying the Armstrong numbers
for (int i = 1; i <= n; i++)
{
if (i == sumDigitCube(i))
{
printf("%d\n", i);
}
}
return 0;
}
/*
* This function will calculate the
* sum of cube of each digit in a number
*/
int sumDigitCube(int number)
{
// Declaring variables
int rem = 0, tot = 0;
/* This while loop will get executes
* until the number is greater than zero
*/
while (number > 0)
{
rem = number % 10;
tot += pow(rem, 3);
number = number / 10;
}
return tot;
}
=====================================
=====================================
Output:
=====================Could you plz rate me well.Thank You
Get Answers For Free
Most questions answered within 1 hours.