JAVA program to generate first n armstrong numbers

JAVA program to generate first n armstrong numbers

This JAVA program is to generate first n armstrong numbers.

For example if we want to generate first 2 armstrong numbers  then we get 153, 370 as the output.

Logic

The only difference between to check if the number is armstrong no or not and this program is the while loop.We take this loop and as soon as we get the desired nos of armstrong nos , the loop terminates.

Dry Run of the Program

Check here it is almost same as to check if the given number is an armstrong number or not.Even if you don’t understand then just mail me I will be more than happy to help you.

Program

import java.util.*;

class armstrongNos
{
	public static void main(String args[])
	{
		int n,copy=152,remainder,sum,x;
		Scanner sc = new Scanner(System.in);

		System.out.println("Enter the number");
    		n=sc.nextInt();

    		//starting copy from 152 as we know 153 is an armstrong no

		System.out.println("First "+n+" armstrong numbers are");
    		while(n!=0)
    		{	
        		copy++;
       	 		x=copy;
        		sum=0;
		        while(copy!=0)
        		{
            			remainder=copy%10;
            			sum=sum+remainder*remainder*remainder;
            			copy=copy/10;
        		}
        		if(sum==x)
        		{
            			System.out.print(x+" ");
            			n--;
        		}
        		copy=x;
    		}
	}
}

Output

Share Me!