Knowee
Questions
Features
Study Tools

#include<math.h> int checkArmstrongNumber(int n) { int originalNumber, remainder, result = 0, count = 0; originalNumber = n; // To get the number of digits while (originalNumber != 0) { originalNumber /= 10; ++count; } originalNumber = n; // Check if the number is an Armstrong number while (originalNumber != 0) { remainder = originalNumber % 10; result += pow(remainder, count); originalNumber /= 10; } if (result == n) return 1; else return result; } Input Your Output Expected Output 371 970554640 1

Question

#include<math.h>

int checkArmstrongNumber(int n) { int originalNumber, remainder, result = 0, count = 0;

originalNumber = n;

// To get the number of digits
while (originalNumber != 0) {
    originalNumber /= 10;
    ++count;
}

originalNumber = n;

// Check if the number is an Armstrong number
while (originalNumber != 0) {
    remainder = originalNumber % 10;
    result += pow(remainder, count);
    originalNumber /= 10;
}

if (result == n)
    return 1;
else
    return result;

} Input Your Output Expected Output 371 970554640 1

...expand
🧐 Not the exact question you are looking for?Go ask a question

Solution

The code you provided is a C function that checks if a given number is an 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.

Here's a step-by-step explanation of the function:

  1. The function checkArmstrongNumber(int n) takes an integer n as input.

  2. It initializes originalNumber to n, remainder and result to 0, and count to 0. count is used to store the number of digits in n.

  3. The first while loop is used to count the number of digits in n. It repeatedly divides originalNumber by 10 until originalNumber is 0, incrementing count each time.

  4. originalNumber is then reset to n.

  5. The second while loop is used to check if n is an Armstrong number. It repeatedly does the following until originalNumber is 0:

    • It sets remainder to the last digit of originalNumber (i.e., originalNumber % 10).
    • It adds remainder raised to the power of count to result (i.e., result += pow(remainder, count)).
    • It removes the last digit from originalNumber (i.e., originalNumber /= 10).
  6. Finally, if result is equal to n, the function returns 1, indicating that n is an Armstrong number. Otherwise, it returns result.

The input and output you provided suggest that the function is working correctly for the input 371, which is an Armstrong number (since 3^3 + 7^3 + 1^3 = 371). However, the function seems to be returning a large number (970554640) for some other input, which is not shown. This could be due to an overflow error if the input number has too many digits.

This problem has been solved

Similar Questions

0/0

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.