Armstrong numbers

Java program to display Armstrong number using for, while, method and in given range.

There are different ways to display Armstrong number in Java.
  1.          Armstrong numbers from 1 to 1000
  2.          Armstrong number using Method
  3.          Armstrong number using For loop
  4.          Armstrong number using while loop

public class Armstrong1to1000 {
	public static void main(String[] args) {
		System.out.println("Amstrong Numbers From 1 to 1000");
		int a,r;
		for(int i=1; i<=1000;i++)
		{
			a=0;
			int n=i;
			while(n!=0) 
			{
				r=n%10;
				a=a+r*r*r;
				n=n/10;
			}
			if(a==i)
			{
				System.out.println(i);
			}
		}
	}
}

OUTPUT:

Amstrong Numbers From 1 to 1000
1
153
370
371
407
import java.util.Scanner;
public class ArmstrongMethod 
{
	void Amg(int n)
	{
		int reminder,amstrong=0,temp=n;
		while(n!=0)			
		{
			reminder=n%10;
			amstrong=amstrong+reminder*reminder*reminder;
			n=n/10;
		}
	if(temp==amstrong)
		System.out.println("\n"+temp+" is an amstrong number");
	else	
		System.out.println("\n"+temp+" is not an amstrong number");
	}
	public static void main(String[] args) 
	{
		AmstrongMethod obj = new AmstrongMethod();
		Scanner scan = new Scanner(System.in);
		System.out.println("\nEnter a Number: ");
		int n = scan.nextInt();
		obj.Amg(n);
	}
}

OUTPUT:

Enter a Number: 
591

591 is not an amstrong number

OUTPUT 2:

Enter a Number: 
370

370 is an amstrong number
import java.util.Scanner;
public class ArmstrongFor {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.println("\nEnter a Number: ");
		int n = scan.nextInt();
		int reminder,amstrong=0,temp=n;
			for(;n>0;)			
			{
				reminder=n%10;
				amstrong=amstrong+reminder*reminder*reminder;
				n=n/10;
			}
		if(temp==amstrong)
		{
			System.out.println("\n"+temp+" is an amstrong number");
		}
		else
		{
			System.out.println("\n"+temp+" is not an amstrong number");
		}
	}
}

OUTPUT:

Enter a Number: 
591

591 is not an amstrong number

OUTPUT 2:

Enter a Number: 
370

370 is an amstrong number
import java.util.*;
public class Armstrong {
	public static void main(String[] args) 	{
		Scanner scan = new Scanner(System.in);
		System.out.println("\nEnter a Number: ");
		int n = scan.nextInt();
		int reminder,amstrong=0,temp=n;
			while(n!=0)			
			{
				reminder=n%10;
				amstrong=amstrong+reminder*reminder*reminder;
				n=n/10;
			}
		if(temp==amstrong)
		{
		System.out.println("\n"+temp+" is an amstrong number");
		}
		else
		{
		System.out.println("\n"+temp+" is not an amstrong number");
		}
	}
}

OUTPUT 1:

Enter a Number: 
591

591 is not an amstrong number

OUTPUT 2:

Enter a Number: 
370

370 is an amstrong number

No comments:

Post a Comment

If you have any doubts, please let me know

Pattern 31 & 32