Ticker

6/recent/ticker-posts

Armstrong Number in C++

Program in C++ To check whether the given number is Armstrong or not :

Armstrong Number: When a number is equal to the sum of the cube of each digit, then it is called an Armstrong Number.

Example: Number 153 is an Armstrong number because:
  1             5            3
= 1*1*1 + 5*5*5 + 3*3*3
=    1     +  125   +   27
=   153 = Number, Hence it is Armstrong number.
The numbers 0, 1, 153, 370, 371 and 407 are some of the Armstrong numbers.

There are various ways to check whether a number is Armstrong or not. The General algorithm for the program is given below :

 Algorithm :


Step 1: Accept a number.
Step 2: Extract each digit and cube it and add it to a variable say sum.
Step 3
 If the sum is equal to a number then display that the number is Armstrong
else display that the number is not Armstrong.
Step 3: Stop

Code 1 :




// C++ program to check whether a given number is an Armstrong number or not

#include <iostream>

using namespace std;

int main()

{

    int numbernumberCopysum = 0;

    cout << "Enter number here: ";

    cin >> number;

    numberCopy = number;

    while (numberCopy > 0)

    {

        int lastDigit = numberCopy % 10;

        int cubeOfLastDigit = lastDigit * lastDigit * lastDigit;

        sum = sum + cubeOfLastDigit;

        numberCopy = numberCopy / 10;
    }

    if (sum == number)

        cout << "The given number " << number << " is an Armstrong Number";

    else

        cout << "The given number " << number << " is not an Armstrong Number";

    return 0;
}





Code 2 :




// C++ program to check whether a given number is an Armstrong number or not

#include <iostream>

#include <string> // included to use stoi function

using namespace std;

int main()

{

    string number;

    int sum = 0;

    cout << "Enter number here: ";

    cin >> number;

    int numberLength = number.length();

    for (int i = 0i < numberLengthi++)

    {

        char c = number.at(i);

        int currentDigit = c - 48;

        int cubeOfDigit = (int)currentDigit * currentDigit * currentDigit;

        sum = sum + cubeOfDigit;
    }

    if (stoi(number) == sum) // stoi function is used to convert string data type to integer data type

        cout << "The given number " << number << " is an Armstrong Number";

    else

        cout << "The given number " << number << " is not an Armstrong Number";

    return 0;
}



If you have any doubt/questions related to Program, or if you want to give any suggestions, feel free to comment below. Don't forget to subscribe and share it with friends.

Post a Comment

0 Comments