Basically we will be learning how to add first digit and last digit of three digit number using java.
Initially we should take a 3 digit number.We can use Scanner class of util package to take user input.
After taking 3 digit number from user, we should save that number in a variable n. Take another variable num and save the contents of n in num.
Now To get first digit ,we should divide the number by 100.
For example: If we take 3 digit number as 645 ,To get first digit we should divide the number by 100( 645/100=>6).
To get first digit,as we have to divide the number by 100,first take a while loop and run the loop until the number becomes 0.We are using the while loop,to get the count of 3 digit number.As loop runs ,count becomes 3.
Now we are taking another for loop and a variable r which is initialized to 1.As the for loop runs,the value of r becomes 1000 as count =3.
Now we should divide 645/100. so that we get first digit 6. save this number in d variable. To get last digit, get the remainder(n%10) and save in re variable.
Take another variable sum and add d and re.
print sum.
class ad { public static void main(String args[]) { int count=0, r=1 ,d,sum=0,re,num; Scanner s=new Scanner(System.in); System.out.println("Enter three digit number:"); int n=s.nextInt(); num=n; while(num!=0) { num=num/10; count++; } for(int i=1;i<count;i++) { r=r*10; } d=n/r; re=n%10; sum=d+re; System.out.println("Sum="+sum); } }
Enter three digit number:
645
Sum=11
Submitted by Ginna Srilekha (ginnasrilekha)
Download packets of source code on Coders Packet
Comments