Computer Science, asked by behera98rakesh, 1 month ago

write a program in java to input two digit numbers find the sum of first and last number​

Answers

Answered by anindyaadhikari13
4

Answer:

Using Java, the co‎de goes like -

import java.util.*;

class Sum{

   public static void main(String args[]){

       Scanner sc=new Scanner(System.in);

       int number, first_digit, last_digit,sum;

       System.out.print("Enter a two digit number: ");

       number=sc.nextInt();

       if(number>9&&number<100)    {

           first_digit=number/10;

           last_digit=number%10;

           sum=first_digit+last_digit;

           System.out.println("Sum of first and last digit of the number is: "+sum);

       }

       else

           System.out.println("Invalid Input.");

       sc.close();

   }

}

Logic:

  • Logic is very simple. Consider a number, - 99. If we divide 99 by 10, we get quotient as 9 and remainder as 9. So, to find out the first digit of the number, we will divide the number by 10 store the result in a variable say first_digit. Also, to calculate the last digit, we will perform modulo division. To get remainder, the modulo (%) operator is used.
  • 99%10 gives 9 as output as 99 divided by 10 leaves 9 as remainder.
  • Now, we have found the first and last digit. We will add them up and display them.
  • Note: We have to check if the entered number is a two digit number or not.

See the attachment.

•••♪

Attachments:
Answered by kamalrajatjoshi94
0

Answer:

import java.util.*;

public class Brainly_Answer

{

public static void main(String args[ ])

{

Scanner in=new Scanner(System.in);

int n,s=0,a=0;

System.out.println("Enter the two digit number");

n=in.nextInt();

if(n>=10&&n<100)

{

while(n!=0)

{

a=n%10;

s=s+a;

n=n/10;

}

System.out.println("The sum of first and last digit="+s);

}

else

{

System.out.println("Invalid input");

}

in.close();

}

}

  • The first photo is the program
  • The second photo is the input I.e(89)
  • The third photo is the output for a two digit number
  • The fourth photo is the input for a three digit number
  • The fifth is the output for that number

Logic:-

  • The logic is simple a=n%10; is used to calculate the remainder and n=n/10 is used to calculate each remainder at each iteration and finally we add that and calculate the sum and display it.
  • If you not enter a two digit number it will display the number as invalid input.
Attachments:
Similar questions