Write a program in Java to calculate the sum of first and last digits of a given number.

 Write a program to calculate the sum of first and last digits of a given number.




import java.util.Scanner;

class SumOfFirst_LastDigit

{

 public static void main(String[] args) 

  {

       int n,d,t,dc=0,firstDigit,lastDigit,sum=0;

       Scanner scr=new Scanner(System.in);

       System.out.println("Enter any number ");

       n=scr.nextInt();

       t=n;

       while(t>0)

       {

        d=t%10;

        dc++;

        t=t/10;

       }

       firstDigit=(n/(int)(Math.pow(10,dc-1)));

       lastDigit=n%10;

       System.out.println("first digit : " +firstDigit);

       System.out.println("last Digit : " +lastDigit);

       sum=firstDigit+lastDigit;      

       System.out.println("Sum of digits = " +sum);

   }

}

Output




Post a Comment

0 Comments