JAVA program to generate armstrong numbers from 1 to n
This JAVA program is to generate armstrong numbers from 1 to n.
For Example generate armstrong numbers upto 200.
Then we will have only 1 armstrong number i.e 153 in the range of 1 to 200.
Logic
The procedure is same as to check if the given number is an armstrong number or not , only in this case an additional while loop will be there to generate armstrong numbers upto n.
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 write down in the comment section, I will be more than happy to help you.
Program
import java.util.*; class armstrongN { 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("Armstrong numbers are"); while(copy<=n) { 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