Monday 16 June 2014

C++ programs on Armstrong number

Here are C++  programs to check whether a number is Armstrong or not using while-loop, recursion, function, character string. I have also given program to find Armstrong number between 1 to  n. 


C++ program to check whether a given number is Armstrong or not using while-loop

#include<iostream>
using namespace std;
int main()
{
    int num,x,y=0,temp;
    cout<<"Enter the number ";
    cin>>num;
    temp=num;
    while(num!=0)
    {
        x=num%10;
        y+=x*x*x;
        num/=10;
    }
    if(y==temp)
        cout<<"Number is Armstrong ";
    else
        cout<<"Number is not Armstrong ";
    return 0;
}



C++ program to check whether a given number is Armstrong or not using tail recursion

#include<iostream>
using namespace std;
int arm(int n,int x)
{
    if(n==0)
        return x;
    int y=n%10;
    x+=y*y*y;
    arm(n/10,x);
}
int main()
{
    int num,temp;
    cout<<"Enter the number ";
    cin>>num;
    temp=arm(num,0);
    if(num==temp)
        cout<<"Number is Armstrong ";
    else
        cout<<"Number is not Armstrong ";
    return 0;
}




C++ program to check whether a given number is Armstrong or not using recursion

#include<iostream>
using namespace std;
int arm(int n,int x)
{
    if(n==0)
        return x*x*x;
    return x*x*x+arm(n/10,n%10);
}
int main()
{
    int num,temp;
    cout<<"Enter the number ";
    cin>>num;
    temp=arm(num/10,num%10);
    if(num==temp)
        cout<<"Number is Armstrong ";
    else
        cout<<"Number is not Armstrong ";
    return 0;
}




C++ program to check whether a given number is Armstrong or not using function

#include<iostream>
using namespace std;
int arm(int n)
{
    int x,y=0;
    while(n!=0)
    {
        x=n%10;
        y+=x*x*x;
        n/=10;
    }
    return y;
}
int main()
{
    int num,temp;
    cout<<"Enter the number ";
    cin>>num;
    if(num==arm(num))
        cout<<"Number is Armstrong ";
    else
        cout<<"Number is not Armstrong ";
    return 0;
}



C++ program to check whether a given number is Armstrong or not using character string

#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    char num[5];
    int temp=0,y;
    cout<<"Enter the number ";
    cin>>num;
    for(int i=0;num[i]!='\0';i++)
    {
        y=num[i]-48;
        temp+=y*y*y;
    }
    if(temp==atoi(num))
        cout<<"Number is Armstrong ";
    else
        cout<<"Number is not Armstrong ";
    return 0;
}



C++ program find Armstrong number from 1 to n

#include<iostream>
using namespace std;
int arm(int n)
{
    int x,y=0;
    while(n!=0)
    {
        x=n%10;
        y+=x*x*x;
        n/=10;
    }
    return y;
}
int main()
{
    cout<<"Armstrong number between 1 to 1000\n";
    for(int i=1;i<1000;i++)
       if(i==arm(i))
          cout<<i<<" ";
    return 0;
}

OUTPUT




No comments:

Post a Comment